diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index b053859..2154b80 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -5,6 +5,7 @@ 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 @@ -34,6 +35,7 @@ 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 CAPABILITIES = ( "cultcache.mirror.publish", @@ -440,6 +442,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 "" @@ -462,7 +465,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], } @@ -767,7 +770,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, @@ -786,7 +789,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), + "evaluated": self._evaluated_snapshot(obj, scan), "customProperties": self._custom_properties(obj.items()), } @@ -808,32 +811,59 @@ class BrokkrBlenderTarget: "shapeKeyCount": len(mesh.shape_keys.key_blocks) if mesh.shape_keys else 0, } - def _evaluated_snapshot(self, obj: Any) -> dict[str, Any] | None: - """What the modifier stack produced, for objects that have one: counts, bounds, and positions up to a cap. - A Geometry Nodes object's own mesh is empty, so the base mesh counts say nothing about it.""" - if obj.type != "MESH" or not len(obj.modifiers): - return None + 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]] = {} + for item in depsgraph.object_instances: + 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 + + 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 = scan evaluated = obj.evaluated_get(depsgraph) mesh = evaluated.to_mesh() try: - vertices = [tuple(round(c, 5) for c in v.co) for v in mesh.vertices] - counts = {"vertexCount": len(vertices), "edgeCount": len(mesh.edges), "polygonCount": len(mesh.polygons)} + 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() - instances = [tuple(round(c, 5) for c in i.matrix_world.translation) for i in depsgraph.object_instances - if i.is_instance and i.parent is not None and i.parent.original == obj] - cloud = vertices + instances - return { - **counts, - "instanceCount": len(instances), - "boundsMin": [min(p[axis] for p in cloud) for axis in range(3)] if cloud else [], - "boundsMax": [max(p[axis] for p in cloud) for axis in range(3)] if cloud else [], - "vertexLocations": [list(p) for p in vertices[:EVALUATED_POSITION_CAP]], - "instanceLocations": [list(p) for p in instances[:EVALUATED_POSITION_CAP]], - "truncated": len(vertices) > EVALUATED_POSITION_CAP or len(instances) > EVALUATED_POSITION_CAP, - } + entry = found.get(obj.name) 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({ + "instanceCount": entry["count"], + "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 { diff --git a/surfaces/blender/brokkr_bridge/node_actions.py b/surfaces/blender/brokkr_bridge/node_actions.py index 83fadf6..cfce6a5 100644 --- a/surfaces/blender/brokkr_bridge/node_actions.py +++ b/surfaces/blender/brokkr_bridge/node_actions.py @@ -13,16 +13,17 @@ 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}$") +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 or nest groups are not part of this cut. -NODE_IDNAME = re.compile(r"^(GeometryNode|FunctionNode|ShaderNode)[A-Za-z0-9]+$") +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") 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"} @@ -41,7 +42,7 @@ def text(command: dict[str, Any], key: str, pattern: re.Pattern, label: str, *, if required: raise ActionRefused(f"{label} is required.") return "" - if not isinstance(value, str) or not pattern.match(value): + if not isinstance(value, str) or not pattern.fullmatch(value): raise ActionRefused(f"{label} must be 1..63 characters of letters, digits, '.', '_' or '-'.") return value @@ -65,8 +66,8 @@ def typed_value(value: Any, kind: str, label: str) -> Any: return finite(value, label) if kind in ("INT", "Int"): number = finite(value, label) - if number != int(number): - raise ActionRefused(f"{label} must be a whole number.") + 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): @@ -81,7 +82,7 @@ def typed_value(value: Any, kind: str, label: str) -> Any: def check_idname(idname: Any) -> str: - if not isinstance(idname, str) or not NODE_IDNAME.match(idname): + 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: @@ -233,9 +234,12 @@ class NodeActions: 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") - link = tree.links.new(out, into) + displaced = [l.from_socket 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 in displaced: + tree.links.new(old, into) 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 @@ -260,6 +264,8 @@ class NodeActions: 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 @@ -290,10 +296,12 @@ def modifier_input(tree: Any, key: str) -> Any: def drives_modifier_input(obj: Any, property_name: str) -> str: - """The modifier whose group has an interface input called property_name (identifier or name), else ''.""" + """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 in (item.identifier, item.name): + 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 index 36d331d..d0b7d56 100644 --- a/surfaces/blender/docs/node-actions.md +++ b/surfaces/blender/docs/node-actions.md @@ -9,20 +9,26 @@ Design and the parts not built yet: `docs/blender-node-graphs.md` (on `libby/ble |---|---|---| | `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. | -| `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. | +| `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); cycles and self links are not detected here. | | `addModifier` | `objectName`, `treeKey`, `modifierName?` (default `Brokkr GeoNodes`) | `NODES` only. Reuses a modifier of that name; at most 8 per object. | | `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 named like an input of a Geometry Nodes modifier on that -object (it never drove the modifier); other custom properties are unchanged. +`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`, bounds, and up to 256 vertex and instance locations (`truncated` when cut). -It is the evaluated result; `mesh` stays the base mesh. +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. +`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. Not built: zones, item sockets, multi-input ordering, removal and unlink actions, library groups, -group-in-group nodes, batches/rollback across intents, an expectedRevision check. Residual risk: values -that make evaluation expensive (a huge `Vertices` count) are bounded only to +-1e9; the snapshot evaluates -every object with modifiers each time it runs. +group-in-group nodes, batches/rollback across intents, an expectedRevision check. Int values are capped at +-4096 and floats at +-1e9, which bounds a request but not the cost of a graph +(a 4096 x 4096 grid is 16M vertices): Blender evaluates what it is given, and the snapshot evaluates every mesh +with modifiers on each capture. There is no removal or unlink action yet, so a heavy graph stays until the +user removes it in Blender. `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 index 78fe8fb..368f53a 100644 --- a/surfaces/blender/tests/live/gn_actions.py +++ b/surfaces/blender/tests/live/gn_actions.py @@ -93,11 +93,11 @@ 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="Count", value=3) -check("custom property on a modifier input is refused", r["status"] == "failed" and "setModifierInput" in r["message"], r["message"]) +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="tag", value=3) -check("other custom properties still accepted", r["status"] == "accepted", r["message"]) +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 @@ -158,6 +158,33 @@ r = act(t, action="linkSockets", treeKey="Scatter", fromNode="cone", fromSocket= 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) + 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") diff --git a/surfaces/blender/tests/live/gn_actions.result.json b/surfaces/blender/tests/live/gn_actions.result.json index d90e0b5..59a5f0b 100644 --- a/surfaces/blender/tests/live/gn_actions.result.json +++ b/surfaces/blender/tests/live/gn_actions.result.json @@ -200,9 +200,9 @@ ] }, { - "name": "custom property on a modifier input is refused", + "name": "custom property naming a modifier input identifier is refused", "ok": true, - "detail": "'Count' is an input of Geometry Nodes modifier 'GN'; a custom property does not drive it, use setModifierInput." + "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", @@ -210,7 +210,7 @@ "detail": null }, { - "name": "other custom properties still accepted", + "name": "a custom property sharing only a display name is ordinary", "ok": true, "detail": "Blender custom property updated." }, @@ -456,6 +456,316 @@ "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, '.', '_' 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, + "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, + "positionsSkipped": false, + "nonFinite": true, + "vertexBoundsMin": [], + "vertexBoundsMax": [], + "vertexLocations": [], + "instanceBoundsMin": [], + "instanceBoundsMax": [], + "instanceLocations": [], + "truncated": false + } } ] } \ No newline at end of file diff --git a/surfaces/blender/tests/test_node_actions.py b/surfaces/blender/tests/test_node_actions.py index 556075f..2a26ea2 100644 --- a/surfaces/blender/tests/test_node_actions.py +++ b/surfaces/blender/tests/test_node_actions.py @@ -8,6 +8,7 @@ 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" @@ -64,7 +65,9 @@ class Links(list): self.valid = valid def new(self, a, b): - link = NS(from_socket=a, to_socket=b, is_valid=self.valid) + 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, is_valid=self.valid(a, b) if callable(self.valid) else self.valid) self.append(link) return link @@ -108,10 +111,14 @@ class Inputs: class Modifiers(list): + refuses = False + def get(self, name): return next((m for m in self if m.name == name), None) 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 @@ -301,15 +308,22 @@ class NodeActionTests(unittest.TestCase): self.assertEqual(host.modifiers[0].properties.inputs.Socket_1.value, 1.5) # setObjectCustomProperty on a Geometry Nodes host - def test_custom_property_naming_a_modifier_input_is_refused(self): + 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 ("Count", "Socket_1", "customProperties.Count"): + 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"] @@ -317,25 +331,97 @@ class NodeActionTests(unittest.TestCase): 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_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 test_evaluated_snapshot_reports_counts_bounds_and_cap(self): + def snapshot_fixture(self, coords, instances): host = self.bpy.data.objects["Host"] host.modifiers.new("GN", "NODES") - verts = [NS(co=(float(i), 0.0, 0.0)) for i in range(3)] - mesh = NS(vertices=verts, edges=[1], polygons=[]) + + 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 - instances = [NS(is_instance=True, parent=NS(original=host), matrix_world=NS(translation=(0.0, 5.0 + i, 0.0))) for i in range(bt.EVALUATED_POSITION_CAP + 2)] - instances.append(NS(is_instance=True, parent=NS(original=Obj("other")), matrix_world=NS(translation=(9.0, 9.0, 9.0)))) - instances.append(NS(is_instance=False, parent=None, matrix_world=NS(translation=(8.0, 8.0, 8.0)))) self.bpy.context = NS(evaluated_depsgraph_get=lambda: NS(update=lambda: None, object_instances=instances)) - data = self.target._evaluated_snapshot(host) - self.assertEqual((data["vertexCount"], data["edgeCount"], data["instanceCount"]), (3, 1, bt.EVALUATED_POSITION_CAP + 2)) - self.assertEqual((data["boundsMin"], data["boundsMax"]), ([0.0, 0.0, 0.0], [2.0, 5.0 + bt.EVALUATED_POSITION_CAP + 1, 0.0])) + 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_object_without_modifiers_has_no_evaluated_block(self): - self.assertIsNone(self.target._evaluated_snapshot(self.bpy.data.objects["Host"])) + self.assertIsNone(self.target._evaluated_snapshot(self.bpy.data.objects["Host"], None)) + self.assertIsNone(self.target._evaluated_snapshot(self.bpy.data.objects["Host"], (None, {}))) if __name__ == "__main__":