From a9e409ef64677f3da8c1a11b17cae95d050a9ee7 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 00:55:10 +0000 Subject: [PATCH 01/14] test: characterize native input defaults and connected constants --- .../blender/test_consumer_aware_constants.py | 217 ++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 tests/blender/test_consumer_aware_constants.py diff --git a/tests/blender/test_consumer_aware_constants.py b/tests/blender/test_consumer_aware_constants.py new file mode 100644 index 0000000..5efde22 --- /dev/null +++ b/tests/blender/test_consumer_aware_constants.py @@ -0,0 +1,217 @@ +"""Blender 5.2 reference behavior for constant-input and absent-input semantics. + +These tests deliberately construct Blender nodes without using the NodeForge +compiler. They are the behavioral oracle for later consumer-aware delivery. +""" + +import bpy +import pytest + + +def _fixture(name): + """Create an evaluated Geometry Nodes modifier and a cube geometry source.""" + group = bpy.data.node_groups.new(name + "_tree", "GeometryNodeTree") + group.interface.new_socket(name="Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry") + output = group.nodes.new("NodeGroupOutput") + cube = group.nodes.new("GeometryNodeMeshCube") + cube.inputs["Size"].default_value = (2, 3, 4) + mesh = bpy.data.meshes.new(name + "_mesh") + obj = bpy.data.objects.new(name + "_object", mesh) + bpy.context.collection.objects.link(obj) + modifier = obj.modifiers.new("GeometryNodes", "NODES") + modifier.node_group = group + return group, cube, output, obj, mesh + + +def _positions(obj): + """Read evaluated mesh vertices without retaining a depsgraph mesh.""" + bpy.context.view_layer.update() + evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()) + mesh = evaluated.to_mesh() + try: + return tuple(sorted(tuple(round(float(c), 5) for c in v.co) for v in mesh.vertices)) + finally: + evaluated.to_mesh_clear() + + +def _cleanup(group, obj, mesh, *other_groups): + """Release transient test datablocks and the modifier's object.""" + bpy.data.objects.remove(obj, do_unlink=True) + bpy.data.meshes.remove(mesh, do_unlink=True) + for item in (group, *other_groups): + bpy.data.node_groups.remove(item, do_unlink=True) + + +@pytest.mark.parametrize( + "node_type,input_name,source_name,output_name,source_output", + [ + ("GeometryNodeSetPosition", "Position", "Geometry", "Geometry", "Mesh"), + ("GeometryNodeMeshToPoints", "Position", "Mesh", "Points", "Mesh"), + ], +) +def test_hidden_position_absence_differs_from_connected_zero( + node_type, input_name, source_name, output_name, source_output +): + """Unlinked position fields differ from an explicit connected zero Vector.""" + name = "NFRef_" + node_type + group, cube, output, obj, mesh = _fixture(name) + try: + consumer = group.nodes.new(node_type) + group.links.new(cube.outputs[source_output], consumer.inputs[source_name]) + if node_type == "GeometryNodeMeshToPoints": + convert = group.nodes.new("GeometryNodePointsToVertices") + group.links.new(consumer.outputs[output_name], convert.inputs["Points"]) + group.links.new(convert.outputs["Mesh"], output.inputs["Geometry"]) + else: + group.links.new(consumer.outputs[output_name], output.inputs["Geometry"]) + socket = consumer.inputs[input_name] + assert socket.hide_value and tuple(socket.default_value) == (0.0, 0.0, 0.0) + omitted = _positions(obj) + assert len(set(omitted)) == 8 + socket.default_value = (0, 0, 0) + assert _positions(obj) == omitted + zero = group.nodes.new("ShaderNodeCombineXYZ") + group.links.new(zero.outputs["Vector"], socket) + connected = _positions(obj) + assert len(connected) == 8 and set(connected) == {(0.0, 0.0, 0.0)} + assert connected != omitted + finally: + _cleanup(group, obj, mesh) + + +def test_noise_unconnected_vector_is_implicit_position_not_zero(): + """Noise with no Vector link varies spatially; linked zero is uniform.""" + group, cube, output, obj, mesh = _fixture("NFRef_noise") + try: + noise = group.nodes.new("ShaderNodeTexNoise") + store = group.nodes.new("GeometryNodeStoreNamedAttribute") + store.data_type = "FLOAT" + store.domain = "POINT" + store.inputs["Name"].default_value = "nf_ref_noise" + group.links.new(cube.outputs["Mesh"], store.inputs["Geometry"]) + group.links.new(noise.outputs["Fac"], store.inputs["Value"]) + group.links.new(store.outputs["Geometry"], output.inputs["Geometry"]) + + def values(): + bpy.context.view_layer.update() + evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()) + evaluated_mesh = evaluated.to_mesh() + try: + data = evaluated_mesh.attributes["nf_ref_noise"].data + return tuple(round(float(v.value), 5) for v in data) + finally: + evaluated.to_mesh_clear() + + socket = noise.inputs["Vector"] + assert socket.hide_value + omitted = values() + assert len(set(omitted)) > 1 + socket.default_value = (0, 0, 0) + assert values() == omitted + zero = group.nodes.new("ShaderNodeCombineXYZ") + group.links.new(zero.outputs["Vector"], socket) + assert len(set(values())) == 1 + finally: + _cleanup(group, obj, mesh) + + +def test_hidden_selection_bool_can_be_semantically_ordinary(): + """hide_value alone does not prove alternative unconnected semantics.""" + group, cube, output, obj, mesh = _fixture("NFRef_bool_selection") + try: + moved = group.nodes.new("GeometryNodeSetPosition") + group.links.new(cube.outputs["Mesh"], moved.inputs["Geometry"]) + zero = group.nodes.new("ShaderNodeCombineXYZ") + group.links.new(zero.outputs["Vector"], moved.inputs["Position"]) + group.links.new(moved.outputs["Geometry"], output.inputs["Geometry"]) + selection = moved.inputs["Selection"] + assert selection.hide_value + for flag in (False, True): + selection.default_value = flag + omitted = _positions(obj) + constant = group.nodes.new("FunctionNodeInputBool") + constant.boolean = flag + group.links.new(constant.outputs[0], selection) + assert _positions(obj) == omitted + group.nodes.remove(constant) + assert len(set(omitted)) == 1 + finally: + _cleanup(group, obj, mesh) + + +def test_group_interface_contextual_input_overrides_only_when_linked(): + """A group interface POSITION fallback differs from a connected zero.""" + group, cube, output, obj, mesh = _fixture("NFRef_group_input") + inner = bpy.data.node_groups.new("NFRef_group_context", "GeometryNodeTree") + try: + inner.interface.new_socket(name="Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry") + argument = inner.interface.new_socket(name="Location", in_out="INPUT", socket_type="NodeSocketVector") + argument.default_input = "POSITION" + input_node = inner.nodes.new("NodeGroupInput") + inside_cube = inner.nodes.new("GeometryNodeMeshCube") + inside_cube.inputs["Size"].default_value = (2, 3, 4) + move = inner.nodes.new("GeometryNodeSetPosition") + inside_out = inner.nodes.new("NodeGroupOutput") + inner.links.new(inside_cube.outputs["Mesh"], move.inputs["Geometry"]) + inner.links.new(input_node.outputs["Location"], move.inputs["Position"]) + inner.links.new(move.outputs["Geometry"], inside_out.inputs["Geometry"]) + caller = group.nodes.new("GeometryNodeGroup") + caller.node_tree = inner + group.links.new(caller.outputs["Geometry"], output.inputs["Geometry"]) + socket = caller.inputs["Location"] + assert socket.hide_value + omitted = _positions(obj) + assert len(set(omitted)) == 8 + socket.default_value = (0, 0, 0) + assert _positions(obj) == omitted + zero = group.nodes.new("ShaderNodeCombineXYZ") + group.links.new(zero.outputs["Vector"], socket) + assert set(_positions(obj)) == {(0.0, 0.0, 0.0)} + group.links.remove(next(link for link in group.links if link.to_socket == socket)) + assert _positions(obj) == omitted + argument.default_input = "VALUE" + assert argument.default_input == "VALUE" + finally: + _cleanup(group, obj, mesh, inner) + + +def test_visible_typed_defaults_and_dynamic_socket_shapes(): + """Blender exposes ordinary defaults only on the active configured sockets.""" + group = bpy.data.node_groups.new("NFRef_defaults", "GeometryNodeTree") + try: + supported = ( + ("GeometryNodeMeshCube", "Vertices X", 3), + ("GeometryNodeMeshCube", "Size", (2.0, 1.0, 3.0)), + ("FunctionNodeInputBool", None, None), + ("GeometryNodeStoreNamedAttribute", "Name", "hello"), + ) + for bl_idname, input_name, value in supported: + node = group.nodes.new(bl_idname) + if input_name is None: + assert node.bl_idname == bl_idname + continue + socket = node.inputs[input_name] + assert hasattr(socket, "default_value") and not socket.hide_value + socket.default_value = value + if isinstance(value, tuple): + assert tuple(socket.default_value) == value + else: + assert socket.default_value == value + switch = group.nodes.new("GeometryNodeSwitch") + switch.input_type = "VECTOR" + assert switch.inputs["True"].bl_idname == "NodeSocketVector" + switch.input_type = "RGBA" + assert switch.inputs["True"].bl_idname == "NodeSocketColor" + combine = group.nodes.new("NodeCombineBundle") + combine.bundle_items.new("FLOAT", "count") + combine.bundle_items.new("BOOLEAN", "enabled") + assert [item.name for item in combine.bundle_items] == ["count", "enabled"] + assert combine.inputs["count"].bl_idname == "NodeSocketFloat" + assert combine.inputs["enabled"].bl_idname == "NodeSocketBool" + assert combine.inputs["count"].default_value == 0.0 + assert not combine.inputs["count"].hide_value + set_position = group.nodes.new("GeometryNodeSetPosition") + assert set_position.inputs["Geometry"].bl_idname == "NodeSocketGeometry" + assert not hasattr(set_position.inputs["Geometry"], "default_value") + finally: + bpy.data.node_groups.remove(group, do_unlink=True) From 3b173fce861cc1d5db34db8fd7b6282623c2bdca Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 00:57:12 +0000 Subject: [PATCH 02/14] feat: add typed deferred constants and consumer-aware input delivery --- blender/input_delivery.py | 188 ++++++++++++++++++ blender/values.py | 59 ++++++ .../blender/test_consumer_aware_constants.py | 85 ++++++++ tests/unit/test_input_delivery.py | 42 ++++ 4 files changed, 374 insertions(+) create mode 100644 blender/input_delivery.py create mode 100644 tests/unit/test_input_delivery.py diff --git a/blender/input_delivery.py b/blender/input_delivery.py new file mode 100644 index 0000000..cbed778 --- /dev/null +++ b/blender/input_delivery.py @@ -0,0 +1,188 @@ +"""Consumer-aware delivery of typed values to resolved Blender input sockets. + +A socket default is a physical representation only for a conventional visible +input. Hidden, contextual, unsupported and multi-input destinations require +explicit producers and links rather than assuming Blender's unconnected state. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from ..errors import CompileError +from ..nf_types import NFType +from ..semantic.callable_contracts import canonicalize_group_input_default +from .socket_types import runtime_socket_nf_type, validate_runtime_value_socket +from .values import ConstantPayload, DeferredConstant, Value + + +@dataclass(frozen=True) +class InputRealization: + """Report the actual physical realization for raw metadata and tests.""" + + mode: str + default: object | None = None + links: int = 0 + + +def _same_value(expected, actual) -> bool: + """Compare a canonical numeric/tuple default with Blender's RNA readback.""" + if isinstance(expected, tuple): + try: + actual_parts = tuple(actual) + except TypeError: + return False + return len(expected) == len(actual_parts) and all( + _same_value(a, b) for a, b in zip(expected, actual_parts) + ) + if type(expected) is bool: + return type(actual) is bool and expected == actual + if type(expected) is int: + return type(actual) is int and expected == actual + if type(expected) is float: + return type(actual) in {int, float} and abs(float(actual) - expected) <= 1e-6 + return expected == actual + + +def _input_type(socket): + """Return the physical input type without guessing from display labels.""" + return runtime_socket_nf_type(socket) + + +def _interface_has_contextual_fallback(socket) -> bool: + """Detect non-VALUE defaults of a physical GeometryNodeGroup call input.""" + node = getattr(socket, "node", None) + if getattr(node, "bl_idname", None) != "GeometryNodeGroup": + return False + tree = getattr(node, "node_tree", None) + interface = getattr(tree, "interface", None) + if interface is None: + return True + identifier = getattr(socket, "identifier", None) + for item in interface.items_tree: + if ( + getattr(item, "item_type", None) == "SOCKET" + and getattr(item, "in_out", None) == "INPUT" + and getattr(item, "identifier", None) == identifier + ): + return getattr(item, "default_input", "VALUE") != "VALUE" + # The physical input is not reliably backed by a visible interface item. + return True + + +def _is_safe_default(socket) -> bool: + """Conservatively recognize ordinary visible writable scalar input defaults.""" + if bool(getattr(socket, "is_multi_input", False)): + return False + if bool(getattr(socket, "is_unavailable", False)) or not bool(getattr(socket, "enabled", True)): + return False + if bool(getattr(socket, "hide_value", False)) or _interface_has_contextual_fallback(socket): + return False + return hasattr(socket, "default_value") + + +def _constant_from(operand, socket, context: str) -> DeferredConstant: + """Normalize a deferred carrier or raw literal against one resolved input.""" + if isinstance(operand, DeferredConstant): + return operand + if isinstance(operand, ConstantPayload): + return DeferredConstant(operand.typ, operand.value) + typ = _input_type(socket) + if typ is None: + raise CompileError(f"{context}: unsupported input socket type {getattr(socket, 'bl_idname', None)!r}") + return DeferredConstant(typ, operand) + + +def _validate_type(socket, typ: NFType, context: str): + """Require exact typing except for the preexisting Int→Float widening.""" + physical = _input_type(socket) + if physical is None: + raise CompileError(f"{context}: unsupported input socket type {getattr(socket, 'bl_idname', None)!r}") + if typ != physical and not (typ is NFType.INT and physical is NFType.FLOAT): + raise CompileError(f"{context}: input expects {physical.value}, got {typ.value}") + + +def validate_input(group, socket, operand, *, context: str = "node input"): + """Preflight a resolved socket/operand without adding links or default values.""" + if getattr(socket, "is_output", False): + raise CompileError(f"{context}: destination must be an input socket") + node = getattr(socket, "node", None) + if getattr(node, "id_data", None) is not group: + raise CompileError(f"{context}: input belongs to a different node tree") + if bool(getattr(socket, "is_unavailable", False)) or not bool(getattr(socket, "enabled", True)): + raise CompileError(f"{context}: input socket is unavailable") + if isinstance(operand, Value): + _validate_type(socket, operand.typ, context) + validate_runtime_value_socket(operand.socket, operand.typ, group, context=context) + return operand + constant = _constant_from(operand, socket, context) + _validate_type(socket, constant.typ, context) + if constant.typ is NFType.INT and _input_type(socket) is NFType.FLOAT: + # Widen only for the physical input, preserving the source carrier type. + canonicalize_group_input_default(NFType.FLOAT, constant.value) + return constant + + +def require_output(group, operand, *, context: str = "constant") -> Value: + """Return a physical output, allocating one typed producer per deferred owner.""" + if isinstance(operand, Value): + validate_runtime_value_socket(operand.socket, operand.typ, group, context=context) + return operand + if not isinstance(operand, DeferredConstant): + raise CompileError(f"{context}: expected a typed backend operand") + operand.bind_group(group) + if operand._materialized is not None: + return operand._materialized + from .nodes import ( + _bool_value, _color_value, _int_value, _rotation_value, + _string_value, _value, _vector_value, + ) + + producers = { + NFType.FLOAT: _value, + NFType.INT: _int_value, + NFType.BOOL: _bool_value, + NFType.VECTOR: _vector_value, + NFType.COLOR: _color_value, + NFType.ROTATION: _rotation_value, + NFType.STRING: _string_value, + } + producer = producers.get(operand.typ) + if producer is None: + raise CompileError(f"{context}: cannot materialize {operand.typ.value} constant") + value = producer(group, operand.value) + operand._materialized = value + return value + + +def deliver_input(group, socket, operand, *, context: str = "node input") -> InputRealization: + """Write an eligible default or connect a validated physical producer to an input.""" + checked = validate_input(group, socket, operand, context=context) + if isinstance(checked, Value): + try: + group.links.new(checked.socket, socket) + except Exception as exc: + raise CompileError(f"{context}: failed to link runtime input: {exc}") from exc + return InputRealization("single_link", links=1) + checked.bind_group(group) + if _is_safe_default(socket): + default = checked.value + if checked.typ is NFType.INT and _input_type(socket) is NFType.FLOAT: + default = canonicalize_group_input_default(NFType.FLOAT, default) + try: + socket.default_value = default + except Exception as exc: + raise CompileError(f"{context}: failed to assign socket default: {exc}") from exc + actual = socket.default_value + if not _same_value(default, actual): + raise CompileError(f"{context}: Blender did not store an equivalent socket default") + return InputRealization("literal_default", default=default) + value = require_output(group, checked, context=context) + try: + group.links.new(value.socket, socket) + except Exception as exc: + raise CompileError(f"{context}: failed to link constant input: {exc}") from exc + return InputRealization("single_link", links=1) + + +__all__ = ["InputRealization", "validate_input", "deliver_input", "require_output"] diff --git a/blender/values.py b/blender/values.py index 234e31f..5cfba28 100644 --- a/blender/values.py +++ b/blender/values.py @@ -33,3 +33,62 @@ def make_value(socket, typ): __all__ = ["Value", "ObjectValue", "make_value"] + + +from dataclasses import dataclass + +from ..errors import CompileError +from ..semantic.callable_contracts import canonicalize_group_input_default + + +@dataclass(frozen=True) +class ConstantPayload: + """Canonical detached scalar/composite data suitable for a physical socket default.""" + + typ: NFType + value: bool | int | float | str | tuple + + def __post_init__(self): + """Normalize a valid typed constant without retaining Blender RNA objects.""" + if not isinstance(self.typ, NFType): + raise TypeError("ConstantPayload.typ must be NFType") + canonical = canonicalize_group_input_default(self.typ, self.value) + object.__setattr__(self, "value", canonical) + + +class DeferredConstant: + """Attempt-local typed constant, materialized only at a physical socket boundary. + + The identity of this carrier is significant: aliases keep this object and + share its single producer once the value is physically required. + """ + + __slots__ = ("payload", "_owner_group", "_materialized") + + def __init__(self, typ: NFType, value): + """Create one canonical value without mutating any Blender node tree.""" + self.payload = ConstantPayload(typ, value) + self._owner_group = None + self._materialized = None + + @property + def typ(self) -> NFType: + """Return the original semantic type even after physical materialization.""" + return self.payload.typ + + @property + def value(self): + """Return immutable canonical constant data.""" + return self.payload.value + + def bind_group(self, group) -> None: + """Pin this invocation-scoped carrier to its first physical Blender owner.""" + if self._owner_group is None: + self._owner_group = group + elif self._owner_group is not group: + raise CompileError("Deferred constant cannot cross physical node-tree boundaries") + + +BackendOperand = Value | DeferredConstant + +__all__ += ["ConstantPayload", "DeferredConstant", "BackendOperand"] diff --git a/tests/blender/test_consumer_aware_constants.py b/tests/blender/test_consumer_aware_constants.py index 5efde22..6d54dbd 100644 --- a/tests/blender/test_consumer_aware_constants.py +++ b/tests/blender/test_consumer_aware_constants.py @@ -215,3 +215,88 @@ def test_visible_typed_defaults_and_dynamic_socket_shapes(): assert not hasattr(set_position.inputs["Geometry"], "default_value") finally: bpy.data.node_groups.remove(group, do_unlink=True) + + +def test_consumer_delivery_uses_direct_default_and_caches_hidden_producer(): + """One deferred Vector serves a visible default and a hidden linked input.""" + from NodeForge.blender.input_delivery import deliver_input, require_output + from NodeForge.blender.values import DeferredConstant + from NodeForge.nf_types import NFType + + group = bpy.data.node_groups.new("NFDeferred_inputs", "GeometryNodeTree") + other = bpy.data.node_groups.new("NFDeferred_other", "GeometryNodeTree") + try: + cube = group.nodes.new("GeometryNodeMeshCube") + set_pos = group.nodes.new("GeometryNodeSetPosition") + constant = DeferredConstant(NFType.VECTOR, (0, 1, 2)) + direct = deliver_input(group, cube.inputs["Size"], constant) + assert direct.mode == "literal_default" and tuple(cube.inputs["Size"].default_value) == (0, 1, 2) + assert constant._materialized is None + linked = deliver_input(group, set_pos.inputs["Position"], constant) + assert linked.mode == "single_link" and set_pos.inputs["Position"].is_linked + physical = require_output(group, constant) + assert physical.socket.as_pointer() == group.links[-1].from_socket.as_pointer() + assert sum(n.bl_idname == "ShaderNodeCombineXYZ" for n in group.nodes) == 1 + assert require_output(group, constant) is physical + another_cube = other.nodes.new("GeometryNodeMeshCube") + with pytest.raises(Exception, match="cross physical node-tree"): + deliver_input(other, another_cube.inputs["Size"], constant) + finally: + bpy.data.node_groups.remove(group, do_unlink=True) + bpy.data.node_groups.remove(other, do_unlink=True) + + +def test_consumer_delivery_strict_types_and_existing_runtime_links(): + """Typed input checks reject Bool→Int but retain an existing runtime link.""" + from NodeForge.blender.input_delivery import deliver_input + from NodeForge.blender.values import DeferredConstant, Value + from NodeForge.nf_types import NFType + from NodeForge.errors import CompileError + + group = bpy.data.node_groups.new("NFDeferred_types", "GeometryNodeTree") + try: + cube = group.nodes.new("GeometryNodeMeshCube") + assert deliver_input(group, cube.inputs["Vertices X"], DeferredConstant(NFType.INT, 3)).mode == "literal_default" + with pytest.raises(CompileError, match="expects INT, got BOOL"): + deliver_input(group, cube.inputs["Vertices X"], DeferredConstant(NFType.BOOL, True)) + float_consumer = group.nodes.new("ShaderNodeMath") + assert deliver_input(group, float_consumer.inputs[0], DeferredConstant(NFType.INT, 2)).mode == "literal_default" + bool_value = group.nodes.new("FunctionNodeInputBool") + switch = group.nodes.new("GeometryNodeSwitch") + switch.input_type = "FLOAT" + assert deliver_input(group, switch.inputs["Switch"], Value(bool_value.outputs[0], NFType.BOOL)).mode == "single_link" + assert switch.inputs["Switch"].is_linked + with pytest.raises(CompileError, match="input expects INT"): + deliver_input(group, cube.inputs["Vertices X"], Value(bool_value.outputs[0], NFType.BOOL)) + finally: + bpy.data.node_groups.remove(group, do_unlink=True) + + +def test_consumer_delivery_respects_contextual_group_and_typed_color_rotation(): + """Caller POSITION defaults require a link; ordinary Color/Rotation inputs can store data.""" + from NodeForge.blender.input_delivery import deliver_input + from NodeForge.blender.values import DeferredConstant + from NodeForge.nf_types import NFType + + outer = bpy.data.node_groups.new("NFDeferred_outer", "GeometryNodeTree") + inner = bpy.data.node_groups.new("NFDeferred_inner", "GeometryNodeTree") + try: + socket = inner.interface.new_socket(name="Location", in_out="INPUT", socket_type="NodeSocketVector") + socket.default_input = "POSITION" + group = outer.nodes.new("GeometryNodeGroup") + group.node_tree = inner + result = deliver_input(outer, group.inputs["Location"], DeferredConstant(NFType.VECTOR, (0, 0, 0))) + assert result.mode == "single_link" + assert group.inputs["Location"].is_linked + transform = outer.nodes.new("GeometryNodeTransform") + rotation = DeferredConstant(NFType.ROTATION, (0, -0.5, 1.5)) + assert deliver_input(outer, transform.inputs["Rotation"], rotation).mode == "literal_default" + assert tuple(transform.inputs["Rotation"].default_value) == rotation.value + color_input = outer.nodes.new("ShaderNodeMix") + color_input.data_type = "RGBA" + color = DeferredConstant(NFType.COLOR, (0.25, 0.5, 1.0, 0.75)) + assert deliver_input(outer, color_input.inputs["A"], color).mode == "literal_default" + assert tuple(color_input.inputs["A"].default_value) == color.value + finally: + bpy.data.node_groups.remove(outer, do_unlink=True) + bpy.data.node_groups.remove(inner, do_unlink=True) diff --git a/tests/unit/test_input_delivery.py b/tests/unit/test_input_delivery.py new file mode 100644 index 0000000..84cacce --- /dev/null +++ b/tests/unit/test_input_delivery.py @@ -0,0 +1,42 @@ +"""Pure Python contracts for deferred constant payloads and identity.""" + +import pytest + +from NodeForge.blender.values import ConstantPayload, DeferredConstant, Value +from NodeForge.errors import CompileError +from NodeForge.nf_types import NFType + + +def test_deferred_payload_canonicalizes_numeric_and_vector_data(): + """Canonicalization preserves NFType and makes composites immutable.""" + scalar = DeferredConstant(NFType.FLOAT, 1.25) + vector = DeferredConstant(NFType.VECTOR, (1, 2.5, -3)) + assert scalar.value == 1.25 and scalar.typ is NFType.FLOAT + assert vector.value == (1.0, 2.5, -3.0) + assert isinstance(vector.value, tuple) + assert scalar._materialized is None and vector._owner_group is None + assert vector is not DeferredConstant(NFType.VECTOR, vector.value) + + +@pytest.mark.parametrize("typ,value", [ + (NFType.BOOL, 1), + (NFType.INT, 1.5), + (NFType.VECTOR, (0.0, 1.0)), + (NFType.COLOR, (-1.0, 0.0, 0.0, 1.0)), + (NFType.ROTATION, (0.0, False, 0.0)), + (NFType.GEOMETRY, "not a geometry"), +]) +def test_invalid_deferred_payload_is_rejected_at_creation(typ, value): + """Invalid typed values never reach a Blender node or a downstream consumer.""" + with pytest.raises(CompileError): + ConstantPayload(typ, value) + + +def test_deferred_group_owner_is_pinned_and_never_crosses_trees(): + """Deferred constants may be shared within one tree but never reused across owners.""" + constant = DeferredConstant(NFType.INT, 7) + tree_a, tree_b = object(), object() + constant.bind_group(tree_a) + constant.bind_group(tree_a) + with pytest.raises(CompileError, match="cross physical node-tree"): + constant.bind_group(tree_b) From ab4c123c36704e0079df80b5c821b8d5137b9bfa Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 01:00:34 +0000 Subject: [PATCH 03/14] feat: preserve runtime identities and native defaults in raw nodes --- blender/input_delivery.py | 21 +++++ blender/raw_nodes.py | 76 ++++++------------- semantic/analysis.py | 3 +- semantic/builtin_calls.py | 35 ++++++--- .../blender/test_consumer_aware_constants.py | 56 ++++++++++++++ tests/unit/test_raw_nodes.py | 47 ++++++++++++ 6 files changed, 171 insertions(+), 67 deletions(-) diff --git a/blender/input_delivery.py b/blender/input_delivery.py index cbed778..0e4ee95 100644 --- a/blender/input_delivery.py +++ b/blender/input_delivery.py @@ -16,6 +16,13 @@ from .values import ConstantPayload, DeferredConstant, Value +@dataclass(frozen=True) +class MenuLiteral: + """An enum-backed Blender input without a general runtime producer.""" + + value: str + + @dataclass(frozen=True) class InputRealization: """Report the actual physical realization for raw metadata and tests.""" @@ -111,6 +118,12 @@ def validate_input(group, socket, operand, *, context: str = "node input"): raise CompileError(f"{context}: input belongs to a different node tree") if bool(getattr(socket, "is_unavailable", False)) or not bool(getattr(socket, "enabled", True)): raise CompileError(f"{context}: input socket is unavailable") + if getattr(socket, "bl_idname", "") == "NodeSocketMenu" and not isinstance(operand, (Value, DeferredConstant)): + if type(operand) is not str or not operand: + raise CompileError(f"{context}: Menu input requires a non-empty enum literal") + if not hasattr(socket, "default_value"): + raise CompileError(f"{context}: Menu input has no supported literal default") + return MenuLiteral(operand) if isinstance(operand, Value): _validate_type(socket, operand.typ, context) validate_runtime_value_socket(operand.socket, operand.typ, group, context=context) @@ -158,6 +171,14 @@ def require_output(group, operand, *, context: str = "constant") -> Value: def deliver_input(group, socket, operand, *, context: str = "node input") -> InputRealization: """Write an eligible default or connect a validated physical producer to an input.""" checked = validate_input(group, socket, operand, context=context) + if isinstance(checked, MenuLiteral): + try: + socket.default_value = checked.value + except Exception as exc: + raise CompileError(f"{context}: failed to assign Menu input: {exc}") from exc + if socket.default_value != checked.value: + raise CompileError(f"{context}: Menu input did not store the requested literal") + return InputRealization("literal_default", default=checked.value) if isinstance(checked, Value): try: group.links.new(checked.socket, socket) diff --git a/blender/raw_nodes.py b/blender/raw_nodes.py index 7aeb0ec..5fea34f 100644 --- a/blender/raw_nodes.py +++ b/blender/raw_nodes.py @@ -22,7 +22,8 @@ from ..semantic.callable_contracts import canonicalize_color_components from .socket_types import runtime_socket_nf_type from .nodes import _new_node -from .values import Value, make_value +from .values import Value, DeferredConstant, make_value +from .input_delivery import deliver_input, validate_input RAW_NODE_PROP = "nodeforge_raw_node" @@ -147,16 +148,16 @@ def build_materialized_raw_node( raise CompileError(f"{context}: multi-input {selector_label} items cannot be empty") _require_multi_input(socket, context, selector_label) for value in value_spec: - _validate_materialized_value(value, socket, context, selector_label) + validate_input(group, socket, value, context=f"{context}: input {selector_label}") prepared_inputs.append((socket, socket_ref, INPUT_MULTI_LINK, tuple(value_spec))) - elif isinstance(value_spec, Value): - _validate_materialized_value(value_spec, socket, context, selector_label) - prepared_inputs.append((socket, socket_ref, INPUT_SINGLE_LINK, value_spec)) else: - normalized = _normalize_input_literal(value_spec, context, selector_label, socket=socket) - if not hasattr(socket, "default_value"): - raise CompileError(f"{context}: input {selector_label!r} does not accept literal defaults") - prepared_inputs.append((socket, socket_ref, INPUT_LITERAL, normalized)) + # Raw literal syntax retains its established validation; physical + # type and realization are decided at the resolved socket boundary. + payload = value_spec + if not isinstance(value_spec, (Value, DeferredConstant)): + payload = _normalize_input_literal(value_spec, context, selector_label, socket=socket) + validate_input(group, socket, payload, context=f"{context}: input {selector_label}") + prepared_inputs.append((socket, socket_ref, None, payload)) prepared_outputs = [] resolved_output_sockets = [] @@ -205,22 +206,23 @@ def build_materialized_raw_node( # rollback for such failures. input_contracts = [] for socket, socket_ref, mode, payload in prepared_inputs: + input_context = f"{context}: input {socket_ref.identifier}" if mode == INPUT_MULTI_LINK: for value in payload: - _link_materialized_value(group, value, socket, context, socket_ref.identifier) + realization = deliver_input(group, socket, value, context=input_context) + if realization.mode != INPUT_SINGLE_LINK: + raise CompileError(f"{input_context}: multi-input items must be connected") input_contracts.append( - {"socket": _serialize_physical_socket_ref(socket_ref), "mode": mode, "links": len(payload)} - ) - elif mode == INPUT_SINGLE_LINK: - _link_materialized_value(group, payload, socket, context, socket_ref.identifier) - input_contracts.append( - {"socket": _serialize_physical_socket_ref(socket_ref), "mode": mode, "links": 1} + {"socket": _serialize_physical_socket_ref(socket_ref), "mode": INPUT_MULTI_LINK, "links": len(payload)} ) else: - normalized = _assign_literal_default(socket, payload, context, socket_ref.identifier) - input_contracts.append( - {"socket": _serialize_physical_socket_ref(socket_ref), "mode": mode, "default": normalized} - ) + realization = deliver_input(group, socket, payload, context=input_context) + contract = {"socket": _serialize_physical_socket_ref(socket_ref), "mode": realization.mode} + if realization.mode == INPUT_SINGLE_LINK: + contract["links"] = 1 + else: + contract["default"] = _normalize_socket_default(socket.default_value, input_context) + input_contracts.append(contract) output_refs = tuple(item[2] for item in prepared_outputs) mode = RAW_MULTI_MODE if outputs is not None else RAW_SINGLE_MODE @@ -432,21 +434,6 @@ def _reject_duplicate_physical_socket(existing, socket, *, context: str) -> None raise CompileError(context) -def _validate_materialized_value(value, socket, context, socket_name): - """Validate one runtime Value against a resolved input without linking it.""" - if not isinstance(value, Value): - raise CompileError(f"{context}: input {socket_name!r} expects a runtime node value") - _validate_runtime_socket_type(socket, value.typ, direction="input", context=context, socket_name=socket_name) - - -def _link_materialized_value(group, value, socket, context, socket_name): - """Link one prevalidated runtime Value to a prevalidated raw-node input.""" - try: - group.links.new(value.socket, socket) - except Exception as exc: - raise CompileError(f"{context}: failed to link input {socket_name!r}: {exc}") from exc - - def _validate_public_type(typ, context): if typ not in _SUPPORTED_TYPES: raise CompileError(f"{context} must be a NodeForge type token") @@ -504,25 +491,6 @@ def _require_multi_input(socket, context, socket_name): raise CompileError(f"{context}: Blender did not expose multi-input metadata for socket {socket_name!r}") -def _assign_literal_default(socket, literal, context, socket_name): - literal = _normalize_input_literal(literal, context, socket_name, socket=socket) - if not hasattr(socket, "default_value"): - raise CompileError(f"{context}: input {socket_name!r} does not accept literal defaults") - try: - socket.default_value = literal - except Exception: - try: - for index, component in enumerate(literal): - socket.default_value[index] = component - except Exception as exc: - raise CompileError(f"{context}: failed to assign literal default for input {socket_name!r}: {exc}") from exc - try: - normalized = _normalize_socket_default(socket.default_value, f"{context}: input {socket_name!r}") - except Exception as exc: - raise CompileError(f"{context}: could not verify literal default for input {socket_name!r}") from exc - return normalized - - def _normalize_input_literal(literal, context, socket_name, *, socket=None): """Validate literals against the physical destination after semantic normalization.""" is_color = socket is not None and runtime_socket_nf_type(socket) is TYPE_COLOR diff --git a/semantic/analysis.py b/semantic/analysis.py index 8f23878..7562538 100644 --- a/semantic/analysis.py +++ b/semantic/analysis.py @@ -1821,7 +1821,8 @@ def add_runtime(child, parameter_name, context): return typ builtin = analyze_builtin_call( - name, cleaned_call, environment.const_eval_values, add_runtime + name, cleaned_call, environment.const_eval_values, add_runtime, + runtime_binding_names=environment.runtime_bindings, ) if isinstance(builtin.result, ContextReadCallResult): if builtin.result.slot not in available_group_context_slots: diff --git a/semantic/builtin_calls.py b/semantic/builtin_calls.py index dfaa033..6b19395 100644 --- a/semantic/builtin_calls.py +++ b/semantic/builtin_calls.py @@ -453,7 +453,7 @@ def _raw_input_literal(value, context, socket_name): raise CompileError(f"{context}: unsupported literal default for input {socket_name!r}") -def _analyze_raw_node(expr, consts, add_runtime): +def _analyze_raw_node(expr, consts, add_runtime, runtime_binding_names=frozenset()): """Normalize ``node(...)`` source syntax without querying Blender sockets.""" if len(expr.args) != 1: raise CompileError("node(...) expects exactly one positional bl_idname argument") @@ -563,15 +563,26 @@ def _analyze_raw_node(expr, consts, add_runtime): operands.append(AnalyzedCallOperand(parameter_name, typ_i)) input_specs.append((selector, ("multi", tuple(refs)))) continue - try: - literal = _const_eval(value_expr, consts) - except ConstEvalUnavailable: - typ_i = add_runtime(value_expr, parameter_name, f"node() input {parameter_name!r}") - ref = len(operands) - operands.append(AnalyzedCallOperand(parameter_name, typ_i)) - input_specs.append((selector, ("runtime", ref))) - else: - input_specs.append((selector, ("literal", _raw_input_literal(literal, "node()", parameter_name)))) + # Runtime names shadow compile-time snapshots at ordinary expression + # sites. Raw input evaluation must honor the same binding precedence; + # otherwise named Vector producers become orphaned while their + # consumers silently receive copied static defaults. + runtime_expression = any( + isinstance(child, ast.Name) and child.id in runtime_binding_names + for child in ast.walk(value_expr) + ) + if not runtime_expression: + try: + literal = _const_eval(value_expr, consts) + except ConstEvalUnavailable: + pass + else: + input_specs.append((selector, ("literal", _raw_input_literal(literal, "node()", parameter_name)))) + continue + typ_i = add_runtime(value_expr, parameter_name, f"node() input {parameter_name!r}") + ref = len(operands) + operands.append(AnalyzedCallOperand(parameter_name, typ_i)) + input_specs.append((selector, ("runtime", ref))) options = ( ("bl_idname", bl_idname), @@ -588,7 +599,7 @@ def _analyze_raw_node(expr, consts, add_runtime): return BuiltinCallSemantics(tuple(operands), options, result) -def analyze_builtin_call(name: str, expr: ast.Call, consts, add_runtime: RuntimeAnalyzer) -> BuiltinCallSemantics: +def analyze_builtin_call(name: str, expr: ast.Call, consts, add_runtime: RuntimeAnalyzer, *, runtime_binding_names=frozenset()) -> BuiltinCallSemantics: """Normalize one IR-capable builtin call using detached compile-time state.""" if name not in IR_CAPABLE_BUILTIN_NAMES: raise KeyError(name) @@ -1043,7 +1054,7 @@ def runtime(node, parameter_name, context): return BuiltinCallSemantics(tuple(operands), (), RuntimeCallResult(TYPE_BUNDLE)) if name == "node": - return _analyze_raw_node(expr, consts, add_runtime) + return _analyze_raw_node(expr, consts, add_runtime, runtime_binding_names) raise CompileError(f"Internal error: missing semantic builtin analyzer for {name}") diff --git a/tests/blender/test_consumer_aware_constants.py b/tests/blender/test_consumer_aware_constants.py index 6d54dbd..58a2994 100644 --- a/tests/blender/test_consumer_aware_constants.py +++ b/tests/blender/test_consumer_aware_constants.py @@ -300,3 +300,59 @@ def test_consumer_delivery_respects_contextual_group_and_typed_color_rotation(): finally: bpy.data.node_groups.remove(outer, do_unlink=True) bpy.data.node_groups.remove(inner, do_unlink=True) + + +def test_raw_consumer_link_semantics_and_named_vector_identity(): + """Raw named Vector links one producer; contextual explicit zero is linked.""" + from NodeForge import compiler + from NodeForge.blender import raw_nodes + + source = ''' +def shape(): + size = vector(2.0, 1.0, 1.5) + mesh = node("GeometryNodeMeshCube", inputs={"Size": size}, output="Mesh", typ=Geometry) + return mesh +''' + group = compiler.create_expression_group(source, "NFDeferred_raw_named") + try: + cubes = [n for n in group.nodes if n.bl_idname == "GeometryNodeMeshCube"] + combine = [n for n in group.nodes if n.bl_idname == "ShaderNodeCombineXYZ"] + assert len(cubes) == 1 and len(combine) == 1 + assert cubes[0].inputs["Size"].is_linked + assert len([l for l in group.links if l.from_node == combine[0]]) == 1 + spec = raw_nodes.raw_node_spec(cubes[0]) + assert spec["inputs"][0]["mode"] == raw_nodes.INPUT_SINGLE_LINK + + explicit = compiler.create_expression_group(''' +def shape(): + return node("GeometryNodeSetPosition", inputs={"Geometry": cube(1.0), "Position": (0.0, 0.0, 0.0)}, output="Geometry", typ=Geometry) +''', "NFDeferred_raw_pos") + try: + position_node = next(n for n in explicit.nodes if n.bl_idname == "GeometryNodeSetPosition") + assert position_node.inputs["Position"].is_linked + assert raw_nodes.raw_node_spec(position_node)["inputs"][1]["mode"] == raw_nodes.INPUT_SINGLE_LINK + finally: + bpy.data.node_groups.remove(explicit, do_unlink=True) + finally: + bpy.data.node_groups.remove(group, do_unlink=True) + + +def test_raw_value_defaults_do_not_add_producers_and_unsupported_types_fail(): + """Regular inputs stay as defaults; wrong typed runtime/virtual sockets reject.""" + from NodeForge import compiler + from NodeForge.errors import CompileError + + group = compiler.create_expression_group(''' +def shape(): + return node("GeometryNodeMeshCube", inputs={"Size": (2.0, 1.0, 1.5), "Vertices X": 3}, output="Mesh", typ=Geometry) +''', "NFDeferred_raw_defaults") + try: + assert len([n for n in group.nodes if n.bl_idname == "GeometryNodeMeshCube"]) == 1 + assert all(n.bl_idname != "ShaderNodeCombineXYZ" for n in group.nodes) + finally: + bpy.data.node_groups.remove(group, do_unlink=True) + with pytest.raises(CompileError): + compiler.create_expression_group(''' +def shape(): + return node("GeometryNodeMeshCube", inputs={"Vertices X": True}, output="Mesh", typ=Geometry) +''', "NFDeferred_raw_bad_bool") diff --git a/tests/unit/test_raw_nodes.py b/tests/unit/test_raw_nodes.py index 266ba47..bbe9e5a 100644 --- a/tests/unit/test_raw_nodes.py +++ b/tests/unit/test_raw_nodes.py @@ -68,6 +68,8 @@ def __init__(self, bl_idname, inputs=(), outputs=()): self.name = bl_idname self.label = "" self.bl_rna = SimpleNamespace(properties={}) + for socket in (*self.inputs, *self.outputs): + socket.node = self class _FakeLinks(list): @@ -360,6 +362,8 @@ def test_raw_build_preflights_all_selectors_before_defaults_links_or_metadata(mo input_socket = _FakeSocket("Value", "Value", default_value=0.0) node = _FakeNode("ShaderNodeValue", inputs=[input_socket], outputs=[_FakeSocket("Value", "ValueOut", is_output=True)]) group = _FakeGroup() + # Backend socket validation now verifies ownership at the physical boundary. + node.id_data = group monkeypatch.setattr(raw_nodes, "_new_node", lambda *_args, **_kwargs: node) with pytest.raises(CompileError, match="unknown output socket name"): @@ -383,6 +387,8 @@ def test_raw_build_rejects_identifierless_declared_socket_before_mutation(monkey output_socket = _FakeSocket("Value", "Out", is_output=True) node = _FakeNode("ShaderNodeValue", inputs=[input_socket], outputs=[output_socket]) group = _FakeGroup() + # Backend socket validation now verifies ownership at the physical boundary. + node.id_data = group monkeypatch.setattr(raw_nodes, "_new_node", lambda *_args, **_kwargs: node) with pytest.raises(CompileError, match="cannot be persisted safely"): @@ -406,6 +412,8 @@ def test_raw_build_writes_schema_v2_identifier_refs_only(monkeypatch): output_socket = _FakeSocket("Value", "OutputValue", is_output=True) node = _FakeNode("ShaderNodeValue", inputs=[input_socket], outputs=[output_socket]) group = _FakeGroup() + # Backend socket validation now verifies ownership at the physical boundary. + node.id_data = group monkeypatch.setattr(raw_nodes, "_new_node", lambda *_args, **_kwargs: node) value = raw_nodes.build_materialized_raw_node( @@ -437,6 +445,8 @@ def test_mixed_selectors_cannot_bind_one_physical_socket_twice(monkeypatch): output = _FakeSocket("Value", "Out", is_output=True) node = _FakeNode("ShaderNodeMath", inputs=[shared], outputs=[output]) group = _FakeGroup() + # Backend socket validation now verifies ownership at the physical boundary. + node.id_data = group monkeypatch.setattr(raw_nodes, "_new_node", lambda *_args, **_kwargs: node) with pytest.raises(CompileError, match="two input selectors resolve to the same physical socket"): @@ -618,3 +628,40 @@ def test_validate_raw_node_after_cutover_uses_schema_specific_locator_and_fails_ output.identifier = "Corrupted" with pytest.raises(CompileError, match="identifier 'OutputID' is missing"): raw_nodes.validate_raw_node_after_cutover(node, group) + + +def test_raw_input_precedence_preserves_runtime_bound_name(): + """Runtime names shadow detached CTFE snapshots in raw input evaluation.""" + expr = ast.parse('node("GeometryNodeMeshCube", inputs={"Size": size}, output="Mesh", typ=Geometry)', mode="eval").body + calls = [] + + def add_runtime(node, parameter_name, context): + calls.append((node, parameter_name, context)) + return TYPE_VECTOR + + result = analyze_builtin_call( + "node", expr, {"size": (2.0, 1.0, 1.5)}, add_runtime, + runtime_binding_names={"size"}, + ) + options = dict(result.options) + assert options["inputs"] == (("Size", ("runtime", 0)),) + assert len(calls) == 1 and isinstance(calls[0][0], ast.Name) + + static = analyze_builtin_call( + "node", expr, {"size": (2.0, 1.0, 1.5)}, add_runtime, + runtime_binding_names=(), + ) + assert dict(static.options)["inputs"] == (("Size", ("literal", (2.0, 1.0, 1.5))),) + + +def test_raw_input_precedence_follows_runtime_name_in_expression(): + """A nested expression referencing a runtime name is not replaced by CTFE.""" + expr = ast.parse( + 'node("GeometryNodeMeshCube", inputs={"Size": vector(size, 1, 1)}, output="Mesh", typ=Geometry)', + mode="eval", + ).body + result = analyze_builtin_call( + "node", expr, {"size": 2.0}, lambda *_: TYPE_VECTOR, + runtime_binding_names={"size"}, + ) + assert dict(result.options)["inputs"] == (("Size", ("runtime", 0)),) From c5259f8ceda8fd89103fe4ac1098884753013cd2 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 01:07:31 +0000 Subject: [PATCH 04/14] feat: deliver constants through expressions and geometry nodes --- blender/geometry.py | 192 ++++++++++-------- blender/nodes.py | 47 +++-- .../blender/test_consumer_aware_constants.py | 72 +++++++ tests/unit/test_numeric_semantics.py | 113 ++++++----- tests/unit/test_semantic_backend_contract.py | 21 ++ tests/unit/test_semantic_ir.py | 20 ++ 6 files changed, 311 insertions(+), 154 deletions(-) diff --git a/blender/geometry.py b/blender/geometry.py index 1dfbba4..3ba2f1d 100644 --- a/blender/geometry.py +++ b/blender/geometry.py @@ -4,7 +4,8 @@ from ..type_capabilities import ATTRIBUTE_DATA_TYPES, CAPTURE_ITEM_TYPES from ..semantic.attribute_domains import normalize_attribute_domain from ..errors import CompileError -from .values import Value +from .values import Value, DeferredConstant +from .input_delivery import deliver_input from .nodes import _new_node, _combine_xyz, _combine_xyz_mixed, _is_number_type from ..semantic.compile_time import _as_float_const, _is_const_number, _is_const_vector, _is_const_vector_like from ..semantic.numeric_semantics import normalize_int_constant @@ -46,44 +47,56 @@ def _store_named_attribute( node.data_type = data_type node.domain = domain node.inputs["Selection"].default_value = True - if isinstance(attr_name, Value): - if attr_name.typ != TYPE_STRING: - raise CompileError("store() attribute name must be String") - group.links.new(attr_name.socket, node.inputs["Name"]) - else: - node.inputs["Name"].default_value = attr_name + deliver_input(group, node.inputs["Name"], attr_name, context="store() Name") group.links.new(geometry_socket, node.inputs["Geometry"]) if selection is not None: group.links.new(selection.socket, node.inputs["Selection"]) - group.links.new(value.socket, node.inputs["Value"]) + if isinstance(value, Value) and _attribute_data_type(value.typ) != data_type: + # An explicit store data_type override intentionally uses Blender's + # physical socket conversion; strict literal delivery must not erase it. + group.links.new(value.socket, node.inputs["Value"]) + else: + deliver_input(group, node.inputs["Value"], value, context="attribute Value") return node.outputs["Geometry"] def _set_int_like_socket(group, socket, value, x=0, y=0, label="value", minimum=None): """Write or link a numeric value into an integer-like Blender node socket.""" + if isinstance(value, DeferredConstant): + if not _is_number_type(value.typ): + raise CompileError(f"{label} expects Float/Int") + value = value.value if _is_const_number(value): intval = int(value) if minimum is not None: intval = max(int(minimum), intval) - socket.default_value = intval + deliver_input(group, socket, intval, context=label) return if isinstance(value, Value) and _is_number_type(value.typ): - group.links.new(value.socket, socket) + if value.typ == TYPE_FLOAT: + # Existing numeric geometry helper permits physical Float→Int links. + group.links.new(value.socket, socket) + else: + deliver_input(group, socket, value, context=label) return raise CompileError(f"{label} expects Float/Int") def _set_float_like_socket(group, socket, value, x=0, y=0, label="value", minimum=None): """Write or link a numeric value into a float-like Blender node socket.""" + if isinstance(value, DeferredConstant): + if not _is_number_type(value.typ): + raise CompileError(f"{label} expects Float/Int") + value = value.value if _is_const_number(value): fval = float(value) if minimum is not None: fval = max(float(minimum), fval) - socket.default_value = fval + deliver_input(group, socket, fval, context=label) return if isinstance(value, Value) and _is_number_type(value.typ): - group.links.new(value.socket, socket) + deliver_input(group, socket, value, context=label) return raise CompileError(f"{label} expects Float/Int") @@ -166,24 +179,26 @@ def _euler_to_rotation(group, euler_vec, x=0, y=0): return Value(node.outputs[0], TYPE_ROTATION) def _cube_geometry(group, size, x=0, y=0): - """Function `_cube_geometry` used by the NodeForge addon.""" + """Create Mesh Cube with direct scalar/vector defaults or existing runtime links.""" node = _new_node(group, "GeometryNodeMeshCube", x, y) - for i in [1, 2, 3]: - try: node.inputs[i].default_value = 2 - except Exception: pass - if _is_const_number(size): - _set_vector_socket_default(node.inputs[0], (size, size, size)) - elif _is_const_vector_like(size): - _set_vector_socket_default(node.inputs[0], size) - elif isinstance(size, Value) and size.typ == TYPE_VECTOR: - group.links.new(size.socket, node.inputs[0]) + for index in (1, 2, 3): + node.inputs[index].default_value = 2 + if isinstance(size, DeferredConstant) and _is_number_type(size.typ): + size = (size.value,) * 3 + elif _is_const_number(size): + size = (size,) * 3 + if _is_const_vector_like(size) or ( + isinstance(size, (Value, DeferredConstant)) and size.typ == TYPE_VECTOR + ): + _set_vector_socket_value(group, node.inputs[0], size, x, y, "cube() size") elif isinstance(size, Value) and _is_number_type(size.typ): - v = _combine_xyz(group, size, size, size, x - 180, y - 60) - group.links.new(v.socket, node.inputs[0]) + vector = _combine_xyz(group, size, size, size, x - 180, y - 60) + deliver_input(group, node.inputs[0], vector, context="cube() size") else: raise CompileError("cube(size) expects Float/Int or Vector size") return Value(node.outputs[0], TYPE_GEOMETRY) + def _empty_geometry(group, x=0, y=0): """Create a valid Geometry value with zero elements. @@ -201,26 +216,14 @@ def _empty_geometry(group, x=0, y=0): return Value(node.outputs[0], TYPE_GEOMETRY) -def _set_vector_socket_value(group, socket, value, x=0, y=0, label="value", *, link_const=False): - """Write or link a Vector into a Blender node socket. - - Some Geometry Nodes field inputs, notably Set Position's Position socket in - Blender 5.x, ignore an unlinked socket default during modifier evaluation. - `link_const=True` materializes compile-time vectors as a Combine XYZ node so - those sockets receive an explicit field value while ordinary value sockets can - still keep compact defaults. - """ +def _set_vector_socket_value(group, socket, value, x=0, y=0, label="value"): + """Deliver a Vector to its resolved Blender consumer and respect implicit fields.""" if _is_const_vector_like(value): - if link_const: - vector_value = _combine_xyz_mixed(group, list(value), x, y) - group.links.new(vector_value.socket, socket) - else: - _set_vector_socket_default(socket, value) - return - if isinstance(value, Value) and value.typ == TYPE_VECTOR: - group.links.new(value.socket, socket) - return - raise CompileError(f"{label} expects Vector") + deliver_input(group, socket, tuple(value), context=label) + elif isinstance(value, (Value, DeferredConstant)) and value.typ == TYPE_VECTOR: + deliver_input(group, socket, value, context=label) + else: + raise CompileError(f"{label} expects Vector") def _socket_by_name_or_index(node, name, index): @@ -234,7 +237,7 @@ def _point_geometry(group, position, x=0, y=0): geo = _points_geometry(group, 1, x, y) node = _new_node(group, "GeometryNodeSetPosition", x + 220, y) group.links.new(geo.socket, node.inputs[0]) - _set_vector_socket_value(group, node.inputs[2], position, x, y, "point() position", link_const=True) + _set_vector_socket_value(group, node.inputs[2], position, x, y, "point() position") return Value(node.outputs[0], TYPE_GEOMETRY) @@ -287,48 +290,48 @@ def _polyline_geometry(group, points, x=0, y=0): segments = [] for idx, (a, b) in enumerate(zip(points, points[1:])): node = _new_node(group, "GeometryNodeCurvePrimitiveLine", x, y - idx * 90) - _set_vector_socket_default(node.inputs[0], a) - _set_vector_socket_default(node.inputs[1], b) + _set_vector_socket_value(group, node.inputs[0], a, x, y, "polyline() start") + _set_vector_socket_value(group, node.inputs[1], b, x, y, "polyline() end") segments.append(Value(node.outputs[0], TYPE_GEOMETRY)) return _join_geometry(group, segments, x + 280, y) def _transform_geometry(group, geo, *, translation, scale, rotation, x=0, y=0): - """Function `_transform_geometry` used by the NodeForge addon.""" + """Apply translation, Euler rotation and scale with resolved input semantics.""" if geo.typ != TYPE_GEOMETRY: raise CompileError("transform() expects Geometry") node = _new_node(group, "GeometryNodeTransform", x, y) group.links.new(geo.socket, node.inputs[0]) if translation is not None: - if _is_const_vector_like(translation): - _set_vector_socket_default(node.inputs[2], translation) - elif isinstance(translation, Value) and translation.typ == TYPE_VECTOR: - group.links.new(translation.socket, node.inputs[2]) - else: - raise CompileError("translation= must be Vector") + _set_vector_socket_value(group, node.inputs[2], translation, x, y, "translation=") if rotation is not None: - if _is_const_vector_like(rotation): - _set_rotation_socket_default(node.inputs[3], rotation) + if isinstance(rotation, DeferredConstant) and rotation.typ == TYPE_VECTOR: + rotation = DeferredConstant(TYPE_ROTATION, rotation.value) + elif _is_const_vector_like(rotation): + rotation = DeferredConstant(TYPE_ROTATION, tuple(rotation)) elif isinstance(rotation, Value) and rotation.typ == TYPE_VECTOR: - rot = _euler_to_rotation(group, rotation, x - 180, y - 120) - group.links.new(rot.socket, node.inputs[3]) + rotation = _euler_to_rotation(group, rotation, x - 180, y - 120) else: raise CompileError("rotation= must be Vector in radians") + deliver_input(group, node.inputs[3], rotation, context="transform() rotation") if scale is not None: - if _is_const_number(scale): - _set_vector_socket_default(node.inputs[4], (scale, scale, scale)) - elif _is_const_vector_like(scale): - _set_vector_socket_default(node.inputs[4], scale) - elif isinstance(scale, Value) and scale.typ == TYPE_VECTOR: - group.links.new(scale.socket, node.inputs[4]) + if isinstance(scale, DeferredConstant) and _is_number_type(scale.typ): + scale = (scale.value,) * 3 + elif _is_const_number(scale): + scale = (scale,) * 3 + if _is_const_vector_like(scale) or ( + isinstance(scale, (Value, DeferredConstant)) and scale.typ == TYPE_VECTOR + ): + _set_vector_socket_value(group, node.inputs[4], scale, x, y, "scale=") elif isinstance(scale, Value) and _is_number_type(scale.typ): - v = _combine_xyz(group, scale, scale, scale, x - 180, y - 80) - group.links.new(v.socket, node.inputs[4]) + combined = _combine_xyz(group, scale, scale, scale, x - 180, y - 80) + deliver_input(group, node.inputs[4], combined, context="transform() scale") else: raise CompileError("scale= must be Float/Int or Vector") return Value(node.outputs[0], TYPE_GEOMETRY) + def _realize_instances(group, geo, x=0, y=0): """Function `_realize_instances` used by the NodeForge addon.""" if geo.typ != TYPE_GEOMETRY: @@ -346,10 +349,12 @@ def _points_geometry(group, count, x=0, y=0): """ node = _new_node(group, "GeometryNodeMeshLine", x, y) # Count + if isinstance(count, DeferredConstant): + count = count.value if _is_const_number(count): - node.inputs[0].default_value = max(0, int(count)) + deliver_input(group, node.inputs[0], max(0, int(count)), context="points() Count") elif isinstance(count, Value) and count.typ == TYPE_INT: - group.links.new(count.socket, node.inputs[0]) + deliver_input(group, node.inputs[0], count, context="points() Count") elif isinstance(count, Value) and count.typ == TYPE_FLOAT: group.links.new(count.socket, node.inputs[0]) else: @@ -369,14 +374,14 @@ def _set_position_geometry(group, geo, pos, *, selection, x=0, y=0): raise CompileError("set_position(geo, position) first argument must be Geometry") if pos.typ != TYPE_VECTOR: raise CompileError("set_position(geo, position) second argument must be Vector") - if selection is not None and (not isinstance(selection, Value) or selection.typ != TYPE_BOOL): + if selection is not None and (not isinstance(selection, (Value, DeferredConstant)) or selection.typ != TYPE_BOOL): raise CompileError("set_position(..., selection=...) expects Bool selection") node = _new_node(group, "GeometryNodeSetPosition", x, y) group.links.new(geo.socket, node.inputs[0]) node.inputs[1].default_value = True if selection is not None: - group.links.new(selection.socket, node.inputs[1]) - group.links.new(pos.socket, node.inputs[2]) + deliver_input(group, node.inputs[1], selection, context="selection field") + deliver_input(group, node.inputs[2], pos, context="set_position() Position") return Value(node.outputs[0], TYPE_GEOMETRY) @@ -388,34 +393,38 @@ def _instance_on_points(group, instance, points, *, selection, scale, rotation, raise CompileError("instance_on_points(instance, points) first argument must be Geometry") if points.typ != TYPE_GEOMETRY: raise CompileError("instance_on_points(instance, points) second argument must be Geometry") - if selection is not None and (not isinstance(selection, Value) or selection.typ != TYPE_BOOL): + if selection is not None and (not isinstance(selection, (Value, DeferredConstant)) or selection.typ != TYPE_BOOL): raise CompileError("instance_on_points selection= expects Bool") node = _new_node(group, "GeometryNodeInstanceOnPoints", x, y) group.links.new(points.socket, node.inputs[0]) node.inputs[1].default_value = True if selection is not None: - group.links.new(selection.socket, node.inputs[1]) + deliver_input(group, node.inputs[1], selection, context="selection field") group.links.new(instance.socket, node.inputs[2]) if scale is not None: - if _is_const_number(scale): - _set_vector_socket_default(node.inputs[6], (scale, scale, scale)) - elif _is_const_vector_like(scale): - _set_vector_socket_default(node.inputs[6], scale) - elif isinstance(scale, Value) and scale.typ == TYPE_VECTOR: - group.links.new(scale.socket, node.inputs[6]) + if isinstance(scale, DeferredConstant) and _is_number_type(scale.typ): + scale = (scale.value,) * 3 + elif _is_const_number(scale): + scale = (scale,) * 3 + if _is_const_vector_like(scale) or ( + isinstance(scale, (Value, DeferredConstant)) and scale.typ == TYPE_VECTOR + ): + _set_vector_socket_value(group, node.inputs[6], scale, x, y, "instance_on_points scale") elif isinstance(scale, Value) and _is_number_type(scale.typ): - v = _combine_xyz(group, scale, scale, scale, x - 180, y - 80) - group.links.new(v.socket, node.inputs[6]) + vector = _combine_xyz(group, scale, scale, scale, x - 180, y - 80) + deliver_input(group, node.inputs[6], vector, context="instance_on_points scale") else: raise CompileError("instance_on_points scale= expects Float/Int or Vector") if rotation is not None: - if _is_const_vector_like(rotation): - _set_rotation_socket_default(node.inputs[5], rotation) + if isinstance(rotation, DeferredConstant) and rotation.typ == TYPE_VECTOR: + rotation = DeferredConstant(TYPE_ROTATION, rotation.value) + elif _is_const_vector_like(rotation): + rotation = DeferredConstant(TYPE_ROTATION, tuple(rotation)) elif isinstance(rotation, Value) and rotation.typ == TYPE_VECTOR: - rot = _euler_to_rotation(group, rotation, x - 180, y - 120) - group.links.new(rot.socket, node.inputs[5]) + rotation = _euler_to_rotation(group, rotation, x - 180, y - 120) else: raise CompileError("instance_on_points rotation= expects Vector in radians") + deliver_input(group, node.inputs[5], rotation, context="instance_on_points rotation") out = Value(node.outputs[0], TYPE_GEOMETRY) if realize: return _realize_instances(group, out, x + 240, y) @@ -446,11 +455,11 @@ def _sample_index_geometry(group, geometry, value, index, *, domain, clamp, x=0, node.domain = domain node.clamp = clamp group.links.new(geometry.socket, node.inputs["Geometry"]) - group.links.new(value.socket, node.inputs["Value"]) + deliver_input(group, node.inputs["Value"], value, context="attribute Value") if constant_index is None: - group.links.new(index.socket, node.inputs["Index"]) + deliver_input(group, node.inputs["Index"], index, context="sample_index() Index") else: - node.inputs["Index"].default_value = constant_index + deliver_input(group, node.inputs["Index"], constant_index, context="sample_index() Index") return Value(node.outputs["Value"], value.typ) @@ -468,7 +477,7 @@ def _capture_attribute_geometry(group, geometry, value, *, selection, domain, da if socket_type not in socket_type_to_value_type: raise CompileError("capture_attribute() supports Float, Int, Bool and Vector values (also Color and Rotation)") domain = normalize_attribute_domain(domain, "capture_attribute()") - if selection is not None and (not isinstance(selection, Value) or selection.typ != TYPE_BOOL): + if selection is not None and (not isinstance(selection, (Value, DeferredConstant)) or selection.typ != TYPE_BOOL): raise CompileError("capture_attribute() selection= must be a Bool expression") node = _new_node(group, "GeometryNodeCaptureAttribute", x, y) node.domain = domain @@ -478,5 +487,10 @@ def _capture_attribute_geometry(group, geometry, value, *, selection, domain, da node.inputs["Selection"].default_value = True else: group.links.new(selection.socket, node.inputs["Selection"]) - group.links.new(value.socket, node.inputs["Value"]) + if isinstance(value, Value) and CAPTURE_ITEM_TYPES.get(value.typ) != socket_type: + # Existing explicit capture type overrides allow Blender to convert a + # linked field; this is not an implicit raw constant conversion. + group.links.new(value.socket, node.inputs["Value"]) + else: + deliver_input(group, node.inputs["Value"], value, context="attribute Value") return Value(node.outputs["Geometry"], TYPE_GEOMETRY), Value(node.outputs["Value"], socket_type_to_value_type[socket_type]) diff --git a/blender/nodes.py b/blender/nodes.py index 1613106..3ac9414 100644 --- a/blender/nodes.py +++ b/blender/nodes.py @@ -5,7 +5,9 @@ from .socket_types import socket_type_for_nf_type from ..errors import CompileError from ..semantic.numeric_semantics import normalize_float_constant, normalize_int_constant -from .values import Value +from .values import Value, DeferredConstant +from .input_delivery import deliver_input, require_output +from .socket_types import runtime_socket_nf_type, runtime_socket_owner_tree @@ -87,7 +89,7 @@ def _math(group, operation, args, x=0, y=0): for i, arg in enumerate(args): if not _is_number_type(arg.typ): raise CompileError(f"Math operation {operation} expects numeric input") - group.links.new(arg.socket, node.inputs[i]) + deliver_input(group, node.inputs[i], arg, context=f"{operation} input {i}") return Value(node.outputs[0], TYPE_FLOAT) @@ -98,7 +100,7 @@ def _integer_math(group, operation, args, x=0, y=0): for i, arg in enumerate(args): if arg.typ is not TYPE_INT: raise CompileError(f"Integer Math operation {operation} expects Int input") - group.links.new(arg.socket, node.inputs[i]) + deliver_input(group, node.inputs[i], arg, context=f"{operation} input {i}") return Value(node.outputs[0], TYPE_INT) def _vector_math(group, operation, args, out_type=TYPE_VECTOR, x=0, y=0): @@ -108,10 +110,18 @@ def _vector_math(group, operation, args, out_type=TYPE_VECTOR, x=0, y=0): vi = 0 for arg in args: if arg.typ == TYPE_VECTOR: - group.links.new(arg.socket, node.inputs[vi]) + if isinstance(arg, Value) and runtime_socket_nf_type(arg.socket) is TYPE_ROTATION: + # Object Info exposes Rotation as a physical Rotation socket, + # while its established NodeForge object property is Vector. + # Preserve Blender's existing Rotation -> Vector field link. + if runtime_socket_owner_tree(arg.socket) is not group or not getattr(arg.socket, "is_output", False): + raise CompileError(f"{operation} Vector input: foreign or non-output Rotation socket") + group.links.new(arg.socket, node.inputs[vi]) + else: + deliver_input(group, node.inputs[vi], arg, context=f"{operation} Vector input") vi += 1 elif _is_number_type(arg.typ): - group.links.new(arg.socket, node.inputs[3]) + deliver_input(group, node.inputs[3], arg, context=f"{operation} scalar input") else: raise CompileError(f"Vector Math {operation} got unsupported type {arg.typ}") return Value(node.outputs[1 if out_type == TYPE_FLOAT else 0], out_type) @@ -131,12 +141,12 @@ def _combine_xyz_mixed(group, comps, x=0, y=0): raise CompileError("vector(x, y, z) expects 3 arguments") node = _new_node(group, "ShaderNodeCombineXYZ", x, y) for i, val in enumerate(comps): - if isinstance(val, Value): + if isinstance(val, (Value, DeferredConstant)): if not _is_number_type(val.typ): raise CompileError("vector(x, y, z) expects numeric arguments") - group.links.new(val.socket, node.inputs[i]) + deliver_input(group, node.inputs[i], val, context=f"vector component {i}") elif type(val) in {int, float}: - node.inputs[i].default_value = normalize_float_constant(val) + deliver_input(group, node.inputs[i], normalize_float_constant(val), context=f"vector component {i}") else: raise CompileError("vector(x, y, z) expects numeric arguments") return Value(node.outputs[0], TYPE_VECTOR) @@ -146,7 +156,7 @@ def _separate_xyz(group, val, component, x=0, y=0): if val.typ != TYPE_VECTOR: raise CompileError(".x/.y/.z can only be used on Vector values") node = _new_node(group, "ShaderNodeSeparateXYZ", x, y) - group.links.new(val.socket, node.inputs[0]) + deliver_input(group, node.inputs[0], val, context="separate xyz") return Value(node.outputs[{"x": 0, "y": 1, "z": 2}[component]], TYPE_FLOAT) def _compare(group, operation, left, right, x=0, y=0): @@ -167,8 +177,15 @@ def _compare(group, operation, left, right, x=0, y=0): if getattr(socket, "name", None) == "Epsilon": socket.default_value = 0.0 break - group.links.new(left.socket, node.inputs[0]) - group.links.new(right.socket, node.inputs[1]) + for index, value in enumerate((left, right)): + if data_type == "INT" and value.typ is TYPE_BOOL and isinstance(value, DeferredConstant): + # Blender represents Bool comparisons with integer inputs; this + # conversion is specific to Compare, not a general raw socket cast. + value = DeferredConstant(TYPE_INT, int(value.value)) + if data_type == "INT" and value.typ is TYPE_BOOL and isinstance(value, Value): + group.links.new(value.socket, node.inputs[index]) + else: + deliver_input(group, node.inputs[index], value, context="Compare input") return Value(node.outputs[0], TYPE_BOOL) def _boolean_math(group, operation, args, x=0, y=0): @@ -178,7 +195,7 @@ def _boolean_math(group, operation, args, x=0, y=0): for i, arg in enumerate(args): if arg.typ != TYPE_BOOL: raise CompileError("Boolean operations expect Bool values") - group.links.new(arg.socket, node.inputs[i]) + deliver_input(group, node.inputs[i], arg, context=f"{operation} input {i}") return Value(node.outputs[0], TYPE_BOOL) def _switch(group, cond, false_val, true_val, x=0, y=0): @@ -189,9 +206,9 @@ def _switch(group, cond, false_val, true_val, x=0, y=0): raise CompileError("select() true/false values must have same type") node = _new_node(group, "GeometryNodeSwitch", x, y) node.input_type = SWITCH_INPUT_TYPES[false_val.typ] - group.links.new(cond.socket, node.inputs[0]) - group.links.new(false_val.socket, node.inputs[1]) - group.links.new(true_val.socket, node.inputs[2]) + deliver_input(group, node.inputs[0], cond, context="Switch condition") + deliver_input(group, node.inputs[1], false_val, context="Switch false input") + deliver_input(group, node.inputs[2], true_val, context="Switch true input") return Value(node.outputs[0], false_val.typ) def _position(group, x=0, y=0): diff --git a/tests/blender/test_consumer_aware_constants.py b/tests/blender/test_consumer_aware_constants.py index 58a2994..af349a3 100644 --- a/tests/blender/test_consumer_aware_constants.py +++ b/tests/blender/test_consumer_aware_constants.py @@ -356,3 +356,75 @@ def shape(): def shape(): return node("GeometryNodeMeshCube", inputs={"Vertices X": True}, output="Mesh", typ=Geometry) ''', "NFDeferred_raw_bad_bool") + + +def test_expression_consumer_defaults_keep_runtime_producer_links(): + """Math and Combine XYZ inline constants occupy sockets, not extra nodes.""" + from NodeForge.blender.nodes import _math, _combine_xyz_mixed + from NodeForge.blender.values import DeferredConstant, Value + from NodeForge.nf_types import NFType + + group = bpy.data.node_groups.new("NFDeferred_expression", "GeometryNodeTree") + try: + source = group.nodes.new("ShaderNodeValue") + operand = Value(source.outputs[0], NFType.FLOAT) + result = _math(group, "ADD", (operand, DeferredConstant(NFType.FLOAT, 5.0))) + math_node = result.socket.node + assert math_node.inputs[0].is_linked + assert not math_node.inputs[1].is_linked + assert math_node.inputs[1].default_value == 5.0 + vector = _combine_xyz_mixed(group, [operand, DeferredConstant(NFType.INT, 2), 3.0]) + combine = vector.socket.node + assert combine.inputs[0].is_linked + assert not combine.inputs[1].is_linked and combine.inputs[1].default_value == 2.0 + assert not combine.inputs[2].is_linked and combine.inputs[2].default_value == 3.0 + assert len([n for n in group.nodes if n.bl_idname == "ShaderNodeValue"]) == 1 + finally: + bpy.data.node_groups.remove(group, do_unlink=True) + + +@pytest.mark.parametrize("flag", [True, False]) +def test_deferred_bool_compare_uses_consumer_int_default_not_global_cast(flag): + """Boolean Compare has Int inputs but source Bool links retain their identity.""" + from NodeForge.blender.nodes import _compare + from NodeForge.blender.values import DeferredConstant, Value + from NodeForge.nf_types import NFType + + group = bpy.data.node_groups.new("NFDeferred_bool_compare", "GeometryNodeTree") + try: + physical = group.nodes.new("FunctionNodeInputBool") + physical.boolean = flag + result = _compare( + group, "EQUAL", DeferredConstant(NFType.BOOL, flag), + Value(physical.outputs[0], NFType.BOOL), + ) + compare = result.socket.node + assert compare.data_type == "INT" + assert not compare.inputs[0].is_linked and compare.inputs[0].default_value == int(flag) + assert compare.inputs[1].is_linked + assert next(l for l in group.links if l.to_socket == compare.inputs[1]).from_node == physical + assert not any(n.bl_idname == "FunctionNodeInputInt" for n in group.nodes) + finally: + bpy.data.node_groups.remove(group, do_unlink=True) + + +def test_geometry_consumer_direct_vector_and_implicit_position_link(): + """Cube Size is stored directly while Set Position uses a linked explicit zero.""" + from NodeForge.blender.geometry import _cube_geometry, _set_position_geometry + from NodeForge.blender.values import DeferredConstant + from NodeForge.nf_types import NFType + + group = bpy.data.node_groups.new("NFDeferred_geometry", "GeometryNodeTree") + try: + size = DeferredConstant(NFType.VECTOR, (2, 3, 4)) + cube = _cube_geometry(group, size) + assert not cube.socket.node.inputs["Size"].is_linked + assert tuple(cube.socket.node.inputs["Size"].default_value) == size.value + moved = _set_position_geometry( + group, cube, DeferredConstant(NFType.VECTOR, (0, 0, 0)), selection=None, + ) + node = moved.socket.node + assert node.inputs["Position"].is_linked + assert sum(n.bl_idname == "ShaderNodeCombineXYZ" for n in group.nodes) == 1 + finally: + bpy.data.node_groups.remove(group, do_unlink=True) diff --git a/tests/unit/test_numeric_semantics.py b/tests/unit/test_numeric_semantics.py index f498366..88337a8 100644 --- a/tests/unit/test_numeric_semantics.py +++ b/tests/unit/test_numeric_semantics.py @@ -526,61 +526,23 @@ def test_backend_compare_uses_int_or_float_contract_and_zero_float_epsilon(): from NodeForge.blender.nodes import _compare from NodeForge.blender.values import Value - class Socket: - def __init__(self, name=""): - self.name = name - self.default_value = None - - class SocketList(list): - def __getitem__(self, key): - if isinstance(key, str): - for socket in self: - if socket.name == key: - return socket - raise KeyError(key) - return super().__getitem__(key) - - class Node: - def __init__(self): - self.bl_idname = "FunctionNodeCompare" - self.location = (0, 0) - self.operation = None - self.data_type = None - self.inputs = SocketList([Socket("A"), Socket("B"), Socket("Epsilon")]) - self.outputs = SocketList([Socket("Result")]) - - class Nodes(list): - def new(self, bl_idname): - assert bl_idname == "FunctionNodeCompare" - node = Node() - self.append(node) - return node - - class Links(list): - def new(self, from_socket, to_socket): - self.append((from_socket, to_socket)) - - class Group: - def __init__(self): - self.nodes = Nodes() - self.links = Links() - - int_group = Group() + # Shared fake nodes now model physical input ownership and dynamic types. + int_group = _FakeGroup() result = _compare( int_group, "EQUAL", - Value(Socket(), TYPE_INT), - Value(Socket(), TYPE_INT), + Value(_FakeSocket(), TYPE_INT), + Value(_FakeSocket(), TYPE_INT), ) assert result.typ is TYPE_BOOL assert int_group.nodes[0].data_type == "INT" - float_group = Group() + float_group = _FakeGroup() result = _compare( float_group, "EQUAL", - Value(Socket(), TYPE_INT), - Value(Socket(), TYPE_FLOAT), + Value(_FakeSocket(), TYPE_INT), + Value(_FakeSocket(), TYPE_FLOAT), ) assert result.typ is TYPE_BOOL assert float_group.nodes[0].data_type == "FLOAT" @@ -663,12 +625,56 @@ def analyze(source): analyze('input_float("X", default=True + 1)') +@pytest.fixture(autouse=True) +def _allow_unowned_fake_source_sockets(monkeypatch): + """Legacy numeric unit fakes omit source RNA; Blender suite checks owner/type.""" + from NodeForge.blender import input_delivery + + monkeypatch.setattr( + input_delivery, "validate_runtime_value_socket", + lambda socket, _typ, _group, **_kwargs: socket, + ) + + class _FakeSocket: """Minimal socket used to exercise the real Blender-lowering helpers without bpy.""" - def __init__(self, name=""): + def __init__(self, name="", *, index=0, is_output=False): self.name = name + self.index = index + self.is_output = is_output self.default_value = None + self.hide_value = False + self.is_multi_input = False + self.is_unavailable = False + self.enabled = True + self.node = None + + @property + def bl_idname(self): + """Expose the same type-dependent input/output boundary as Blender RNA.""" + node = self.node + if node is None: + return "NodeSocketFloat" + type_name = node.bl_idname + if self.is_output: + return { + "FunctionNodeInputInt": "NodeSocketInt", + "FunctionNodeInputBool": "NodeSocketBool", + "FunctionNodeIntegerMath": "NodeSocketInt", + "FunctionNodeCompare": "NodeSocketBool", + "FunctionNodeBooleanMath": "NodeSocketBool", + "ShaderNodeCombineXYZ": "NodeSocketVector", + }.get(type_name, "NodeSocketFloat") + if type_name == "FunctionNodeIntegerMath": + return "NodeSocketInt" + if type_name == "FunctionNodeBooleanMath": + return "NodeSocketBool" + if type_name == "FunctionNodeCompare": + return {"INT": "NodeSocketInt", "VECTOR": "NodeSocketVector"}.get(node.data_type, "NodeSocketFloat") + if type_name == "ShaderNodeVectorMath" and self.index in {0, 1}: + return "NodeSocketVector" + return "NodeSocketFloat" class _FakeSockets(list): @@ -695,17 +701,24 @@ def __init__(self, bl_idname): self.data_type = None if bl_idname == "FunctionNodeCompare": names = ["A", "B", "Epsilon", "", "", "", "", ""] - self.inputs = _FakeSockets([_FakeSocket(name) for name in names]) + self.inputs = _FakeSockets([_FakeSocket(name, index=i) for i, name in enumerate(names)]) else: - self.inputs = _FakeSockets([_FakeSocket() for _ in range(8)]) - self.outputs = _FakeSockets([_FakeSocket() for _ in range(4)]) + self.inputs = _FakeSockets([_FakeSocket(index=i) for i in range(8)]) + self.outputs = _FakeSockets([_FakeSocket(index=i, is_output=True) for i in range(4)]) + for socket in (*self.inputs, *self.outputs): + socket.node = self class _FakeNodes(list): """Node collection implementing ``nodes.new`` for numeric backend tests.""" + def __init__(self, owner): + super().__init__() + self.owner = owner + def new(self, bl_idname): node = _FakeNode(bl_idname) + node.id_data = self.owner self.append(node) return node @@ -722,7 +735,7 @@ class _FakeGroup: """Minimal Geometry Nodes group substrate for pure backend selection tests.""" def __init__(self): - self.nodes = _FakeNodes() + self.nodes = _FakeNodes(self) self.links = _FakeLinks() diff --git a/tests/unit/test_semantic_backend_contract.py b/tests/unit/test_semantic_backend_contract.py index b7e0a27..019a5cb 100644 --- a/tests/unit/test_semantic_backend_contract.py +++ b/tests/unit/test_semantic_backend_contract.py @@ -33,6 +33,27 @@ pytestmark = pytest.mark.unit + +@pytest.fixture(autouse=True) +def _untyped_graph_substrate(monkeypatch): + """The host-only shape matrix uses untyped sockets, not real Blender RNA. + + Socket legality is tested against Blender-owned sockets in the dedicated + input-delivery tests. Keep this suite focused on analyzer/backend IR shapes. + """ + from NodeForge.blender import nodes as backend_nodes + from NodeForge.blender import geometry as backend_geometry + from NodeForge.blender.values import DeferredConstant, Value + + def fake_delivery(group, socket, operand, *, context="node input"): + if isinstance(operand, Value): + group.links.new(operand.socket, socket) + else: + socket.default_value = operand.value if isinstance(operand, DeferredConstant) else operand + + monkeypatch.setattr(backend_nodes, "deliver_input", fake_delivery) + monkeypatch.setattr(backend_geometry, "deliver_input", fake_delivery) + def _empty_callable_environment(): """Return an empty immutable callable namespace for non-call semantic tests.""" return CallableEnvironment(frozenset(), {}, {}, {}) diff --git a/tests/unit/test_semantic_ir.py b/tests/unit/test_semantic_ir.py index 4f734f5..500c656 100644 --- a/tests/unit/test_semantic_ir.py +++ b/tests/unit/test_semantic_ir.py @@ -1415,6 +1415,26 @@ def __init__(self, name): self.default_value = None +@pytest.fixture(autouse=True) +def _sample_index_untyped_socket_compatibility(monkeypatch): + """Sample Index helper unit stubs lack Blender RNA ownership/type metadata. + + The dedicated Blender tests exercise strict deliver_input validation. + """ + original = geometry_backend.deliver_input + + def mock_sample_delivery(group, socket, operand, *, context="node input"): + if isinstance(socket, _SampleSocket): + if isinstance(operand, Value): + group.links.new(operand.socket, socket) + else: + socket.default_value = operand.value if hasattr(operand, "value") else operand + return None + return original(group, socket, operand, context=context) + + monkeypatch.setattr(geometry_backend, "deliver_input", mock_sample_delivery) + + class _SampleNode: """Sample Index stand-in that exposes dynamic sockets only after data_type is set.""" From d18ab556f90db14aaa0ecb6db15aa2f9e864cd7c Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 01:09:31 +0000 Subject: [PATCH 05/14] feat: deliver constants to dynamic Bundle inputs --- blender/bundle.py | 24 ++++----- tests/blender/test_bundle_runtime.py | 76 ++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 12 deletions(-) diff --git a/blender/bundle.py b/blender/bundle.py index 7d47d74..ae1afca 100644 --- a/blender/bundle.py +++ b/blender/bundle.py @@ -8,6 +8,7 @@ ) from ..errors import CompileError from .nodes import _new_node +from .input_delivery import deliver_input, require_output from .values import make_value _BUNDLE_SOCKET_TYPES = { @@ -24,7 +25,7 @@ } def build_bundle(group, items, *, x=0, y=0): - """Build a Combine Bundle node from already-materialized runtime item Values.""" + """Build a Combine Bundle, delivering items after dynamic sockets are defined.""" node = _new_node(group, "NodeCombineBundle", x, y) try: for item_name, value in items: @@ -41,15 +42,12 @@ def build_bundle(group, items, *, x=0, y=0): raise CompileError( f"bundle(): generated input order mismatch for {item_name!r}; got {getattr(socket, 'name', None)!r}" ) - try: - group.links.new(value.socket, socket) - except Exception as exc: - raise CompileError(f"bundle(): failed to link item {item_name!r}: {exc}") from exc + deliver_input(group, socket, value, context=f"bundle() item {item_name!r}") return make_value(node.outputs["Bundle"], TYPE_BUNDLE) def build_bundle_get(group, bundle_value, path_value, output_type, *, x=0, y=0): - """Build Get Bundle Item from already-materialized runtime operands.""" + """Build Get Bundle Item with a physical Bundle and consumer-aware Path.""" if bundle_value.typ != TYPE_BUNDLE: raise CompileError(f"bundle_get() first argument expects Bundle, got {bundle_value.typ}") if path_value.typ != TYPE_STRING: @@ -58,15 +56,16 @@ def build_bundle_get(group, bundle_value, path_value, output_type, *, x=0, y=0): node = _new_node(group, "NodeGetBundleItem", x, y) try: node.socket_type = socket_type - group.links.new(bundle_value.socket, node.inputs["Bundle"]) - group.links.new(path_value.socket, node.inputs["Path"]) except Exception as exc: raise CompileError(f"bundle_get(): failed to configure Get Bundle Item: {exc}") from exc + physical_bundle = require_output(group, bundle_value, context="bundle_get() Bundle") + deliver_input(group, node.inputs["Bundle"], physical_bundle, context="bundle_get() Bundle") + deliver_input(group, node.inputs["Path"], path_value, context="bundle_get() Path") return make_value(node.outputs["Item"], output_type) def build_bundle_set(group, bundle_value, path_value, item_value, *, x=0, y=0): - """Build Store Bundle Item from already-materialized runtime operands.""" + """Build Store Bundle Item with typed Path/Item socket delivery.""" if bundle_value.typ != TYPE_BUNDLE: raise CompileError(f"bundle_set() first argument expects Bundle, got {bundle_value.typ}") if path_value.typ != TYPE_STRING: @@ -75,11 +74,12 @@ def build_bundle_set(group, bundle_value, path_value, item_value, *, x=0, y=0): node = _new_node(group, "NodeStoreBundleItem", x, y) try: node.socket_type = socket_type - group.links.new(bundle_value.socket, node.inputs["Bundle"]) - group.links.new(path_value.socket, node.inputs["Path"]) - group.links.new(item_value.socket, node.inputs["Item"]) except Exception as exc: raise CompileError(f"bundle_set(): failed to configure Store Bundle Item: {exc}") from exc + physical_bundle = require_output(group, bundle_value, context="bundle_set() Bundle") + deliver_input(group, node.inputs["Bundle"], physical_bundle, context="bundle_set() Bundle") + deliver_input(group, node.inputs["Path"], path_value, context="bundle_set() Path") + deliver_input(group, node.inputs["Item"], item_value, context="bundle_set() Item") return make_value(node.outputs["Bundle"], TYPE_BUNDLE) diff --git a/tests/blender/test_bundle_runtime.py b/tests/blender/test_bundle_runtime.py index 42af9e4..7ee0e29 100644 --- a/tests/blender/test_bundle_runtime.py +++ b/tests/blender/test_bundle_runtime.py @@ -345,3 +345,79 @@ def nf_fixture(path: String['Path'] = 'value'): check(len([node for node in group.nodes if node.bl_idname == "NodeGetBundleItem"]) == 1, "Bundle IRBody get topology changed") check(len([node for node in group.nodes if node.bl_idname == "NodeStoreBundleItem"]) == 1, "Bundle IRBody set topology changed") bpy.data.node_groups.remove(group) + + +def test_bundle_backend_delivers_deferred_primitives_into_dynamic_defaults(): + """An explicitly supplied primitive uses the generated Bundle socket default.""" + from NodeForge.blender.bundle import build_bundle, build_bundle_get, build_bundle_set + from NodeForge.blender.values import DeferredConstant, Value + from NodeForge.nf_types import NFType + + group = bpy.data.node_groups.new("NFBundle_deferred_direct", "GeometryNodeTree") + try: + geometry = group.nodes.new("GeometryNodeMeshCube") + state = build_bundle(group, [ + ("value", DeferredConstant(NFType.FLOAT, 2.5)), + ("count", DeferredConstant(NFType.INT, 3)), + ("flag", DeferredConstant(NFType.BOOL, True)), + ("direction", DeferredConstant(NFType.VECTOR, (1.0, 2.0, 3.0))), + ("label", DeferredConstant(NFType.STRING, "ok")), + ("color", DeferredConstant(NFType.COLOR, (0.1, 0.2, 0.3, 0.4))), + ("geometry", Value(geometry.outputs["Mesh"], NFType.GEOMETRY)), + ]) + combine = _one_node(group, "NodeCombineBundle") + check([item.name for item in combine.bundle_items] == [ + "value", "count", "flag", "direction", "label", "color", "geometry" + ], "Bundle item order changed") + check(not any(combine.inputs[name].is_linked for name in + ("value", "count", "flag", "direction", "label", "color")), + "primitive Bundle items created redundant links") + check(combine.inputs["value"].default_value == 2.5, "Float Bundle default mismatch") + check(combine.inputs["count"].default_value == 3, "Int Bundle default mismatch") + check(combine.inputs["flag"].default_value is True, "Bool Bundle default mismatch") + check(tuple(combine.inputs["direction"].default_value) == (1, 2, 3), "Vector Bundle default mismatch") + check(combine.inputs["label"].default_value == "ok", "String Bundle default mismatch") + check(tuple(round(x, 3) for x in combine.inputs["color"].default_value) == (0.1, 0.2, 0.3, 0.4), "Color Bundle default mismatch") + check(combine.inputs["geometry"].is_linked, "runtime geometry Bundle item lost link") + + got = build_bundle_get(group, state, DeferredConstant(NFType.STRING, "value"), NFType.FLOAT) + read = _one_node(group, "NodeGetBundleItem") + check(read.inputs["Bundle"].is_linked, "Get Bundle input lost link") + check(read.inputs["Path"].default_value == "value" and not read.inputs["Path"].is_linked, + "Get Bundle Path must be a direct String default") + check(got.typ == NFType.FLOAT, "Get Bundle result type mismatch") + + build_bundle_set(group, state, DeferredConstant(NFType.STRING, "value"), DeferredConstant(NFType.FLOAT, 5.0)) + store = _one_node(group, "NodeStoreBundleItem") + check(store.inputs["Bundle"].is_linked, "Store Bundle source lost link") + check(store.inputs["Path"].default_value == "value" and not store.inputs["Path"].is_linked, + "Store Bundle Path must be a direct String default") + check(store.inputs["Item"].default_value == 5.0 and not store.inputs["Item"].is_linked, + "Store Bundle Item must be a direct Float default") + check(not any(n.bl_idname in ("ShaderNodeValue", "FunctionNodeInputInt", "FunctionNodeInputBool", "FunctionNodeInputString", "ShaderNodeCombineXYZ") for n in group.nodes), + "redundant Bundle constant producers remain") + finally: + bpy.data.node_groups.remove(group, do_unlink=True) + + +def test_bundle_backend_rejects_unsupported_and_foreign_runtime_items(): + """Bundle validation occurs at dynamic item or physical source boundary.""" + from NodeForge.blender.bundle import build_bundle, build_bundle_get, build_bundle_set + from NodeForge.blender.values import DeferredConstant, Value + from NodeForge.errors import CompileError + from NodeForge.nf_types import NFType + + group = bpy.data.node_groups.new("NFBundle_deferred_errors", "GeometryNodeTree") + other = bpy.data.node_groups.new("NFBundle_deferred_foreign", "GeometryNodeTree") + try: + with pytest.raises(CompileError, match="unsupported Bundle item type"): + build_bundle(group, [("rotation", DeferredConstant(NFType.ROTATION, (0.0, 0.0, 0.0)))]) + valid = build_bundle(group, [("number", DeferredConstant(NFType.INT, 1))]) + with pytest.raises(CompileError, match="path expects String"): + build_bundle_get(group, valid, DeferredConstant(NFType.FLOAT, 1.0), NFType.INT) + foreign = other.nodes.new("ShaderNodeValue") + with pytest.raises(CompileError, match="current Geometry Nodes group"): + build_bundle_set(group, valid, DeferredConstant(NFType.STRING, "number"), Value(foreign.outputs[0], NFType.FLOAT)) + finally: + bpy.data.node_groups.remove(group, do_unlink=True) + bpy.data.node_groups.remove(other, do_unlink=True) From 29611b1abacbd3663b1f78e7503079c26b4f62ef Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 01:20:57 +0000 Subject: [PATCH 06/14] feat: preserve deferred operands across inline and physical boundaries --- blender/geometry.py | 2 +- blender/input_delivery.py | 16 +- blender/ir_lowering.py | 184 +++++++++++++----- .../cases/expected/binary_mul_add.json | 30 +-- .../cases/expected/comparison_chained.json | 70 ++----- .../expected/for_unpack_append_compat.json | 38 +--- .../for_unpack_geometry_builder_compat.json | 63 +----- .../cases/expected/literal_bool.json | 44 +---- .../expected/top_level_definition_chain.json | 132 ++----------- .../expected/top_level_forward_mixed.json | 26 +-- .../top_level_import_alias_identity.json | 22 +-- .../expected/top_level_import_multi.json | 44 +---- .../top_level_import_shared_unique.json | 44 +---- .../expected/top_level_lexical_shadowing.json | 22 +-- .../expected/top_level_panel_defaults.json | 28 +-- .../expected/top_level_shared_entries.json | 88 +-------- .../expected/top_level_tuple_outputs.json | 46 +---- .../cases/expected/unary_minus_float.json | 22 +-- .../cases/expected/unary_minus_vector.json | 22 +-- .../expected/unary_plus_const_array.json | 8 - .../cases/expected/vector_divide_scalar.json | 28 +-- tests/blender/test_inline_source_calls.py | 19 +- tests/blender/test_sample_index.py | 32 ++- tests/blender/test_semantic_ir_compile.py | 43 ++-- tests/unit/test_inline_lowering.py | 59 +++++- tests/unit/test_semantic_backend_contract.py | 17 +- tests/unit/test_semantic_ir.py | 21 +- 27 files changed, 382 insertions(+), 788 deletions(-) diff --git a/blender/geometry.py b/blender/geometry.py index 3ba2f1d..db955c0 100644 --- a/blender/geometry.py +++ b/blender/geometry.py @@ -443,7 +443,7 @@ def _sample_index_geometry(group, geometry, value, index, *, domain, clamp, x=0, domain = normalize_attribute_domain(domain, "sample_index()") if type(clamp) is not bool: raise CompileError("sample_index() clamp= must be a compile-time Bool") - if isinstance(index, Value): + if isinstance(index, (Value, DeferredConstant)): if index.typ != TYPE_INT: raise CompileError("sample_index() index must be Int") constant_index = None diff --git a/blender/input_delivery.py b/blender/input_delivery.py index 0e4ee95..8c889be 100644 --- a/blender/input_delivery.py +++ b/blender/input_delivery.py @@ -12,7 +12,7 @@ from ..errors import CompileError from ..nf_types import NFType from ..semantic.callable_contracts import canonicalize_group_input_default -from .socket_types import runtime_socket_nf_type, validate_runtime_value_socket +from .socket_types import runtime_socket_nf_type, runtime_socket_owner_tree, validate_runtime_value_socket from .values import ConstantPayload, DeferredConstant, Value @@ -136,10 +136,20 @@ def validate_input(group, socket, operand, *, context: str = "node input"): return constant -def require_output(group, operand, *, context: str = "constant") -> Value: +def require_output(group, operand, *, context: str = "constant", allow_native_conversion: bool = False) -> Value: """Return a physical output, allocating one typed producer per deferred owner.""" if isinstance(operand, Value): - validate_runtime_value_socket(operand.socket, operand.typ, group, context=context) + if allow_native_conversion: + # Group outputs have historically accepted Blender's native links + # (notably Object Info Rotation -> NodeForge Vector). Preserve the + # physical source's output/owner invariants without changing types. + source = operand.socket + if (runtime_socket_owner_tree(source) is not group + or not getattr(source, "is_output", False) + or runtime_socket_nf_type(source) is None): + raise CompileError(f"{context}: invalid physical output socket for native group conversion") + else: + validate_runtime_value_socket(operand.socket, operand.typ, group, context=context) return operand if not isinstance(operand, DeferredConstant): raise CompileError(f"{context}: expected a typed backend operand") diff --git a/blender/ir_lowering.py b/blender/ir_lowering.py index 4465b6f..4f23ce4 100644 --- a/blender/ir_lowering.py +++ b/blender/ir_lowering.py @@ -65,7 +65,8 @@ IRRepeat, IRPanelDeclaration, ) -from .values import ObjectValue, Value, make_value +from .values import ObjectValue, Value, DeferredConstant, make_value +from .input_delivery import deliver_input, require_output from ..semantic.callable_contracts import canonicalize_group_input_default, source_argument_type_matches from ..semantic.ir import IRFunctionMaterializationMode from .interface import _create_group_input_socket, _create_interface_panel, _set_socket_default @@ -146,7 +147,7 @@ class BlenderIRLoweringContext: """ group: object - runtime_bindings: Mapping[BindingId, Value] + runtime_bindings: Mapping[BindingId, Value | DeferredConstant] group_context_values: Mapping[GroupContextSlot, Value] = None interface_input_items: dict | None = None source_callable_session: object | None = None @@ -190,9 +191,9 @@ def _materialized_value(materialized, value): def _store_result(materialized, result, value): """Validate and register one backend value for an IR result.""" - if not isinstance(value, Value): + if not isinstance(value, (Value, DeferredConstant)): raise CompileError( - f"Internal error: Semantic IR value v{result.id} materialized as {type(value).__name__}, not Value" + f"Internal error: Semantic IR value v{result.id} has invalid backend type {type(value).__name__}" ) if value.typ != result.typ: raise CompileError( @@ -202,26 +203,17 @@ def _store_result(materialized, result, value): def _lower_literal(context, operation, materialized, x, y): - """Materialize one literal operation with the existing Blender node topology.""" - if operation.result.typ == TYPE_BOOL: - val = _value(context.group, 1.0 if operation.value else 0.0, x, y) - zero = _value(context.group, 0.0, x + 20, y - 40) - result = _compare(context.group, "NOT_EQUAL", val, zero, x, y) - elif operation.result.typ == TYPE_FLOAT: - result = _value(context.group, operation.value, x, y) - elif operation.result.typ == TYPE_INT: - result = _int_value(context.group, operation.value, x, y) - else: - result = _string_value(context.group, operation.value, x, y) + """Keep a typed IR literal detached until a physical input/output needs it.""" + result = DeferredConstant(operation.result.typ, operation.value) _store_result(materialized, operation.result, result) def _lower_binding(context, operation, materialized, runtime_bindings): """Resolve one semantic runtime binding to its backend materialization.""" value = runtime_bindings.get(operation.binding_id) - if not isinstance(value, Value): + if not isinstance(value, (Value, DeferredConstant)): raise CompileError( - f"Internal error: Semantic IR binding {operation.binding_id!r} is no longer a runtime Value" + f"Internal error: Semantic IR binding {operation.binding_id!r} has no backend operand" ) if value.typ != operation.result.typ: raise CompileError( @@ -238,10 +230,10 @@ def _lower_unary(context, operation, materialized, x, y): if operation.operand.typ is TYPE_INT: result = _integer_math(context.group, "NEGATE", [operand], x, y) elif operation.operand.typ is TYPE_FLOAT: - zero = _value(context.group, 0.0, x, y - 40) + zero = DeferredConstant(TYPE_FLOAT, 0.0) result = _math(context.group, "SUBTRACT", [zero, operand], x, y) elif operation.operand.typ == TYPE_VECTOR: - minus_one = _value(context.group, -1.0, x, y - 40) + minus_one = DeferredConstant(TYPE_FLOAT, -1.0) result = _vector_math(context.group, "SCALE", [operand, minus_one], TYPE_VECTOR, x, y) else: raise CompileError( @@ -302,7 +294,7 @@ def _lower_binary(context, operation, materialized, x, y): f"{operation.left.typ} {operation.op} {operation.right.typ}" ) elif operation.op == "DIVIDE" and operation.left.typ == TYPE_VECTOR and operation.right.typ in numeric_types: - inv = _math(context.group, "DIVIDE", [_value(context.group, 1.0, x, y - 40), right], x, y) + inv = _math(context.group, "DIVIDE", [DeferredConstant(TYPE_FLOAT, 1.0), right], x, y) result = _vector_math(context.group, "SCALE", [left, inv], TYPE_VECTOR, x, y) else: raise CompileError( @@ -339,8 +331,8 @@ def _lower_conditional(context, operation, materialized, x, y): def _lower_vector_literal(context, operation, materialized, x, y): - """Materialize one normalized compile-time Vector with existing topology.""" - result = _combine_xyz_mixed(context.group, list(operation.components), x, y) + """Keep a literal Vector detached, preserving its typed components.""" + result = DeferredConstant(TYPE_VECTOR, tuple(operation.components)) _store_result(materialized, operation.result, result) @@ -415,6 +407,12 @@ def _lower_builtin_call(context, operation, operands, x, y): return _field_id(group, x, y) if name == "vector": components = [_slot_value(slot, operands) for slot in options["components"]] + if all(type(component) in {int, float} or isinstance(component, DeferredConstant) + and component.typ in {TYPE_FLOAT, TYPE_INT} for component in components): + return DeferredConstant(TYPE_VECTOR, tuple( + component.value if isinstance(component, DeferredConstant) else component + for component in components + )) return _combine_xyz_mixed(group, components, x, y) if "vector_operation" in options: result_type = operation.results[0].typ @@ -445,8 +443,8 @@ def _lower_builtin_call(context, operation, operands, x, y): return _capture_attribute_geometry( group, operands[0], - operands[1], - selection=selection, + require_output(group, operands[1], context="capture_attribute() field"), + selection=require_output(group, selection, context="capture_attribute() selection") if selection is not None else None, domain=options["domain"], data_type=options["data_type"], x=x, @@ -456,7 +454,7 @@ def _lower_builtin_call(context, operation, operands, x, y): return _sample_index_geometry( group, operands[0], - operands[1], + require_output(group, operands[1], context="sample_index() field"), _slot_value(options["index"], operands), domain=options["domain"], clamp=options["clamp"], @@ -469,6 +467,8 @@ def _lower_builtin_call(context, operation, operands, x, y): value_index = 2 if name_mode[0] == "runtime" else 1 value = operands[value_index] selection = operands[value_index + 1] if len(operands) > value_index + 1 else None + if selection is not None: + selection = require_output(group, selection, context="store_named_attribute() selection") return _store_named_attribute_geometry( group, operands[0], @@ -508,7 +508,7 @@ def _lower_builtin_call(context, operation, operands, x, y): group, operands[0], operands[1], - selection=selection, + selection=require_output(group, selection, context="instance_on_points() selection") if selection is not None else None, scale=_slot_value(options["scale"], operands), rotation=_slot_value(options["rotation"], operands), realize=options["realize"], @@ -613,12 +613,79 @@ def _inline_constant_value(context, typ, value, x, y): def _inline_runtime_value(context, expected, actual, x, y): - """Detach a runtime Value and realize the only permitted numeric widening.""" - if not isinstance(actual, Value) or not source_argument_type_matches(expected, actual.typ): + """Detach physical Values while retaining deferred arguments until use.""" + if not isinstance(actual, (Value, DeferredConstant)) or not source_argument_type_matches(expected, actual.typ): raise CompileError(f"Internal error: inline argument expects {expected}, got {getattr(actual, 'typ', None)}") if expected is TYPE_FLOAT and actual.typ is TYPE_INT: - return _math(context.group, "ADD", [actual, _value(context.group, 0.0, x, y - 60)], x, y) - return make_value(actual.socket, actual.typ) + if isinstance(actual, DeferredConstant): + return DeferredConstant(TYPE_FLOAT, actual.value) + return _math(context.group, "ADD", [actual, DeferredConstant(TYPE_FLOAT, 0.0)], x, y) + if isinstance(actual, Value): + return make_value(actual.socket, actual.typ) + return actual + + +def _inline_parameter_is_direct_single_sink(body, declaration_id): + """Prove one parameter reaches at most one supported, immediate IR consumer. + + Only the prepared typed body is inspected. Loops/branches, nested source + forwarding, output-only values, and multiple uses retain one shared physical + producer per invocation (#59). This does not build a new flattened IR pass. + """ + declarations = (stmt for stmt in body.statements if isinstance(stmt, IRInputDeclaration)) + binding_id = next((stmt.target_binding_id for stmt in declarations + if stmt.declaration_id == declaration_id), None) + if binding_id is None: + return False + consumers = 0 + for stmt in body.statements: + if isinstance(stmt, (IRIf, IRRepeat)): + return False + program = getattr(stmt, "value", None) + if program is None or not hasattr(program, "operations"): + continue + refs = [op.result.id for op in program.operations + if isinstance(op, IRBinding) and op.binding_id == binding_id] + if not refs: + continue + if len(refs) > 1 or getattr(program.result, "id", None) in refs: + return False + ref = refs[0] + used = 0 + for op in program.operations: + if isinstance(op, IRBinding): + continue + if isinstance(op, IRCall): + hits = [index for index, arg in enumerate(op.arguments) if arg.value.id == ref] + if hits: + if op.target.kind is not IRCallableKind.BUILTIN or len(hits) != 1: + return False + if op.target.name not in { + "node", "vector", "cube", "points", "point", "line", "grid", + "set_position", "transform", "instance_on_points", "bundle", + "bundle_get", "bundle_set", "store_named_attribute", "sample_index", + } and "vector_operation" not in dict(op.options): + return False + if op.target.name == "node": + raw = dict(op.options).get("inputs", ()) + if sum(spec == ("runtime", hits[0]) for _selector, spec in raw) != 1: + return False + used += 1 + continue + for attribute in ("operand", "left", "right", "condition", "true_value", "false_value", "value"): + if getattr(getattr(op, attribute, None), "id", None) == ref: + if not isinstance(op, (IRUnary, IRBinary, IRBoolBinary, IRCompare, + IRConditional, IRVectorComponent)): + return False + used += 1 + # A reference without an admitted consumer may be part of a structural + # expression; avoid assuming that such a value is unused. + if used != 1: + return False + consumers += used + if consumers > 1: + return False + return consumers <= 1 def _inline_parameter_bindings(context, operation, operands, prepared, x, y): @@ -660,7 +727,11 @@ def _inline_parameter_bindings(context, operation, operands, prepared, x, y): if mode == "runtime": value = _inline_runtime_value(context, parameter.typ, arg, x - 180, y - offset) else: - value = _inline_constant_value(context, parameter.typ, arg, x - 180, y - offset) + value = DeferredConstant(parameter.typ, arg) + if isinstance(value, DeferredConstant) and not _inline_parameter_is_direct_single_sink( + prepared.group.body, origin + ): + value = require_output(context.group, value, context=f"inline argument {parameter.display_name}") if origin in bound: raise CompileError("Internal error: inline declaration was bound more than once") bound[origin] = value @@ -702,7 +773,8 @@ def _lower_inline_source_call(context, operation, operands, prepared, x, y): layout_origin=child_origin, root_input_endpoint=context.root_input_endpoint, ) - result = lower_body(bound_context, prepared.group.body, inputs, base_depth=0) + result = lower_body(bound_context, prepared.group.body, inputs, base_depth=0, + physical_outputs=False) outputs = result.explicit_outputs if result.explicit_outputs else ( (result.auto_output,) if result.auto_output is not None else () ) @@ -712,7 +784,8 @@ def _lower_inline_source_call(context, operation, operands, prepared, x, y): for (_name, value), output in zip(outputs, prepared.contract.outputs): if value.typ is not output.typ: raise CompileError("Internal error: inline return type disagrees with source contract") - values.append(make_value(value.socket, value.typ)) + physical = require_output(context.group, value, context="inline function return", allow_native_conversion=True) + values.append(make_value(physical.socket, physical.typ)) trace = getattr(context.function_materialization_context, "function_compilation_trace", None) frame = getattr(trace, "current", None) if frame is not None: @@ -801,12 +874,14 @@ def _lower_source_call(context, operation, operands, x, y): for static in operation.static_arguments: if static.parameter_index >= len(physical_inputs): raise CompileError("Internal error: source-call static input position is out of range") - _set_socket_default(physical_inputs[static.parameter_index], static.value) + deliver_input(context.group, physical_inputs[static.parameter_index], + DeferredConstant(static.typ, static.value) if hasattr(static, "typ") else static.value, + context="grouped static argument") for argument, value in zip(operation.arguments, operands): position = argument.parameter_index if position is None or position >= len(physical_inputs): raise CompileError("Internal error: source-call runtime input position is out of range") - context.group.links.new(value.socket, physical_inputs[position]) + deliver_input(context.group, physical_inputs[position], value, context="grouped function argument") physical_outputs = _group_node_outputs(node) values = [] @@ -831,9 +906,11 @@ def _lower_call(context, operation, materialized, x, y): if (operation.extension_materialization is not None and operation.extension_materialization.mode is IRExtensionMaterializationMode.GROUPED): from .extension_group_materializer import materialize_extension_call - result = materialize_extension_call(context, operation, operands, x, y) + result = materialize_extension_call(context, operation, + [require_output(context.group, v, context="grouped extension input") for v in operands], x, y) else: - result = lower_extension_call(context, operation, operands, x, y) + result = lower_extension_call(context, operation, + [require_output(context.group, v, context="extension input") for v in operands], x, y) else: raise CompileError(f"Internal error: unsupported Call IR target kind {operation.target.kind}") _store_call_results(materialized, operation, result) @@ -887,7 +964,7 @@ def _execute_operation(context, operation, materialized, base_depth, runtime_bin return if isinstance(operation, IRContextWrite): value = _materialized_value(materialized, operation.value) - context.group_context_values[operation.slot] = value + context.group_context_values[operation.slot] = require_output(context.group, value, context="group context") return raise CompileError(f"Internal error: unsupported Semantic IR operation {type(operation).__name__}") @@ -909,8 +986,8 @@ def _lower_program_result(context, program, runtime_bindings, base_depth): def _require_body_value_type(value, expected_type): """Reject impossible backend/body semantic type mismatches before publication.""" - if not isinstance(value, Value): - raise CompileError("Internal error: IRBody expression did not materialize a runtime Value") + if not isinstance(value, (Value, DeferredConstant)): + raise CompileError("Internal error: IRBody expression did not produce a backend operand") if value.typ is not expected_type: raise CompileError( f"Internal error: IRBody backend type {value.typ} does not match semantic type {expected_type}" @@ -924,7 +1001,7 @@ class BodyLoweringResult: explicit_outputs: tuple[tuple[str, Value], ...] auto_output: tuple[str, Value] | None - runtime_bindings: Mapping[BindingId, Value] + runtime_bindings: Mapping[BindingId, Value | DeferredConstant] group_context_values: Mapping[GroupContextSlot, Value] def __post_init__(self) -> None: @@ -954,7 +1031,7 @@ def _lower_body_internal( if group_input is None: # Inline parameters are already validated and keyed by BindingId. value = runtime_bindings.get(statement.target_binding_id) - if not isinstance(value, Value) or value.typ is not statement.typ: + if not isinstance(value, (Value, DeferredConstant)) or value.typ is not statement.typ: raise CompileError("Internal error: missing or incompatible prebound inline input") auto_output = (statement.target_name, value) continue @@ -975,6 +1052,12 @@ def _lower_body_internal( _lower_program_result(context, statement.value, runtime_bindings, base_depth), statement.value.result.typ, ) + if statement.value.result.typ is TYPE_VECTOR and isinstance(value, DeferredConstant): + # A named Vector constructor is an intentional source identity (#50). + if any(isinstance(op, IRVectorLiteral) or + isinstance(op, IRCall) and op.target.name == "vector" + for op in statement.value.operations): + value = require_output(context.group, value, context="named Vector") runtime_bindings[statement.binding_id] = value auto_output = (statement.source_name, value) continue @@ -1082,6 +1165,7 @@ def _lower_body_internal( repeat_x, repeat_y, ) + iterations = require_output(context.group, iterations, context="Repeat iterations") context.group.links.new(iterations.socket, ri.inputs[0]) for state in statement.states: try: @@ -1090,6 +1174,7 @@ def _lower_body_internal( raise CompileError(f"Internal error: missing Repeat entry state {state.source_name!r}") from exc if initial.typ is not state.typ: raise CompileError("Internal error: Repeat backend entry type does not match semantic input type") + initial = require_output(context.group, initial, context="Repeat entry state") context.group.links.new(initial.socket, _socket_by_name(ri.inputs, state.source_name)) body_bindings = dict(runtime_bindings) @@ -1112,6 +1197,7 @@ def _lower_body_internal( raise CompileError(f"Internal error: missing Repeat exit state {state.source_name!r}") from exc if final_value.typ is not state.typ: raise CompileError("Internal error: Repeat backend exit type violates semantic state contract") + final_value = require_output(context.group, final_value, context="Repeat exit state") context.group.links.new(final_value.socket, _socket_by_name(ro.inputs, state.source_name)) output_value = Value(_socket_by_name(ro.outputs, state.source_name), state.typ) if state.publish_to_parent: @@ -1127,11 +1213,19 @@ def _lower_body_internal( ) -def lower_body(context, body, initial_runtime_bindings, base_depth=1, *, group_input=None): - """Materialize typed IR using supplied bindings or a physical Group Input node.""" +def lower_body(context, body, initial_runtime_bindings, base_depth=1, *, group_input=None, + physical_outputs=True): + """Lower one body; expose physical outputs for group assembly boundaries.""" if not isinstance(body, IRBody): raise TypeError("body must be an IRBody") - return _lower_body_internal(context, body, initial_runtime_bindings, base_depth, group_input=group_input) + result = _lower_body_internal(context, body, initial_runtime_bindings, base_depth, group_input=group_input) + if not physical_outputs: + return result + outputs = tuple((name, require_output(context.group, v, context="Group Output", allow_native_conversion=True)) + for name, v in result.explicit_outputs) + auto = ((result.auto_output[0], require_output(context.group, result.auto_output[1], + context="Group auto output", allow_native_conversion=True)) if result.auto_output is not None else None) + return BodyLoweringResult(outputs, auto, result.runtime_bindings, result.group_context_values) def _materialize_program_result(materialized, result): diff --git a/tests/blender/expression_characterization/cases/expected/binary_mul_add.json b/tests/blender/expression_characterization/cases/expected/binary_mul_add.json index 9dd6d46..6269e5e 100644 --- a/tests/blender/expression_characterization/cases/expected/binary_mul_add.json +++ b/tests/blender/expression_characterization/cases/expected/binary_mul_add.json @@ -26,7 +26,7 @@ "Socket_0" ], "to": [ - "n3", + "n2", "Value" ] }, @@ -35,16 +35,6 @@ "n0", "Socket_1" ], - "to": [ - "n4", - "Value_001" - ] - }, - { - "from": [ - "n2", - "Integer" - ], "to": [ "n3", "Value_001" @@ -52,17 +42,17 @@ }, { "from": [ - "n3", + "n2", "Value" ], "to": [ - "n4", + "n3", "Value" ] }, { "from": [ - "n4", + "n3", "Value" ], "to": [ @@ -82,24 +72,16 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "FunctionNodeInputInt", - "id": "n2", - "payload": { - "value": 2 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "MULTIPLY" } }, { "bl_idname": "ShaderNodeMath", - "id": "n4", + "id": "n3", "properties": { "operation": "ADD" } diff --git a/tests/blender/expression_characterization/cases/expected/comparison_chained.json b/tests/blender/expression_characterization/cases/expected/comparison_chained.json index 7892472..5499092 100644 --- a/tests/blender/expression_characterization/cases/expected/comparison_chained.json +++ b/tests/blender/expression_characterization/cases/expected/comparison_chained.json @@ -32,7 +32,7 @@ "Socket_0" ], "to": [ - "n4", + "n3", "A" ] }, @@ -42,7 +42,7 @@ "Socket_1" ], "to": [ - "n3", + "n2", "Value" ] }, @@ -52,7 +52,7 @@ "Socket_1" ], "to": [ - "n6", + "n4", "Value" ] }, @@ -62,73 +62,53 @@ "Socket_2" ], "to": [ - "n7", + "n5", "B" ] }, { "from": [ "n2", - "Integer" - ], - "to": [ - "n3", - "Value_001" - ] - }, - { - "from": [ - "n3", "Value" ], "to": [ - "n4", + "n3", "B" ] }, { "from": [ - "n4", + "n3", "Result" ], - "to": [ - "n8", - "Boolean" - ] - }, - { - "from": [ - "n5", - "Integer" - ], "to": [ "n6", - "Value_001" + "Boolean" ] }, { "from": [ - "n6", + "n4", "Value" ], "to": [ - "n7", + "n5", "A" ] }, { "from": [ - "n7", + "n5", "Result" ], "to": [ - "n8", + "n6", "Boolean_001" ] }, { "from": [ - "n8", + "n6", "Boolean" ], "to": [ @@ -148,48 +128,32 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "FunctionNodeInputInt", - "id": "n2", - "payload": { - "value": 2 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "MULTIPLY" } }, { "bl_idname": "FunctionNodeCompare", - "id": "n4", + "id": "n3", "properties": { "data_type": "FLOAT", "mode": "ELEMENT", "operation": "LESS_THAN" } }, - { - "bl_idname": "FunctionNodeInputInt", - "id": "n5", - "payload": { - "value": 2 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n6", + "id": "n4", "properties": { "operation": "MULTIPLY" } }, { "bl_idname": "FunctionNodeCompare", - "id": "n7", + "id": "n5", "properties": { "data_type": "FLOAT", "mode": "ELEMENT", @@ -198,7 +162,7 @@ }, { "bl_idname": "FunctionNodeBooleanMath", - "id": "n8", + "id": "n6", "properties": { "operation": "AND" } diff --git a/tests/blender/expression_characterization/cases/expected/for_unpack_append_compat.json b/tests/blender/expression_characterization/cases/expected/for_unpack_append_compat.json index cac74ec..7d14be6 100644 --- a/tests/blender/expression_characterization/cases/expected/for_unpack_append_compat.json +++ b/tests/blender/expression_characterization/cases/expected/for_unpack_append_compat.json @@ -13,26 +13,6 @@ "n2", "Value" ], - "to": [ - "n4", - "Value" - ] - }, - { - "from": [ - "n3", - "Value" - ], - "to": [ - "n4", - "Value_001" - ] - }, - { - "from": [ - "n4", - "Value" - ], "to": [ "n1", "Socket_0" @@ -50,25 +30,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, - { - "bl_idname": "ShaderNodeValue", - "id": "n3", - "payload": { - "value": 2.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n4", + "id": "n2", "properties": { "operation": "ADD" } diff --git a/tests/blender/expression_characterization/cases/expected/for_unpack_geometry_builder_compat.json b/tests/blender/expression_characterization/cases/expected/for_unpack_geometry_builder_compat.json index 7e0e6d9..69e2e84 100644 --- a/tests/blender/expression_characterization/cases/expected/for_unpack_geometry_builder_compat.json +++ b/tests/blender/expression_characterization/cases/expected/for_unpack_geometry_builder_compat.json @@ -11,52 +11,12 @@ { "from": [ "n2", - "Value" - ], - "to": [ - "n5", - "X" - ] - }, - { - "from": [ - "n2", - "Value" - ], - "to": [ - "n5", - "Y" - ] - }, - { - "from": [ - "n2", - "Value" - ], - "to": [ - "n5", - "Z" - ] - }, - { - "from": [ - "n4", "Mesh" ], "to": [ "n1", "Socket_0" ] - }, - { - "from": [ - "n5", - "Vector" - ], - "to": [ - "n4", - "Size" - ] } ], "nodes": [ @@ -70,30 +30,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, - { - "bl_idname": "ShaderNodeValue", - "id": "n3", - "payload": { - "value": 2.0 - }, - "properties": {} - }, { "bl_idname": "GeometryNodeMeshCube", - "id": "n4", - "properties": {} - }, - { - "bl_idname": "ShaderNodeCombineXYZ", - "id": "n5", + "id": "n2", "properties": {} } ] diff --git a/tests/blender/expression_characterization/cases/expected/literal_bool.json b/tests/blender/expression_characterization/cases/expected/literal_bool.json index 679b519..77eb682 100644 --- a/tests/blender/expression_characterization/cases/expected/literal_bool.json +++ b/tests/blender/expression_characterization/cases/expected/literal_bool.json @@ -11,27 +11,7 @@ { "from": [ "n2", - "Value" - ], - "to": [ - "n4", - "A" - ] - }, - { - "from": [ - "n3", - "Value" - ], - "to": [ - "n4", - "B" - ] - }, - { - "from": [ - "n4", - "Result" + "Boolean" ], "to": [ "n1", @@ -51,29 +31,9 @@ "properties": {} }, { - "bl_idname": "ShaderNodeValue", + "bl_idname": "FunctionNodeInputBool", "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, - { - "bl_idname": "ShaderNodeValue", - "id": "n3", - "payload": { - "value": 0.0 - }, "properties": {} - }, - { - "bl_idname": "FunctionNodeCompare", - "id": "n4", - "properties": { - "data_type": "FLOAT", - "mode": "ELEMENT", - "operation": "NOT_EQUAL" - } } ] }, diff --git a/tests/blender/expression_characterization/cases/expected/top_level_definition_chain.json b/tests/blender/expression_characterization/cases/expected/top_level_definition_chain.json index 2b96803..01e72f0 100644 --- a/tests/blender/expression_characterization/cases/expected/top_level_definition_chain.json +++ b/tests/blender/expression_characterization/cases/expected/top_level_definition_chain.json @@ -82,23 +82,13 @@ "Socket_1" ], "to": [ - "n4", - "Value" - ] - }, - { - "from": [ "n3", "Value" - ], - "to": [ - "n4", - "Value_001" ] }, { "from": [ - "n4", + "n3", "Value" ], "to": [ @@ -142,23 +132,13 @@ "Socket_0" ], "to": [ - "n3", - "Value" - ] - }, - { - "from": [ "n2", "Value" - ], - "to": [ - "n3", - "Value_001" ] }, { "from": [ - "n3", + "n2", "Value" ], "to": [ @@ -178,17 +158,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "ADD" } @@ -201,17 +173,9 @@ "id": "n2", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n3", - "payload": { - "value": 2.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n4", + "id": "n3", "properties": { "operation": "MULTIPLY" } @@ -250,23 +214,13 @@ "Socket_0" ], "to": [ - "n3", - "Value" - ] - }, - { - "from": [ "n2", "Value" - ], - "to": [ - "n3", - "Value_001" ] }, { "from": [ - "n3", + "n2", "Value" ], "to": [ @@ -286,17 +240,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "SUBTRACT" } @@ -327,23 +273,13 @@ "Socket_0" ], "to": [ - "n3", - "Value" - ] - }, - { - "from": [ "n2", "Value" - ], - "to": [ - "n3", - "Value_001" ] }, { "from": [ - "n3", + "n2", "Value" ], "to": [ @@ -363,17 +299,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "ADD" } @@ -414,23 +342,13 @@ "Socket_1" ], "to": [ - "n4", - "Value" - ] - }, - { - "from": [ "n3", "Value" - ], - "to": [ - "n4", - "Value_001" ] }, { "from": [ - "n4", + "n3", "Value" ], "to": [ @@ -474,23 +392,13 @@ "Socket_0" ], "to": [ - "n3", - "Value" - ] - }, - { - "from": [ "n2", "Value" - ], - "to": [ - "n3", - "Value_001" ] }, { "from": [ - "n3", + "n2", "Value" ], "to": [ @@ -510,17 +418,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "ADD" } @@ -533,17 +433,9 @@ "id": "n2", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n3", - "payload": { - "value": 2.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n4", + "id": "n3", "properties": { "operation": "MULTIPLY" } diff --git a/tests/blender/expression_characterization/cases/expected/top_level_forward_mixed.json b/tests/blender/expression_characterization/cases/expected/top_level_forward_mixed.json index 34ce9ae..e63debe 100644 --- a/tests/blender/expression_characterization/cases/expected/top_level_forward_mixed.json +++ b/tests/blender/expression_characterization/cases/expected/top_level_forward_mixed.json @@ -8,18 +8,8 @@ "Mesh" ], "to": [ - "n2", - "Socket_0" - ] - }, - { - "from": [ "n1", - "Vector" - ], - "to": [ - "n2", - "Socket_1" + "Socket_0" ] } ], @@ -29,16 +19,6 @@ "id": "n0", "properties": {} }, - { - "bl_idname": "ShaderNodeCombineXYZ", - "defaults": { - "X": 0.0, - "Y": 0.0, - "Z": 2.0 - }, - "id": "n1", - "properties": {} - }, { "bl_idname": "GeometryNodeGroup", "group": { @@ -118,12 +98,12 @@ "id": "g1", "unique": false }, - "id": "n2", + "id": "n1", "properties": {} }, { "bl_idname": "GeometryNodeMeshCube", - "id": "n3", + "id": "n2", "properties": {} } ] diff --git a/tests/blender/expression_characterization/cases/expected/top_level_import_alias_identity.json b/tests/blender/expression_characterization/cases/expected/top_level_import_alias_identity.json index 3aa8550..8bbbddf 100644 --- a/tests/blender/expression_characterization/cases/expected/top_level_import_alias_identity.json +++ b/tests/blender/expression_characterization/cases/expected/top_level_import_alias_identity.json @@ -27,23 +27,13 @@ "Socket_0" ], "to": [ - "n3", - "Value" - ] - }, - { - "from": [ "n2", "Value" - ], - "to": [ - "n3", - "Value_001" ] }, { "from": [ - "n3", + "n2", "Value" ], "to": [ @@ -63,17 +53,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 5.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "ADD" } diff --git a/tests/blender/expression_characterization/cases/expected/top_level_import_multi.json b/tests/blender/expression_characterization/cases/expected/top_level_import_multi.json index 2827536..b235399 100644 --- a/tests/blender/expression_characterization/cases/expected/top_level_import_multi.json +++ b/tests/blender/expression_characterization/cases/expected/top_level_import_multi.json @@ -27,23 +27,13 @@ "Socket_0" ], "to": [ - "n3", - "Value" - ] - }, - { - "from": [ "n2", "Value" - ], - "to": [ - "n3", - "Value_001" ] }, { "from": [ - "n3", + "n2", "Value" ], "to": [ @@ -63,17 +53,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "ADD" } @@ -120,23 +102,13 @@ "Socket_1" ], "to": [ - "n4", - "Value" - ] - }, - { - "from": [ "n3", "Value" - ], - "to": [ - "n4", - "Value_001" ] }, { "from": [ - "n4", + "n3", "Value" ], "to": [ @@ -165,17 +137,9 @@ "id": "n2", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n3", - "payload": { - "value": 2.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n4", + "id": "n3", "properties": { "operation": "MULTIPLY" } diff --git a/tests/blender/expression_characterization/cases/expected/top_level_import_shared_unique.json b/tests/blender/expression_characterization/cases/expected/top_level_import_shared_unique.json index 5482eda..1a5504e 100644 --- a/tests/blender/expression_characterization/cases/expected/top_level_import_shared_unique.json +++ b/tests/blender/expression_characterization/cases/expected/top_level_import_shared_unique.json @@ -27,23 +27,13 @@ "Socket_0" ], "to": [ - "n3", - "Value" - ] - }, - { - "from": [ "n2", "Value" - ], - "to": [ - "n3", - "Value_001" ] }, { "from": [ - "n3", + "n2", "Value" ], "to": [ @@ -63,17 +53,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "ADD" } @@ -119,23 +101,13 @@ "Socket_0" ], "to": [ - "n3", - "Value" - ] - }, - { - "from": [ "n2", "Value" - ], - "to": [ - "n3", - "Value_001" ] }, { "from": [ - "n3", + "n2", "Value" ], "to": [ @@ -155,17 +127,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "ADD" } diff --git a/tests/blender/expression_characterization/cases/expected/top_level_lexical_shadowing.json b/tests/blender/expression_characterization/cases/expected/top_level_lexical_shadowing.json index b1ee6ba..e042090 100644 --- a/tests/blender/expression_characterization/cases/expected/top_level_lexical_shadowing.json +++ b/tests/blender/expression_characterization/cases/expected/top_level_lexical_shadowing.json @@ -27,23 +27,13 @@ "Socket_0" ], "to": [ - "n3", - "Value" - ] - }, - { - "from": [ "n2", "Value" - ], - "to": [ - "n3", - "Value_001" ] }, { "from": [ - "n3", + "n2", "Value" ], "to": [ @@ -63,17 +53,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "ADD" } diff --git a/tests/blender/expression_characterization/cases/expected/top_level_panel_defaults.json b/tests/blender/expression_characterization/cases/expected/top_level_panel_defaults.json index 0640ff9..73daa60 100644 --- a/tests/blender/expression_characterization/cases/expected/top_level_panel_defaults.json +++ b/tests/blender/expression_characterization/cases/expected/top_level_panel_defaults.json @@ -28,7 +28,7 @@ "Socket_0" ], "to": [ - "n3", + "n2", "Value" ] }, @@ -38,7 +38,7 @@ "Socket_1" ], "to": [ - "n4", + "n3", "Value_001" ] }, @@ -49,22 +49,12 @@ ], "to": [ "n3", - "Value_001" - ] - }, - { - "from": [ - "n3", - "Value" - ], - "to": [ - "n4", "Value" ] }, { "from": [ - "n4", + "n3", "Value" ], "to": [ @@ -84,24 +74,16 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 2.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "MULTIPLY" } }, { "bl_idname": "ShaderNodeMath", - "id": "n4", + "id": "n3", "properties": { "operation": "ADD" } diff --git a/tests/blender/expression_characterization/cases/expected/top_level_shared_entries.json b/tests/blender/expression_characterization/cases/expected/top_level_shared_entries.json index 916c613..bd81d58 100644 --- a/tests/blender/expression_characterization/cases/expected/top_level_shared_entries.json +++ b/tests/blender/expression_characterization/cases/expected/top_level_shared_entries.json @@ -22,23 +22,13 @@ "Socket_0" ], "to": [ - "n3", - "Value" - ] - }, - { - "from": [ "n2", "Value" - ], - "to": [ - "n3", - "Value_001" ] }, { "from": [ - "n3", + "n2", "Value" ], "to": [ @@ -58,17 +48,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "ADD" } @@ -149,23 +131,13 @@ "Socket_0" ], "to": [ - "n3", - "Value" - ] - }, - { - "from": [ "n2", "Value" - ], - "to": [ - "n3", - "Value_001" ] }, { "from": [ - "n3", + "n2", "Value" ], "to": [ @@ -185,17 +157,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "ADD" } @@ -244,23 +208,13 @@ "Socket_1" ], "to": [ - "n4", - "Value" - ] - }, - { - "from": [ "n3", "Value" - ], - "to": [ - "n4", - "Value_001" ] }, { "from": [ - "n4", + "n3", "Value" ], "to": [ @@ -304,23 +258,13 @@ "Socket_0" ], "to": [ - "n3", - "Value" - ] - }, - { - "from": [ "n2", "Value" - ], - "to": [ - "n3", - "Value_001" ] }, { "from": [ - "n3", + "n2", "Value" ], "to": [ @@ -340,17 +284,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "ADD" } @@ -363,17 +299,9 @@ "id": "n2", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n3", - "payload": { - "value": 2.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n4", + "id": "n3", "properties": { "operation": "MULTIPLY" } diff --git a/tests/blender/expression_characterization/cases/expected/top_level_tuple_outputs.json b/tests/blender/expression_characterization/cases/expected/top_level_tuple_outputs.json index 4e84a1b..b9adf56 100644 --- a/tests/blender/expression_characterization/cases/expected/top_level_tuple_outputs.json +++ b/tests/blender/expression_characterization/cases/expected/top_level_tuple_outputs.json @@ -53,7 +53,7 @@ "Socket_0" ], "to": [ - "n3", + "n2", "Value" ] }, @@ -63,7 +63,7 @@ "Socket_0" ], "to": [ - "n5", + "n3", "Value" ] }, @@ -72,16 +72,6 @@ "n2", "Value" ], - "to": [ - "n3", - "Value_001" - ] - }, - { - "from": [ - "n3", - "Value" - ], "to": [ "n1", "Socket_1" @@ -89,17 +79,7 @@ }, { "from": [ - "n4", - "Value" - ], - "to": [ - "n5", - "Value_001" - ] - }, - { - "from": [ - "n5", + "n3", "Value" ], "to": [ @@ -119,32 +99,16 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 2.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "MULTIPLY" } }, - { - "bl_idname": "ShaderNodeValue", - "id": "n4", - "payload": { - "value": 1.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n5", + "id": "n3", "properties": { "operation": "ADD" } diff --git a/tests/blender/expression_characterization/cases/expected/unary_minus_float.json b/tests/blender/expression_characterization/cases/expected/unary_minus_float.json index 288df79..0e92363 100644 --- a/tests/blender/expression_characterization/cases/expected/unary_minus_float.json +++ b/tests/blender/expression_characterization/cases/expected/unary_minus_float.json @@ -20,7 +20,7 @@ "Socket_0" ], "to": [ - "n3", + "n2", "Value_001" ] }, @@ -29,16 +29,6 @@ "n2", "Value" ], - "to": [ - "n3", - "Value" - ] - }, - { - "from": [ - "n3", - "Value" - ], "to": [ "n1", "Socket_1" @@ -56,17 +46,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 0.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "SUBTRACT" } diff --git a/tests/blender/expression_characterization/cases/expected/unary_minus_vector.json b/tests/blender/expression_characterization/cases/expected/unary_minus_vector.json index e04df8a..b52de5b 100644 --- a/tests/blender/expression_characterization/cases/expected/unary_minus_vector.json +++ b/tests/blender/expression_characterization/cases/expected/unary_minus_vector.json @@ -24,23 +24,13 @@ "Socket_0" ], "to": [ - "n3", + "n2", "Vector" ] }, { "from": [ "n2", - "Value" - ], - "to": [ - "n3", - "Scale" - ] - }, - { - "from": [ - "n3", "Vector" ], "to": [ @@ -60,17 +50,9 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": -1.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeVectorMath", - "id": "n3", + "id": "n2", "properties": { "operation": "SCALE" } diff --git a/tests/blender/expression_characterization/cases/expected/unary_plus_const_array.json b/tests/blender/expression_characterization/cases/expected/unary_plus_const_array.json index b6fa78a..c6c91f7 100644 --- a/tests/blender/expression_characterization/cases/expected/unary_plus_const_array.json +++ b/tests/blender/expression_characterization/cases/expected/unary_plus_const_array.json @@ -37,14 +37,6 @@ "value": 1.0 }, "properties": {} - }, - { - "bl_idname": "ShaderNodeValue", - "id": "n3", - "payload": { - "value": 2.0 - }, - "properties": {} } ] }, diff --git a/tests/blender/expression_characterization/cases/expected/vector_divide_scalar.json b/tests/blender/expression_characterization/cases/expected/vector_divide_scalar.json index e743cb0..e5e5211 100644 --- a/tests/blender/expression_characterization/cases/expected/vector_divide_scalar.json +++ b/tests/blender/expression_characterization/cases/expected/vector_divide_scalar.json @@ -30,7 +30,7 @@ "Socket_0" ], "to": [ - "n4", + "n3", "Vector" ] }, @@ -40,7 +40,7 @@ "Socket_1" ], "to": [ - "n3", + "n2", "Value_001" ] }, @@ -51,22 +51,12 @@ ], "to": [ "n3", - "Value" - ] - }, - { - "from": [ - "n3", - "Value" - ], - "to": [ - "n4", "Scale" ] }, { "from": [ - "n4", + "n3", "Vector" ], "to": [ @@ -86,24 +76,16 @@ "id": "n1", "properties": {} }, - { - "bl_idname": "ShaderNodeValue", - "id": "n2", - "payload": { - "value": 1.0 - }, - "properties": {} - }, { "bl_idname": "ShaderNodeMath", - "id": "n3", + "id": "n2", "properties": { "operation": "DIVIDE" } }, { "bl_idname": "ShaderNodeVectorMath", - "id": "n4", + "id": "n3", "properties": { "operation": "SCALE" } diff --git a/tests/blender/test_inline_source_calls.py b/tests/blender/test_inline_source_calls.py index 400d26f..a0d3aee 100644 --- a/tests/blender/test_inline_source_calls.py +++ b/tests/blender/test_inline_source_calls.py @@ -83,13 +83,12 @@ def test_inline_rotation_default_links_native_rotation_socket(): ''', 'NFTest_Inline_Rotation_Default') constants = _nodes(tree, 'FunctionNodeInputRotation') transforms = _nodes(tree, 'GeometryNodeTransform') - assert len(constants) == len(transforms) == 1 + assert len(constants) == 0 and len(transforms) == 1 assert not _nodes(tree, 'GeometryNodeGroup') - assert constants[0].outputs['Rotation'].bl_idname == 'NodeSocketRotation' - assert tuple(constants[0].rotation_euler) == tuple( + assert not transforms[0].inputs['Rotation'].is_linked + assert tuple(transforms[0].inputs['Rotation'].default_value) == tuple( normalize_float_constant(v) for v in (0.0, 0.0, 1.5707963) ) - assert transforms[0].inputs['Rotation'].links[0].from_socket == constants[0].outputs['Rotation'] assert all(link.is_valid for link in tree.links) @@ -603,8 +602,10 @@ def test_inline_rotation_package_function_uses_caller_tree(tmp_path): tree = _compose('''from packages import rotationpkg result = rotationpkg.spatial.rotate.apply(cube(1.0)) ''', 'NFTest_Inline_Rotation_Package') - assert len(_nodes(tree, 'FunctionNodeInputRotation')) == 1 - assert len(_nodes(tree, 'GeometryNodeTransform')) == 1 + assert not _nodes(tree, 'FunctionNodeInputRotation') + transform, = _nodes(tree, 'GeometryNodeTransform') + assert not transform.inputs['Rotation'].is_linked + assert tuple(transform.inputs['Rotation'].default_value) == pytest.approx((0.1, -0.2, 7.0), abs=1e-6) assert not _nodes(tree, 'GeometryNodeGroup') assert all(link.is_valid for link in tree.links) finally: @@ -614,7 +615,7 @@ def test_inline_rotation_package_function_uses_caller_tree(tmp_path): def test_grouped_parent_reload_updates_inline_rotation_and_rolls_back(monkeypatch): """Reload tracks inline Rotation defaults and retains the published group on failure.""" from NodeForge.compiler_identities import parse_module_definition_function_id - from NodeForge.blender import ir_lowering + from NodeForge.blender import nodes as blender_nodes source = '''def inner(rotation: Rotation = (0, 0, 0.25), __inline__=True) -> Rotation: return rotation @@ -643,14 +644,14 @@ def outer(geometry: Geometry) -> Geometry: assert updated.rotation_euler.z == pytest.approx(0.75) before_nodes = {node.as_pointer() for node in parent.nodes} before_groups = {group.as_pointer() for group in bpy.data.node_groups} - original = ir_lowering._rotation_value + original = blender_nodes._rotation_value def fail_after_native_rotation(*args, **kwargs): """Simulate failure after creating the staged Rotation node.""" original(*args, **kwargs) raise RuntimeError('injected inline Rotation failure') - monkeypatch.setattr(ir_lowering, '_rotation_value', fail_after_native_rotation) + monkeypatch.setattr(blender_nodes, '_rotation_value', fail_after_native_rotation) with pytest.raises(RuntimeError, match='injected inline Rotation failure'): compiler.update_library_catalog_group( parent, source=source.replace('0.25', '1.25'), module_context=origin, diff --git a/tests/blender/test_sample_index.py b/tests/blender/test_sample_index.py index 8c1ecbd..4e16731 100644 --- a/tests/blender/test_sample_index.py +++ b/tests/blender/test_sample_index.py @@ -2,7 +2,7 @@ from __future__ import annotations -from helpers import _owned_generated_id_keys, check, compile_group, expect_compile_error +from helpers import bpy, compile_root, _owned_generated_id_keys, check, compile_group, expect_compile_error def _sample_nodes(group): @@ -123,3 +123,33 @@ def nf_fixture(): "NFTest_sample_index_rejected_type_no_resources", ) check(_owned_generated_id_keys() == before, "failed Sample Index compile published generated resources") + + +def test_sample_index_inline_default_index_uses_direct_default_and_rejects_wrong_type(): + """Deferred inline Int reaches Index without accidental int(DeferredConstant).""" + group = bpy.data.node_groups.new("NFTest_sample_index_inline_default_index", "GeometryNodeTree") + compile_root( + '''def sampled(geometry: Geometry, value: Float, at: Int = 3, __inline__=True) -> Float: + return sample_index(geometry, value, at) + +geo = grid(3, 3) +result = sampled(geo, position().x) +''', group, + ) + sample, = _sample_nodes(group) + assert not sample.inputs["Index"].is_linked + assert sample.inputs["Index"].default_value == 3 + assert not any(node.bl_idname == "FunctionNodeInputInt" for node in group.nodes) + + bad_group = bpy.data.node_groups.new("NFTest_sample_index_inline_bad_index", "GeometryNodeTree") + with __import__("pytest").raises(Exception): + compile_root( + '''def sampled(geometry: Geometry, value: Float, at: Bool = True, __inline__=True) -> Float: + return sample_index(geometry, value, at) + +def nf_fixture(): + geo = grid(3, 3) + value = sampled(geo, position().x) + return (value,) +''', bad_group, + ) diff --git a/tests/blender/test_semantic_ir_compile.py b/tests/blender/test_semantic_ir_compile.py index 6419a9b..12846fc 100644 --- a/tests/blender/test_semantic_ir_compile.py +++ b/tests/blender/test_semantic_ir_compile.py @@ -46,7 +46,11 @@ def _linked_numeric_inputs(group, node): values = [] for socket in node.inputs[:2]: link = next((item for item in group.links if item.to_node == node and item.to_socket == socket), None) - check(link is not None, f"Math input {socket.name!r} is unexpectedly unlinked") + if link is None: + # The same source-order value can now reside directly in the Math + # input default, without a redundant producer. + values.append(float(socket.default_value)) + continue source = link.from_node if source.bl_idname == "FunctionNodeInputInt": values.append(float(source.integer)) @@ -305,8 +309,12 @@ def nf_fixture(a: Float['A'] = 2.0, v: Vector['V'] = (1, 2, 3), flag: Bool['Flag helper_values = _nodes(group, "ShaderNodeValue") zero_helpers = [node for node in helper_values if abs(float(node.outputs[0].default_value) - 0.0) < 1e-8] minus_one_helpers = [node for node in helper_values if abs(float(node.outputs[0].default_value) + 1.0) < 1e-8] - check(len(zero_helpers) == 1, f"expected one 0.0 unary helper, got {len(zero_helpers)}") - check(len(minus_one_helpers) == 1, f"expected one -1.0 unary helper, got {len(minus_one_helpers)}") + check(not zero_helpers, f"unary minus created unnecessary zero helpers: {zero_helpers}") + check(not minus_one_helpers, f"unary minus created unnecessary minus-one helpers: {minus_one_helpers}") + check(subtract[0].inputs[0].default_value == 0.0 and not subtract[0].inputs[0].is_linked, + "unary scalar zero must use the Math input default") + check(scale[0].inputs[3].default_value == -1.0 and not scale[0].inputs[3].is_linked, + "unary Vector scale -1 must use the Vector Math input default") @@ -538,7 +546,11 @@ def _lower_contract_program_on_real_blender(program, bindings, name): for binding_name, typ in bindings.items() }) context = BlenderIRLoweringContext(group, runtime_bindings) + from NodeForge.blender.values import DeferredConstant + from NodeForge.blender.input_delivery import require_output result = lower_ir_program(context, program) + if isinstance(result, DeferredConstant): + result = require_output(group, result, context="standalone expression result") return group, result @@ -632,13 +644,8 @@ def _check_literal_realization(group, operation, result_link): check(node.string == operation.value, "String literal value changed at the Blender boundary") return if operation.result.typ == TYPE_BOOL: - check(node.bl_idname == "FunctionNodeCompare", "Bool literal did not realize through Compare") - check(node.operation == "NOT_EQUAL", "Bool literal Compare operation changed") - check(node.data_type == "FLOAT", "Bool literal Compare data_type changed") - inputs = [_link_to_socket(group, node.inputs[index]) for index in (0, 1)] - values = [float(link.from_socket.default_value) for link in inputs] - expected = [1.0 if operation.value else 0.0, 0.0] - check(values == expected, f"Bool literal helper values changed: {values!r} != {expected!r}") + check(node.bl_idname == "FunctionNodeInputBool", "Physical Bool output must use native Bool producer") + check(bool(node.boolean) is bool(operation.value), "Bool literal changed at physical output boundary") return raise AssertionError(f"unexpected literal type {operation.result.typ}") @@ -663,18 +670,16 @@ def _check_unary_realization(group, operation, result_link, binding_names): if operation.operand.typ == TYPE_FLOAT: check(node.bl_idname == "ShaderNodeMath", "Float unary - did not realize as Math") check(node.operation == "SUBTRACT", "Float unary - operation enum changed") - zero_link = _link_to_socket(group, node.inputs[0]) - check(zero_link.from_node.bl_idname == "ShaderNodeValue", "Float unary - lost its zero helper") - check(abs(float(zero_link.from_socket.default_value)) < 1e-8, "Float unary - zero helper changed") + check(not node.inputs[0].is_linked and abs(float(node.inputs[0].default_value)) < 1e-8, + "Float unary - zero was not written as Math input default") _check_operand_source(group, node.inputs[1], operation.operand, binding_names) return check(operation.operand.typ == TYPE_VECTOR, "unexpected analyzer-accepted unary - type") check(node.bl_idname == "ShaderNodeVectorMath", "Vector unary - did not realize as Vector Math") check(node.operation == "SCALE", "Vector unary - operation enum changed") _check_operand_source(group, node.inputs[0], operation.operand, binding_names) - scale_link = _link_to_socket(group, node.inputs[3]) - check(scale_link.from_node.bl_idname == "ShaderNodeValue", "Vector unary - lost its scale helper") - check(abs(float(scale_link.from_socket.default_value) + 1.0) < 1e-8, "Vector unary - scale helper changed") + check(not node.inputs[3].is_linked and abs(float(node.inputs[3].default_value) + 1.0) < 1e-8, + "Vector unary - scale must use Vector Math input default") def _check_binary_realization(group, operation, result_link, binding_names): @@ -739,9 +744,9 @@ def _check_binary_realization(group, operation, result_link, binding_names): reciprocal = reciprocal_link.from_node check(reciprocal.bl_idname == "ShaderNodeMath", "Vector / scalar reciprocal did not use Math") check(reciprocal.operation == "DIVIDE", "Vector / scalar reciprocal operation changed") - one_link = _link_to_socket(group, reciprocal.inputs[0]) - check(one_link.from_node.bl_idname == "ShaderNodeValue", "Vector / scalar reciprocal lost its 1.0 helper") - check(abs(float(one_link.from_socket.default_value) - 1.0) < 1e-8, "Vector / scalar reciprocal helper changed") + check(not reciprocal.inputs[0].is_linked, "Vector / scalar reciprocal has redundant 1.0 producer") + check(abs(float(reciprocal.inputs[0].default_value) - 1.0) < 1e-8, + "Vector / scalar reciprocal default changed") _check_operand_source(group, reciprocal.inputs[1], operation.right, binding_names) diff --git a/tests/unit/test_inline_lowering.py b/tests/unit/test_inline_lowering.py index 5bb6fa9..b2a0371 100644 --- a/tests/unit/test_inline_lowering.py +++ b/tests/unit/test_inline_lowering.py @@ -7,7 +7,7 @@ import pytest from NodeForge.blender import ir_lowering as backend -from NodeForge.blender.values import Value +from NodeForge.blender.values import Value, DeferredConstant from NodeForge.errors import CompileError from NodeForge.semantic.ir import IRInputDeclaration from NodeForge.nf_types import NFType @@ -18,6 +18,32 @@ class StubSocket: """Stand in for a typed Blender output socket during detached lowering tests.""" +@pytest.fixture(autouse=True) +def _host_only_physical_output_stub(monkeypatch): + """Real Blender validates RNA owners; unit-only bare groups use producer stubs.""" + original = backend.require_output + + def require(group, operand, *, context="constant", allow_native_conversion=False): + if type(group) is object: + if isinstance(operand, Value): + return operand + if isinstance(operand, DeferredConstant): + emit = { + NFType.FLOAT: backend._value, + NFType.INT: backend._int_value, + NFType.BOOL: backend._bool_value, + NFType.STRING: backend._string_value, + NFType.VECTOR: backend._vector_value, + NFType.COLOR: backend._color_value, + NFType.ROTATION: backend._rotation_value, + }[operand.typ] + return emit(group, operand.value) + return original(group, operand, context=context, + allow_native_conversion=allow_native_conversion) + + monkeypatch.setattr(backend, 'require_output', require) + + def _emit_stub_value(calls, name, typ): """Return one materialization stub and record the expected native operation.""" def emit(group, *args, **kwargs): @@ -40,6 +66,25 @@ def _lower_inline(source, monkeypatch, runtime_values=()): monkeypatch.setattr(backend, '_color_value', _emit_stub_value(calls, 'Color', NFType.COLOR)) monkeypatch.setattr(backend, '_rotation_value', _emit_stub_value(calls, 'Rotation', NFType.ROTATION)) monkeypatch.setattr(backend, '_math', _emit_stub_value(calls, 'Math', NFType.FLOAT)) + from NodeForge.blender.values import DeferredConstant + + def fake_required_output(group, operand, *, context="constant", allow_native_conversion=False): + """Host-only stubs have no Blender RNA; use their typed fake producers.""" + if isinstance(operand, Value): + return operand + assert isinstance(operand, DeferredConstant) + producer = { + NFType.FLOAT: backend._value, + NFType.INT: backend._int_value, + NFType.BOOL: backend._bool_value, + NFType.STRING: backend._string_value, + NFType.VECTOR: backend._vector_value, + NFType.COLOR: backend._color_value, + NFType.ROTATION: backend._rotation_value, + }[operand.typ] + return producer(group, operand.value) + + monkeypatch.setattr(backend, 'require_output', fake_required_output) context = backend.BlenderIRLoweringContext( group=object(), runtime_bindings={}, source_callable_session=session, function_materializer=object(), function_materialization_context=object(), @@ -55,8 +100,7 @@ def test_bound_inline_uses_no_group_and_realizes_defaults(monkeypatch): x = calc(2.0) ''', monkeypatch) assert len(result) == 1 and result[0].typ is NFType.FLOAT - assert [name for name, _ in calls] == ['Float', 'Float', 'Math'] - assert [args[0] for name, args in calls if name == 'Float'] == [2.0, 4.0] + assert [name for name, _ in calls] == ['Math'] # both literal operands use Math socket defaults def test_bound_inline_preserves_panel_reordered_input_identity(monkeypatch): @@ -68,7 +112,7 @@ def test_bound_inline_preserves_panel_reordered_input_identity(monkeypatch): ''', monkeypatch) assert [arg.parameter_index for arg in operation.static_arguments] == [2, 0] assert result[0].typ is NFType.FLOAT - assert [args[0] for name, args in calls if name == 'Float'] == [2.0, 3.0, 1.0] + assert not [name for name, args in calls if name == 'Float'] # unused c and direct a/b create no Value producers def test_bound_inline_constant_adapters_cover_scalar_vector_and_rgba(monkeypatch): @@ -101,9 +145,8 @@ def test_inline_rotation_default_materializes_once(monkeypatch): assert result[0].typ is NFType.ROTATION assert [name for name, _ in calls] == ['Rotation'] - angles, x, y = calls[0][1] + (angles,) = calls[0][1] assert angles == tuple(normalize_float_constant(v) for v in (0.1, -0.2, 7.0)) - assert isinstance(x, int) and isinstance(y, int) def test_inline_rotation_static_materializer_uses_same_canonical_contract(monkeypatch): @@ -126,7 +169,7 @@ def test_bound_inline_coerces_runtime_int_to_float(monkeypatch): input_value = index() x = calc(input_value) ''', monkeypatch, (Value(StubSocket(), NFType.INT),)) - assert [name for name, _ in calls] == ['Float', 'Math'] + assert [name for name, _ in calls] == ['Math'] assert result[0].typ is NFType.FLOAT @@ -157,7 +200,7 @@ def test_lower_body_requires_prebound_typed_runtime_input(): }) result = backend.lower_body(context, prepared.group.body, { declaration.target_binding_id: Value(StubSocket(), NFType.FLOAT), - }) + }, physical_outputs=False) assert result.explicit_outputs[0][1].typ is NFType.FLOAT diff --git a/tests/unit/test_semantic_backend_contract.py b/tests/unit/test_semantic_backend_contract.py index 019a5cb..f0fcaf8 100644 --- a/tests/unit/test_semantic_backend_contract.py +++ b/tests/unit/test_semantic_backend_contract.py @@ -53,6 +53,17 @@ def fake_delivery(group, socket, operand, *, context="node input"): monkeypatch.setattr(backend_nodes, "deliver_input", fake_delivery) monkeypatch.setattr(backend_geometry, "deliver_input", fake_delivery) + def fake_required(group, operand, *, context="constant", allow_native_conversion=False): + if isinstance(group, _FakeGroup): + if isinstance(operand, Value): + return operand + if isinstance(operand, DeferredConstant): + return Value(_FakeSocket(), operand.typ) + return require_original(group, operand, context=context, + allow_native_conversion=allow_native_conversion) + + require_original = blender_ir_lowering.require_output + monkeypatch.setattr(blender_ir_lowering, "require_output", fake_required) def _empty_callable_environment(): """Return an empty immutable callable namespace for non-call semantic tests.""" @@ -320,8 +331,10 @@ def test_vector_literal_uses_real_combine_xyz_helper_contract(): blender_ir_lowering.BlenderIRLoweringContext(group, MappingProxyType({})), program ) assert result.typ == TYPE_VECTOR - combine = next(node for node in group.nodes if node.bl_idname == "ShaderNodeCombineXYZ") - assert [socket.default_value for socket in combine.inputs[:3]] == [1.0, 2.0, 3.0] + from NodeForge.blender.values import DeferredConstant + assert isinstance(result, DeferredConstant) + assert result.value == (1.0, 2.0, 3.0) + assert not group.nodes # no producer until an output socket actually needs one def test_object_property_uses_exact_object_value_and_reuses_object_info_node(): diff --git a/tests/unit/test_semantic_ir.py b/tests/unit/test_semantic_ir.py index 500c656..2aaa116 100644 --- a/tests/unit/test_semantic_ir.py +++ b/tests/unit/test_semantic_ir.py @@ -749,7 +749,7 @@ def test_backend_binding_bridge_and_invariant_drift(): with pytest.raises(CompileError, match="changed type"): lower_expression(drifted, program) missing = _backend_context(backend, {}, group=None) - with pytest.raises(CompileError, match="no longer a runtime Value"): + with pytest.raises(CompileError, match="no backend operand"): lower_expression(missing, program) @@ -778,7 +778,7 @@ def fake_math(group, operation, args, x=0, y=0): result = backend.lower_expression(context, _lower("a * 2", bindings={"a": TYPE_FLOAT}), base_depth=3) assert result.typ == TYPE_FLOAT - assert calls == [("int_value", 2, 960, -360), ("math", "MULTIPLY", 720, -270)] + assert calls == [("math", "MULTIPLY", 720, -270)] def test_backend_missing_operand_is_controlled_internal_error(): @@ -832,9 +832,9 @@ def fake_boolean_math(group, operation, args, x=0, y=0): backend.lower_expression(context, _lower("-a", bindings={"a": TYPE_FLOAT}), base_depth=1) backend.lower_expression(context, _lower("-v", bindings={"v": TYPE_VECTOR}), base_depth=1) backend.lower_expression(context, _lower("not flag", bindings={"flag": TYPE_BOOL}), base_depth=1) - assert ("value", 0.0, 240, -130) in calls + assert not [row for row in calls if row[0] == "value"] # constants use native operation input defaults assert ("math", "SUBTRACT", 240, -90) in calls - assert ("value", -1.0, 240, -130) in calls + assert not [row for row in calls if row[0] == "value"] assert ("vector_math", "SCALE", 240, -90) in calls assert ("boolean_math", "NOT", 240, -90) in calls @@ -1422,6 +1422,19 @@ def _sample_index_untyped_socket_compatibility(monkeypatch): The dedicated Blender tests exercise strict deliver_input validation. """ original = geometry_backend.deliver_input + require_original = blender_ir_lowering.require_output + + def mock_require_output(group, operand, *, context="constant", allow_native_conversion=False): + from NodeForge.blender.values import DeferredConstant + if not hasattr(group, "bl_rna"): + if isinstance(operand, Value): + return operand + if isinstance(operand, DeferredConstant): + return Value(object(), operand.typ) + return require_original(group, operand, context=context, + allow_native_conversion=allow_native_conversion) + + monkeypatch.setattr(blender_ir_lowering, "require_output", mock_require_output) def mock_sample_delivery(group, socket, operand, *, context="node input"): if isinstance(socket, _SampleSocket): From 90f23623f635adc58d6c7ec5ec57b5fe077ca0a6 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 01:23:08 +0000 Subject: [PATCH 07/14] fix: preserve constant socket realization through group updates --- blender/group_backend.py | 36 +++++++++ tests/blender/test_bundle_runtime.py | 54 +++++++++++++ tests/blender/test_unified_root_update.py | 93 +++++++++++++++++++++++ 3 files changed, 183 insertions(+) diff --git a/blender/group_backend.py b/blender/group_backend.py index 029fd89..b2fc16c 100644 --- a/blender/group_backend.py +++ b/blender/group_backend.py @@ -367,6 +367,42 @@ def _sync_bundle_dynamic_items(src_group, node_map): f"Failed to recreate Bundle item {src_item.name!r} on node {src_node.name!r}: {exc}" ) from exc + # Items rebuild their input/output sockets after generic RNA copying. + # Restore their defaults now, otherwise successful updates silently + # replace unlinked constant values with Blender's initial zero values. + for direction in ("inputs", "outputs"): + source = getattr(src_node, direction) + target = getattr(dst_node, direction) + if len(source) != len(target): + raise CompileError(f"Bundle cutover changed {direction} count on {src_node.name!r}") + for src_socket, dst_socket in zip(source, target): + if (src_socket.name != dst_socket.name + or src_socket.bl_idname != dst_socket.bl_idname): + raise CompileError(f"Bundle cutover changed {direction} socket type/name on {src_node.name!r}") + if not hasattr(src_socket, "default_value"): + continue + _copy_socket_default(src_socket, dst_socket) + before = src_socket.default_value + after = dst_socket.default_value + if hasattr(before, 'as_pointer'): + equal = hasattr(after, 'as_pointer') and before.as_pointer() == after.as_pointer() + elif isinstance(before, (str, int, float, bool)): + equal = before == after + else: + try: + old, new = tuple(before), tuple(after) + except (TypeError, ValueError): + equal = before == after + else: + equal = len(old) == len(new) and all( + abs(float(a) - float(b)) <= 1e-6 for a, b in zip(old, new) + ) + if not equal: + raise CompileError( + f"Bundle cutover lost {direction} default {src_socket.name!r} " + f"on {src_node.name!r}" + ) + for attr in ("active_index", "define_signature"): if not hasattr(src_node, attr) or not hasattr(dst_node, attr): continue diff --git a/tests/blender/test_bundle_runtime.py b/tests/blender/test_bundle_runtime.py index 7ee0e29..63ec9d4 100644 --- a/tests/blender/test_bundle_runtime.py +++ b/tests/blender/test_bundle_runtime.py @@ -421,3 +421,57 @@ def test_bundle_backend_rejects_unsupported_and_foreign_runtime_items(): finally: bpy.data.node_groups.remove(group, do_unlink=True) bpy.data.node_groups.remove(other, do_unlink=True) + + +def test_bundle_rebuild_preserves_dynamic_direct_defaults_and_physical_bundle_link(): + """Configured dynamic item defaults survive cutover; invalid signatures roll back.""" + before = ''' +def nf_fixture(): + state = bundle(value=1.25, enabled=True, direction=vector(1, 2, 3)) + state = bundle_set(state, "value", 5.0) + return (state,) +''' + after = ''' +def nf_fixture(): + state = bundle(value=7.5, label="updated", enabled=False) + state = bundle_set(state, "value", 2.5) + return (state,) +''' + group = compile_group(before, 'NFTest_bundle_constant_update') + root_pointer = group.as_pointer() + + def current(): + node = _one_node(group, 'NodeCombineBundle') + return node, _one_node(group, 'NodeStoreBundleItem') + + combine, store = current() + assert [item.name for item in combine.bundle_items] == ['value', 'enabled', 'direction'] + for socket, default in (('value', 1.25), ('enabled', True), ('direction', (1, 2, 3))): + assert not combine.inputs[socket].is_linked + observed = combine.inputs[socket].default_value + assert (tuple(observed) if socket == 'direction' else observed) == default + assert store.inputs['Bundle'].is_linked + assert store.inputs['Path'].default_value == 'value' and not store.inputs['Path'].is_linked + assert store.inputs['Item'].default_value == 5.0 and not store.inputs['Item'].is_linked + + prepared_create_or_update(after, group.name, existing_group=group) + assert group.as_pointer() == root_pointer + combine, store = current() + assert [item.name for item in combine.bundle_items] == ['value', 'label', 'enabled'] + assert combine.inputs['value'].default_value == 7.5 and not combine.inputs['value'].is_linked + assert combine.inputs['label'].default_value == 'updated' and not combine.inputs['label'].is_linked + assert combine.inputs['enabled'].default_value is False and not combine.inputs['enabled'].is_linked + assert store.inputs['Item'].default_value == 2.5 and not store.inputs['Item'].is_linked + assert store.inputs['Bundle'].is_linked + + blender_group_backend._TEST_CUTOVER_FAIL_AFTER_RESET = True + try: + with pytest.raises(RuntimeError): + prepared_create_or_update(before, group.name, existing_group=group) + finally: + blender_group_backend._TEST_CUTOVER_FAIL_AFTER_RESET = False + assert group.as_pointer() == root_pointer + combine, store = current() + assert [item.name for item in combine.bundle_items] == ['value', 'label', 'enabled'] + assert combine.inputs['value'].default_value == 7.5 + assert store.inputs['Item'].default_value == 2.5 and store.inputs['Bundle'].is_linked diff --git a/tests/blender/test_unified_root_update.py b/tests/blender/test_unified_root_update.py index b7948c8..c6f1ce5 100644 --- a/tests/blender/test_unified_root_update.py +++ b/tests/blender/test_unified_root_update.py @@ -758,3 +758,96 @@ def fail_with_created_node(context, *_args, **_kwargs): tx.rollback() assert tx._closed assert {node.as_pointer() for node in tree.nodes} == old_pointers + + +def test_update_preserves_contextual_position_link_vs_true_omission_and_schema_v2(): + """A replaced raw node retains the precise present/absent input contract.""" + from NodeForge.blender import raw_nodes + + tree, _, outlet = _root('NFR5_constant_position_update') + explicit = ('base = cube(2)\n' + 'result = node("GeometryNodeSetPosition", ' + 'inputs={"Geometry": base, "Position": vector(0, 0, 0)}, ' + 'output="Geometry", typ=Geometry)\n') + omitted = ('base = cube(2)\n' + 'result = node("GeometryNodeSetPosition", ' + 'inputs={"Geometry": base}, output="Geometry", typ=Geometry)\n') + + def contract(node, identifier): + spec = raw_nodes.raw_node_spec(node) + assert spec['schema_version'] == raw_nodes.RAW_SCHEMA_VERSION == 2 + return next((row for row in spec['inputs'] + if row['socket'].identifier == identifier), None) + + def setpos(): + nodes = [node for node in tree.nodes if node.bl_idname == 'GeometryNodeSetPosition'] + assert len(nodes) == 1 + return nodes[0] + + def vertices(obj): + bpy.context.view_layer.update() + evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()) + mesh = evaluated.to_mesh() + try: + return [tuple(round(float(x), 4) for x in v.co) for v in mesh.vertices] + finally: + evaluated.to_mesh_clear() + + obj = bpy.data.objects.new('NFR5_position_obj', bpy.data.meshes.new('NFR5_position_mesh')) + bpy.context.collection.objects.link(obj) + mod = obj.modifiers.new('Nodes', 'NODES') + mod.node_group = tree + try: + compile_root(explicit, tree) + node = setpos() + tree.links.new(node.outputs['Geometry'], outlet.inputs['Geometry']) + assert node.inputs['Position'].is_linked + assert contract(node, 'Position')['mode'] == raw_nodes.INPUT_SINGLE_LINK + assert set(vertices(obj)) == {(0.0, 0.0, 0.0)} + compile_root(omitted, tree) + node = setpos() + assert not node.inputs['Position'].is_linked + assert contract(node, 'Position') is None + assert outlet.inputs['Geometry'].is_linked + assert len(set(vertices(obj))) == 8 + compile_root(explicit, tree) + node = setpos() + assert node.inputs['Position'].is_linked + assert contract(node, 'Position')['mode'] == raw_nodes.INPUT_SINGLE_LINK + assert set(vertices(obj)) == {(0.0, 0.0, 0.0)} + finally: + bpy.data.objects.remove(obj, do_unlink=True) + + +def test_update_failed_constant_delivery_keeps_published_nodes_and_realization(monkeypatch): + """An adapter failure in a staged candidate must not alter the old tree.""" + from NodeForge.blender import raw_nodes + + tree, _, outlet = _root('NFR5_constant_failure_update') + old = ('base = cube(2)\n' + 'result = node("GeometryNodeSetPosition", ' + 'inputs={"Geometry": base, "Position": vector(0, 0, 0)}, ' + 'output="Geometry", typ=Geometry)\n') + compile_root(old, tree) + node, = [item for item in tree.nodes if item.bl_idname == 'GeometryNodeSetPosition'] + tree.links.new(node.outputs['Geometry'], outlet.inputs['Geometry']) + ids = {item.as_pointer() for item in tree.nodes} + links = {(link.from_socket.as_pointer(), link.to_socket.as_pointer()) for link in tree.links} + spec_before = raw_nodes.raw_node_spec(node) + group_refs = {g.as_pointer() for g in bpy.data.node_groups} + real_deliver = raw_nodes.deliver_input + + def failing_delivery(group, socket, operand, *, context='node input'): + result = real_deliver(group, socket, operand, context=context) + if socket.identifier == 'Position' and socket.node.bl_idname == 'GeometryNodeSetPosition': + raise RuntimeError('injected deferred constant candidate failure') + return result + + monkeypatch.setattr(raw_nodes, 'deliver_input', failing_delivery) + with pytest.raises(root_update.RootUpdateError, match='injected deferred constant candidate failure'): + compile_root(old.replace('cube(2)', 'cube(3)'), tree) + node, = [item for item in tree.nodes if item.bl_idname == 'GeometryNodeSetPosition'] + assert ids == {item.as_pointer() for item in tree.nodes} + assert links == {(link.from_socket.as_pointer(), link.to_socket.as_pointer()) for link in tree.links} + assert raw_nodes.raw_node_spec(node) == spec_before + assert group_refs == {g.as_pointer() for g in bpy.data.node_groups} From 9e83a965c12a035e507571d83a7113b88f8aca02 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 01:32:33 +0000 Subject: [PATCH 08/14] test: validate consumer-aware constant realization --- blender/input_delivery.py | 8 +++- .../blender/test_consumer_aware_constants.py | 34 +++++++++++++++++ tests/blender/test_inline_source_calls.py | 38 +++++++++++++++++++ 3 files changed, 79 insertions(+), 1 deletion(-) diff --git a/blender/input_delivery.py b/blender/input_delivery.py index 8c889be..0f890da 100644 --- a/blender/input_delivery.py +++ b/blender/input_delivery.py @@ -144,9 +144,15 @@ def require_output(group, operand, *, context: str = "constant", allow_native_co # (notably Object Info Rotation -> NodeForge Vector). Preserve the # physical source's output/owner invariants without changing types. source = operand.socket + physical = runtime_socket_nf_type(source) if (runtime_socket_owner_tree(source) is not group or not getattr(source, "is_output", False) - or runtime_socket_nf_type(source) is None): + or physical is None + or physical is not operand.typ and not ( + operand.typ is NFType.VECTOR and physical is NFType.ROTATION + )): + # Object Info's Rotation output has an existing Blender-native + # Rotation->Vector conversion. Reject every other typed mismatch. raise CompileError(f"{context}: invalid physical output socket for native group conversion") else: validate_runtime_value_socket(operand.socket, operand.typ, group, context=context) diff --git a/tests/blender/test_consumer_aware_constants.py b/tests/blender/test_consumer_aware_constants.py index af349a3..254b470 100644 --- a/tests/blender/test_consumer_aware_constants.py +++ b/tests/blender/test_consumer_aware_constants.py @@ -428,3 +428,37 @@ def test_geometry_consumer_direct_vector_and_implicit_position_link(): assert sum(n.bl_idname == "ShaderNodeCombineXYZ" for n in group.nodes) == 1 finally: bpy.data.node_groups.remove(group, do_unlink=True) + + +def test_native_output_boundary_keeps_owner_and_output_direction_strict(): + """An existing native type conversion never permits a foreign or input socket.""" + from NodeForge.blender.input_delivery import require_output + from NodeForge.blender.values import Value + from NodeForge.nf_types import NFType + from NodeForge.errors import CompileError + + group = bpy.data.node_groups.new('NFC_AllowNativeOwner', 'GeometryNodeTree') + foreign = bpy.data.node_groups.new('NFC_ForeignNativeOwner', 'GeometryNodeTree') + try: + own = group.nodes.new('ShaderNodeValue') + another = foreign.nodes.new('ShaderNodeValue') + own_value = Value(own.outputs[0], NFType.FLOAT) + assert require_output(group, own_value, context='test', allow_native_conversion=True) is own_value + with pytest.raises(CompileError, match='invalid physical output socket'): + require_output(group, Value(another.outputs[0], NFType.FLOAT), + context='test', allow_native_conversion=True) + math = group.nodes.new('ShaderNodeMath') + with pytest.raises(CompileError, match='invalid physical output socket'): + require_output(group, Value(math.inputs[0], NFType.FLOAT), + context='test', allow_native_conversion=True) + native_rotation = group.nodes.new('FunctionNodeInputRotation') + # Existing Object Info style physical Rotation -> semantic Vector output. + converted = Value(native_rotation.outputs[0], NFType.VECTOR) + assert require_output(group, converted, context='test', allow_native_conversion=True) is converted + string_node = group.nodes.new('FunctionNodeInputString') + with pytest.raises(CompileError, match='invalid physical output socket'): + require_output(group, Value(string_node.outputs[0], NFType.FLOAT), + context='test', allow_native_conversion=True) + finally: + bpy.data.node_groups.remove(group) + bpy.data.node_groups.remove(foreign) diff --git a/tests/blender/test_inline_source_calls.py b/tests/blender/test_inline_source_calls.py index a0d3aee..043e1fe 100644 --- a/tests/blender/test_inline_source_calls.py +++ b/tests/blender/test_inline_source_calls.py @@ -700,3 +700,41 @@ def injected(*args, **kwargs): assert {node.as_pointer() for node in target.nodes} == node_pointers assert {group.as_pointer() for group in bpy.data.node_groups} == group_pointers assert all(link.is_valid for link in target.links) + + +def test_installed_nodeforge_nodes_constants_respect_socket_fallbacks(tmp_path): + """Real v1.3 wrapper defaults preserve ordinary and contextual socket semantics.""" + from pathlib import Path + from NodeForge import packages + + source_root = Path(__file__).resolve().parents[3] / 'nodeforge.nodes' + if not (source_root / 'nodeforge_package.json').exists(): + pytest.skip('nodeforge.nodes integration source is not installed beside NodeForge') + packages.set_packages_dir_for_tests(tmp_path / 'installed') + try: + packages.install_package_directory(source_root) + cube_tree = _compose('''from packages import nodes +result, uv = nodes.mesh.primitives.mesh_cube(size_value=vector(2, 1, 1.5)) +''', 'NFTest_Nodes_Issue67_Cube') + native_cube, = _nodes(cube_tree, 'GeometryNodeMeshCube') + assert not native_cube.inputs['Size'].is_linked + assert tuple(native_cube.inputs['Size'].default_value) == pytest.approx((2, 1, 1.5)) + assert not _nodes(cube_tree, 'ShaderNodeCombineXYZ') + assert not _nodes(cube_tree, 'GeometryNodeGroup') + + write_tree = _compose('''from packages import nodes +result = nodes.geometry.write.set_position_node(cube(1.0)) +''', 'NFTest_Nodes_Issue67_Position') + node, = _nodes(write_tree, 'GeometryNodeSetPosition') + assert node.inputs['Position'].is_linked + assert node.inputs['Position'].links[0].from_socket.bl_idname == 'NodeSocketVector' + assert not _nodes(write_tree, 'GeometryNodeGroup') + + grouped_tree = _compose('''from packages import nodes +result, uv = nodes.mesh.primitives.mesh_cube(__inline__=False) +''', 'NFTest_Nodes_Issue67_Grouped') + group_node, = _nodes(grouped_tree, 'GeometryNodeGroup') + assert not _nodes(grouped_tree, 'GeometryNodeMeshCube') + assert len(_nodes(group_node.node_tree, 'GeometryNodeMeshCube')) == 1 + finally: + packages.set_packages_dir_for_tests(None) From f5a1c93d23ec1baff31e07743586b3854f94fab6 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 01:58:21 +0000 Subject: [PATCH 09/14] fix: deliver known inline String constants to Menu sockets --- blender/input_delivery.py | 17 ++++- tests/blender/test_deferred_menu_literals.py | 76 ++++++++++++++++++++ 2 files changed, 90 insertions(+), 3 deletions(-) create mode 100644 tests/blender/test_deferred_menu_literals.py diff --git a/blender/input_delivery.py b/blender/input_delivery.py index 0f890da..b169f6c 100644 --- a/blender/input_delivery.py +++ b/blender/input_delivery.py @@ -118,12 +118,23 @@ def validate_input(group, socket, operand, *, context: str = "node input"): raise CompileError(f"{context}: input belongs to a different node tree") if bool(getattr(socket, "is_unavailable", False)) or not bool(getattr(socket, "enabled", True)): raise CompileError(f"{context}: input socket is unavailable") - if getattr(socket, "bl_idname", "") == "NodeSocketMenu" and not isinstance(operand, (Value, DeferredConstant)): - if type(operand) is not str or not operand: + if getattr(socket, "bl_idname", "") == "NodeSocketMenu": + if isinstance(operand, DeferredConstant): + # An inline String default is still a known enum literal, not a + # String output socket. Menu inputs have no runtime String link. + if operand.typ is not NFType.STRING: + raise CompileError(f"{context}: Menu input requires a String enum literal") + operand.bind_group(group) + literal = operand.value + elif type(operand) is str: + literal = operand + else: + raise CompileError(f"{context}: Menu input requires a compile-time String enum literal") + if not literal: raise CompileError(f"{context}: Menu input requires a non-empty enum literal") if not hasattr(socket, "default_value"): raise CompileError(f"{context}: Menu input has no supported literal default") - return MenuLiteral(operand) + return MenuLiteral(literal) if isinstance(operand, Value): _validate_type(socket, operand.typ, context) validate_runtime_value_socket(operand.socket, operand.typ, group, context=context) diff --git a/tests/blender/test_deferred_menu_literals.py b/tests/blender/test_deferred_menu_literals.py new file mode 100644 index 0000000..dabdfb1 --- /dev/null +++ b/tests/blender/test_deferred_menu_literals.py @@ -0,0 +1,76 @@ +"""Known inline String constants use literal-only Blender Menu socket defaults.""" + +import bpy +import pytest + +from helpers import compile_root +from NodeForge.blender import raw_nodes +from NodeForge.blender.root_update import RootUpdateError + +pytestmark = pytest.mark.blender + + +def _compile_menu(source, suffix): + """Compile a test source into a fresh tree, returning its raw Menu node.""" + tree = bpy.data.node_groups.new(f'NFTest_Menu_Deferred_{suffix}', 'GeometryNodeTree') + compile_root(source, tree) + nodes = [n for n in tree.nodes if n.bl_idname == 'GeometryNodeResampleCurve'] + assert len(nodes) == 1 + return tree, nodes[0] + + +@pytest.mark.parametrize('call,expected', [('wrap()', 'Count'), ("wrap('Length')", 'Length')]) +def test_inline_menu_string_default_and_explicit_enum_use_native_literal(call, expected): + """Inline String constants retain raw literal metadata without producers.""" + tree, node = _compile_menu('''def wrap(mode: String = 'Count', __inline__=True) -> Geometry: + return node('GeometryNodeResampleCurve', inputs={ID('Mode'):mode}, output=ID('Curve'), typ=Geometry) +result = ''' + call, expected) + socket, = [s for s in node.inputs if s.identifier == 'Mode' and s.bl_idname == 'NodeSocketMenu'] + assert socket.bl_idname == 'NodeSocketMenu' + assert socket.default_value == expected and not socket.is_linked + assert len(tree.links) == 0 + assert not any(n.bl_idname == 'FunctionNodeInputString' for n in tree.nodes) + spec = raw_nodes.raw_node_spec(node) + assert spec['schema_version'] == raw_nodes.RAW_SCHEMA_VERSION + assert any(e['mode'] == raw_nodes.INPUT_LITERAL and e['default'] == expected + and e['socket'].identifier == socket.identifier for e in spec['inputs']) + + +@pytest.mark.parametrize('bad', ["wrap('NOT_A_MODE')", "wrap('')"]) +def test_inline_menu_invalid_enum_is_rejected_without_publication(bad): + """Invalid/empty compile-time strings cannot publish a partial Menu node.""" + tree = bpy.data.node_groups.new('NFTest_Menu_Deferred_Invalid', 'GeometryNodeTree') + source = '''def wrap(mode: String = 'Count', __inline__=True) -> Geometry: + return node('GeometryNodeResampleCurve', inputs={ID('Mode'):mode}, output=ID('Curve'), typ=Geometry) +result = ''' + bad + with pytest.raises(RootUpdateError): + compile_root(source, tree) + assert not [n for n in tree.nodes if n.bl_idname == 'GeometryNodeResampleCurve'] + + +def test_runtime_string_menu_remains_unsupported(): + """A physical String output is not interchangeable with a Menu enum.""" + tree = bpy.data.node_groups.new('NFTest_Menu_Deferred_Runtime', 'GeometryNodeTree') + source = '''def wrap(mode: String, __inline__=True) -> Geometry: + return node('GeometryNodeResampleCurve', inputs={ID('Mode'):mode}, output=ID('Curve'), typ=Geometry) +value = node('FunctionNodeInputString', props={'string':'Count'}, output='String', typ=String) +result = wrap(value) +''' + with pytest.raises(RootUpdateError, match='compile-time String enum literal'): + compile_root(source, tree) + assert not [n for n in tree.nodes if n.bl_idname == 'GeometryNodeResampleCurve'] + + +def test_menu_rejects_deferred_non_string_type_at_physical_boundary(): + """A typed numeric constant cannot bypass the strict Menu String contract.""" + from NodeForge.blender.input_delivery import validate_input + from NodeForge.blender.values import DeferredConstant + from NodeForge.errors import CompileError + from NodeForge.nf_types import NFType + + tree = bpy.data.node_groups.new('NFTest_Menu_Deferred_Type', 'GeometryNodeTree') + node = tree.nodes.new('GeometryNodeResampleCurve') + socket, = [s for s in node.inputs if s.identifier == 'Mode' and s.bl_idname == 'NodeSocketMenu'] + with pytest.raises(CompileError, match='String enum literal'): + validate_input(tree, socket, DeferredConstant(NFType.INT, 1)) + assert not socket.is_linked From c8a427957250b8b88a81f7e22287c00002d02a70 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 02:16:18 +0000 Subject: [PATCH 10/14] fix: preserve known inline Strings across Menu forwarding --- blender/input_delivery.py | 2 +- blender/ir_lowering.py | 5 +- blender/values.py | 10 +- tests/blender/test_deferred_menu_literals.py | 103 +++++++++++++++++++ 4 files changed, 117 insertions(+), 3 deletions(-) diff --git a/blender/input_delivery.py b/blender/input_delivery.py index b169f6c..7e60c31 100644 --- a/blender/input_delivery.py +++ b/blender/input_delivery.py @@ -213,7 +213,7 @@ def deliver_input(group, socket, operand, *, context: str = "node input") -> Inp raise CompileError(f"{context}: failed to link runtime input: {exc}") from exc return InputRealization("single_link", links=1) checked.bind_group(group) - if _is_safe_default(socket): + if _is_safe_default(socket) and not checked._shared_runtime: default = checked.value if checked.typ is NFType.INT and _input_type(socket) is NFType.FLOAT: default = canonicalize_group_input_default(NFType.FLOAT, default) diff --git a/blender/ir_lowering.py b/blender/ir_lowering.py index 4f23ce4..59d2813 100644 --- a/blender/ir_lowering.py +++ b/blender/ir_lowering.py @@ -731,7 +731,10 @@ def _inline_parameter_bindings(context, operation, operands, prepared, x, y): if isinstance(value, DeferredConstant) and not _inline_parameter_is_direct_single_sink( prepared.group.body, origin ): - value = require_output(context.group, value, context=f"inline argument {parameter.display_name}") + # Retain literal provenance for consumers without runtime inputs + # (notably Menu enums). Other consumers still share one physical + # producer, materialized at the first real socket boundary. + value.share_runtime_consumers() if origin in bound: raise CompileError("Internal error: inline declaration was bound more than once") bound[origin] = value diff --git a/blender/values.py b/blender/values.py index 5cfba28..32d9368 100644 --- a/blender/values.py +++ b/blender/values.py @@ -63,13 +63,21 @@ class DeferredConstant: share its single producer once the value is physically required. """ - __slots__ = ("payload", "_owner_group", "_materialized") + __slots__ = ("payload", "_owner_group", "_materialized", "_shared_runtime") def __init__(self, typ: NFType, value): """Create one canonical value without mutating any Blender node tree.""" self.payload = ConstantPayload(typ, value) self._owner_group = None self._materialized = None + self._shared_runtime = False + + def share_runtime_consumers(self) -> None: + """Use one physical producer for non-literal consumers of a shared inline value. + + Literal-only sockets may still consume the original constant directly. + """ + self._shared_runtime = True @property def typ(self) -> NFType: diff --git a/tests/blender/test_deferred_menu_literals.py b/tests/blender/test_deferred_menu_literals.py index dabdfb1..dca870d 100644 --- a/tests/blender/test_deferred_menu_literals.py +++ b/tests/blender/test_deferred_menu_literals.py @@ -74,3 +74,106 @@ def test_menu_rejects_deferred_non_string_type_at_physical_boundary(): with pytest.raises(CompileError, match='String enum literal'): validate_input(tree, socket, DeferredConstant(NFType.INT, 1)) assert not socket.is_linked + +@pytest.mark.parametrize('call, expected', [("wrap()", 'Count'), ("wrap('Length')", 'Length')]) +def test_inline_menu_known_string_survives_alias(call, expected): + """A source-level alias must not erase known literal-only Menu provenance.""" + tree, node = _compile_menu('''def wrap(mode: String = 'Count', __inline__=True) -> Geometry: + alias = mode + return node('GeometryNodeResampleCurve', inputs={ID('Mode'): alias}, output=ID('Curve'), typ=Geometry) +result = ''' + call, 'alias_' + expected) + assert node.inputs['Mode'].default_value == expected + assert len(tree.links) == 0 + assert not any(n.bl_idname == 'FunctionNodeInputString' for n in tree.nodes) + assert raw_nodes.raw_node_spec(node)['inputs'][0]['mode'] == raw_nodes.INPUT_LITERAL + + +@pytest.mark.parametrize('call, expected', [('outer()', 'Count'), ("outer('Length')", 'Length')]) +def test_inline_menu_known_string_survives_nested_inline(call, expected): + """A nested inline call preserves its compile-time String argument.""" + tree, node = _compile_menu('''def inner(mode: String, __inline__=True) -> Geometry: + return node('GeometryNodeResampleCurve', inputs={ID('Mode'): mode}, output=ID('Curve'), typ=Geometry) +def outer(mode: String = 'Count', __inline__=True) -> Geometry: + return inner(mode) +result = ''' + call, 'nested_' + expected) + assert node.inputs['Mode'].default_value == expected + assert len(tree.links) == 0 + assert not any(n.bl_idname == 'FunctionNodeInputString' for n in tree.nodes) + + +def test_inline_known_string_two_menus_have_defaults_without_unused_producer(): + """Literal-only consumers may reuse a known value without a String node.""" + tree = bpy.data.node_groups.new('NFTest_Menu_Deferred_Multiple', 'GeometryNodeTree') + compile_root('''def wrap(mode: String = 'Count', __inline__=True) -> Geometry: + one = node('GeometryNodeResampleCurve', inputs={ID('Mode'):mode}, output=ID('Curve'), typ=Geometry) + return node('GeometryNodeResampleCurve', inputs={ID('Mode'):mode}, output=ID('Curve'), typ=Geometry) +result = wrap() +''', tree) + menus = [n for n in tree.nodes if n.bl_idname == 'GeometryNodeResampleCurve'] + assert len(menus) == 2 + assert all(node.inputs['Mode'].default_value == 'Count' for node in menus) + assert all(raw_nodes.raw_node_spec(node)['inputs'][0]['mode'] == raw_nodes.INPUT_LITERAL for node in menus) + assert not any(n.bl_idname == 'FunctionNodeInputString' for n in tree.nodes) + assert not tree.links + + +def test_inline_known_string_menu_and_ordinary_string_share_physical_when_needed(): + """Conservative multi-use sharing still links ordinary String inputs.""" + tree = bpy.data.node_groups.new('NFTest_Menu_Deferred_Mixed', 'GeometryNodeTree') + compile_root('''def wrap(mode: String = 'Count', __inline__=True) -> Geometry: + exists = node('GeometryNodeInputNamedAttribute', props={'data_type':'FLOAT'}, inputs={'Name':mode}, output='Exists', typ=Bool) + return node('GeometryNodeResampleCurve', inputs={ID('Mode'):mode}, output=ID('Curve'), typ=Geometry) +result = wrap() +''', tree) + menu, = [n for n in tree.nodes if n.bl_idname == 'GeometryNodeResampleCurve'] + named, = [n for n in tree.nodes if n.bl_idname == 'GeometryNodeInputNamedAttribute'] + producers = [n for n in tree.nodes if n.bl_idname == 'FunctionNodeInputString'] + assert len(producers) == 1 + assert menu.inputs['Mode'].default_value == 'Count' + assert not menu.inputs['Mode'].is_linked + assert named.inputs['Name'].is_linked + assert named.inputs['Name'].links[0].from_node == producers[0] + assert raw_nodes.raw_node_spec(menu)['inputs'][0]['mode'] == raw_nodes.INPUT_LITERAL + assert raw_nodes.raw_node_spec(named)['inputs'][0]['mode'] == raw_nodes.INPUT_SINGLE_LINK + + +def test_inline_known_string_two_regular_consumers_share_one_producer(): + """Existing conservative multi-sink policy remains for runtime-capable inputs.""" + tree = bpy.data.node_groups.new('NFTest_Menu_Deferred_TwoRegular', 'GeometryNodeTree') + compile_root('''def wrap(mode: String = 'Count', __inline__=True) -> Bool: + a = node('GeometryNodeInputNamedAttribute', props={'data_type':'FLOAT'}, inputs={'Name':mode}, output='Exists', typ=Bool) + b = node('GeometryNodeInputNamedAttribute', props={'data_type':'FLOAT'}, inputs={'Name':mode}, output='Exists', typ=Bool) + return b +result = wrap() +''', tree) + named = [n for n in tree.nodes if n.bl_idname == 'GeometryNodeInputNamedAttribute'] + producers = [n for n in tree.nodes if n.bl_idname == 'FunctionNodeInputString'] + assert len(producers) == 1 + assert len(named) == 2 + assert all(n.inputs['Name'].is_linked and n.inputs['Name'].links[0].from_node == producers[0] for n in named) + + +def test_inline_menu_nested_runtime_string_still_rejected(): + """Nested forwarding never turns a physical runtime String into an enum.""" + tree = bpy.data.node_groups.new('NFTest_Menu_Deferred_NestedRuntime', 'GeometryNodeTree') + with pytest.raises(RootUpdateError, match='compile-time String enum literal'): + compile_root('''def inner(mode: String, __inline__=True) -> Geometry: + return node('GeometryNodeResampleCurve', inputs={ID('Mode'):mode}, output=ID('Curve'), typ=Geometry) +def outer(mode: String, __inline__=True) -> Geometry: + return inner(mode) +value = node('FunctionNodeInputString', props={'string':'Count'}, output='String', typ=String) +result = outer(value) +''', tree) + assert not any(n.bl_idname == 'GeometryNodeResampleCurve' for n in tree.nodes) + + +def test_inline_menu_alias_invalid_enum_still_rejected(): + """Unknown enum values stay invalid after alias propagation.""" + tree = bpy.data.node_groups.new('NFTest_Menu_Deferred_AliasInvalid', 'GeometryNodeTree') + with pytest.raises(RootUpdateError): + compile_root('''def wrap(mode: String = 'NOPE', __inline__=True) -> Geometry: + alias = mode + return node('GeometryNodeResampleCurve', inputs={ID('Mode'): alias}, output=ID('Curve'), typ=Geometry) +result = wrap() +''', tree) + assert not any(n.bl_idname == 'GeometryNodeResampleCurve' for n in tree.nodes) From 8394ec36336203d39348182d2d194f2f6b82543a Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 02:33:48 +0000 Subject: [PATCH 11/14] fix: restore shared physical operands for non-String inline values --- blender/ir_lowering.py | 13 ++- tests/blender/test_shared_inline_nonstring.py | 95 +++++++++++++++++++ 2 files changed, 104 insertions(+), 4 deletions(-) create mode 100644 tests/blender/test_shared_inline_nonstring.py diff --git a/blender/ir_lowering.py b/blender/ir_lowering.py index 59d2813..f94d453 100644 --- a/blender/ir_lowering.py +++ b/blender/ir_lowering.py @@ -731,10 +731,15 @@ def _inline_parameter_bindings(context, operation, operands, prepared, x, y): if isinstance(value, DeferredConstant) and not _inline_parameter_is_direct_single_sink( prepared.group.body, origin ): - # Retain literal provenance for consumers without runtime inputs - # (notably Menu enums). Other consumers still share one physical - # producer, materialized at the first real socket boundary. - value.share_runtime_consumers() + if value.typ is TYPE_STRING: + # Literal-only Menu sockets need the known String even when + # other consumers require a shared physical String producer. + value.share_runtime_consumers() + else: + # Eager realization preserves non-String sharing through + # consumers that rewrap Bool or unpack numeric arguments. + value = require_output(context.group, value, + context=f"inline argument {parameter.display_name}") if origin in bound: raise CompileError("Internal error: inline declaration was bound more than once") bound[origin] = value diff --git a/tests/blender/test_shared_inline_nonstring.py b/tests/blender/test_shared_inline_nonstring.py new file mode 100644 index 0000000..aeea785 --- /dev/null +++ b/tests/blender/test_shared_inline_nonstring.py @@ -0,0 +1,95 @@ +"""Issue #67: multi-consumer non-String inline values retain one physical source. + +F02 preserves deferred String for literal-only Menu sockets. That choice must +not change sharing of other inline types when downstream builtins adapt them. +""" + +import bpy +import pytest + +from helpers import compile_root + +pytestmark = pytest.mark.blender + + +def _compile(source, name): + tree = bpy.data.node_groups.new(name, "GeometryNodeTree") + compile_root(source, tree) + return tree + + +def _nodes(tree, type_id): + return [node for node in tree.nodes if node.bl_idname == type_id] + + +def _shared_output_reaches(tree, producer, consumers, input_name): + """Assert each consumer receives the same actual output socket.""" + output = producer.outputs[0] + assert len(consumers) == 2 + for consumer in consumers: + destination = consumer.inputs[input_name] + assert destination.is_linked + assert len(destination.links) == 1 + assert destination.links[0].from_socket == output + assert sum(link.from_socket == output for link in tree.links) == 2 + + +def test_multi_consumer_bool_compare_uses_one_bool_source(): + """Bool-to-Int Compare must not lose a shared inline Bool source.""" + tree = _compile('''def wrap(flag: Bool = True, __inline__=True) -> Bool: + a = flag == False + b = flag == True + return b +result = wrap() +''', "NFTest_SharedInline_BoolCompare") + producer, = _nodes(tree, "FunctionNodeInputBool") + comparisons = _nodes(tree, "FunctionNodeCompare") + assert len(comparisons) == 2 + assert all(node.data_type == "INT" for node in comparisons) + _shared_output_reaches(tree, producer, comparisons, "A") + assert all(link.is_valid for link in tree.links) + + +def test_multi_consumer_points_count_uses_one_int_source(): + """points() must not discard multi-sink provenance during numeric conversion.""" + tree = _compile('''def wrap(count: Int = 3, __inline__=True) -> Geometry: + a = points(count) + return points(count) +result = wrap() +''', "NFTest_SharedInline_Points") + producer, = _nodes(tree, "FunctionNodeInputInt") + lines = _nodes(tree, "GeometryNodeMeshLine") + _shared_output_reaches(tree, producer, lines, "Count") + assert all(link.is_valid for link in tree.links) + + +def test_multi_consumer_scalar_cube_uses_one_float_source(): + """Scalar cube() input expanded to vectors still shares a physical Float.""" + tree = _compile('''def wrap(size: Float = 2.0, __inline__=True) -> Geometry: + a = cube(size) + return cube(size) +result = wrap() +''', "NFTest_SharedInline_Cubes") + producer, = _nodes(tree, "ShaderNodeValue") + vectors = _nodes(tree, "ShaderNodeCombineXYZ") + assert len(vectors) == 2 + assert len(_nodes(tree, "GeometryNodeMeshCube")) == 2 + assert all(link.is_valid for link in tree.links) + assert sum(link.from_socket == producer.outputs[0] for link in tree.links) == 6 + assert all( + all(socket.is_linked and socket.links[0].from_socket == producer.outputs[0] + for socket in vector.inputs) + for vector in vectors + ) + + +def test_single_consumer_nonstring_still_uses_default_without_producer(): + """Restoring multi-use sharing does not restore eager materialization to a single sink.""" + tree = _compile('''def wrap(count: Int = 3, __inline__=True) -> Geometry: + return points(count) +result = wrap() +''', "NFTest_SharedInline_Single") + line, = _nodes(tree, "GeometryNodeMeshLine") + assert line.inputs["Count"].default_value == 3 + assert not line.inputs["Count"].is_linked + assert not _nodes(tree, "FunctionNodeInputInt") From 79716c37e4d559434f8acc6ca7025653ca3f5467 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 02:54:05 +0000 Subject: [PATCH 12/14] refactor: consolidate geometry input conversions and drop dead inline materializer --- blender/geometry.py | 108 ++++++++++++++--------------- blender/ir_lowering.py | 24 +------ tests/unit/test_inline_lowering.py | 76 +++++++------------- tests/unit/test_semantic_ir.py | 17 ++--- 4 files changed, 86 insertions(+), 139 deletions(-) diff --git a/blender/geometry.py b/blender/geometry.py index db955c0..76e931e 100644 --- a/blender/geometry.py +++ b/blender/geometry.py @@ -183,19 +183,10 @@ def _cube_geometry(group, size, x=0, y=0): node = _new_node(group, "GeometryNodeMeshCube", x, y) for index in (1, 2, 3): node.inputs[index].default_value = 2 - if isinstance(size, DeferredConstant) and _is_number_type(size.typ): - size = (size.value,) * 3 - elif _is_const_number(size): - size = (size,) * 3 - if _is_const_vector_like(size) or ( - isinstance(size, (Value, DeferredConstant)) and size.typ == TYPE_VECTOR - ): - _set_vector_socket_value(group, node.inputs[0], size, x, y, "cube() size") - elif isinstance(size, Value) and _is_number_type(size.typ): - vector = _combine_xyz(group, size, size, size, x - 180, y - 60) - deliver_input(group, node.inputs[0], vector, context="cube() size") - else: - raise CompileError("cube(size) expects Float/Int or Vector size") + _deliver_scale( + group, node.inputs[0], size, x=x, y=y, label="cube() size", + error="cube(size) expects Float/Int or Vector size", combine_y=-60, + ) return Value(node.outputs[0], TYPE_GEOMETRY) @@ -226,6 +217,36 @@ def _set_vector_socket_value(group, socket, value, x=0, y=0, label="value"): raise CompileError(f"{label} expects Vector") +def _deliver_scale(group, socket, scale, *, x, y, label, error, combine_y): + """Deliver a scalar-uniform or Vector scale to the resolved Blender input.""" + if isinstance(scale, DeferredConstant) and _is_number_type(scale.typ): + scale = (scale.value,) * 3 + elif _is_const_number(scale): + scale = (scale,) * 3 + if _is_const_vector_like(scale) or ( + isinstance(scale, (Value, DeferredConstant)) and scale.typ == TYPE_VECTOR + ): + _set_vector_socket_value(group, socket, scale, x, y, label) + elif isinstance(scale, Value) and _is_number_type(scale.typ): + combined = _combine_xyz(group, scale, scale, scale, x - 180, y + combine_y) + deliver_input(group, socket, combined, context=label) + else: + raise CompileError(error) + + +def _deliver_euler_rotation(group, socket, rotation, *, x, y, label, error): + """Convert a Vector Euler argument to Rotation at its resolved input.""" + if isinstance(rotation, DeferredConstant) and rotation.typ == TYPE_VECTOR: + rotation = DeferredConstant(TYPE_ROTATION, rotation.value) + elif _is_const_vector_like(rotation): + rotation = DeferredConstant(TYPE_ROTATION, tuple(rotation)) + elif isinstance(rotation, Value) and rotation.typ == TYPE_VECTOR: + rotation = _euler_to_rotation(group, rotation, x - 180, y - 120) + else: + raise CompileError(error) + deliver_input(group, socket, rotation, context=label) + + def _socket_by_name_or_index(node, name, index): """Return a node input by stable name, falling back to Blender's index order.""" socket = node.inputs.get(name) if hasattr(node.inputs, "get") else None @@ -306,29 +327,15 @@ def _transform_geometry(group, geo, *, translation, scale, rotation, x=0, y=0): if translation is not None: _set_vector_socket_value(group, node.inputs[2], translation, x, y, "translation=") if rotation is not None: - if isinstance(rotation, DeferredConstant) and rotation.typ == TYPE_VECTOR: - rotation = DeferredConstant(TYPE_ROTATION, rotation.value) - elif _is_const_vector_like(rotation): - rotation = DeferredConstant(TYPE_ROTATION, tuple(rotation)) - elif isinstance(rotation, Value) and rotation.typ == TYPE_VECTOR: - rotation = _euler_to_rotation(group, rotation, x - 180, y - 120) - else: - raise CompileError("rotation= must be Vector in radians") - deliver_input(group, node.inputs[3], rotation, context="transform() rotation") + _deliver_euler_rotation( + group, node.inputs[3], rotation, x=x, y=y, + label="transform() rotation", error="rotation= must be Vector in radians", + ) if scale is not None: - if isinstance(scale, DeferredConstant) and _is_number_type(scale.typ): - scale = (scale.value,) * 3 - elif _is_const_number(scale): - scale = (scale,) * 3 - if _is_const_vector_like(scale) or ( - isinstance(scale, (Value, DeferredConstant)) and scale.typ == TYPE_VECTOR - ): - _set_vector_socket_value(group, node.inputs[4], scale, x, y, "scale=") - elif isinstance(scale, Value) and _is_number_type(scale.typ): - combined = _combine_xyz(group, scale, scale, scale, x - 180, y - 80) - deliver_input(group, node.inputs[4], combined, context="transform() scale") - else: - raise CompileError("scale= must be Float/Int or Vector") + _deliver_scale( + group, node.inputs[4], scale, x=x, y=y, label="scale=", + error="scale= must be Float/Int or Vector", combine_y=-80, + ) return Value(node.outputs[0], TYPE_GEOMETRY) @@ -402,29 +409,16 @@ def _instance_on_points(group, instance, points, *, selection, scale, rotation, deliver_input(group, node.inputs[1], selection, context="selection field") group.links.new(instance.socket, node.inputs[2]) if scale is not None: - if isinstance(scale, DeferredConstant) and _is_number_type(scale.typ): - scale = (scale.value,) * 3 - elif _is_const_number(scale): - scale = (scale,) * 3 - if _is_const_vector_like(scale) or ( - isinstance(scale, (Value, DeferredConstant)) and scale.typ == TYPE_VECTOR - ): - _set_vector_socket_value(group, node.inputs[6], scale, x, y, "instance_on_points scale") - elif isinstance(scale, Value) and _is_number_type(scale.typ): - vector = _combine_xyz(group, scale, scale, scale, x - 180, y - 80) - deliver_input(group, node.inputs[6], vector, context="instance_on_points scale") - else: - raise CompileError("instance_on_points scale= expects Float/Int or Vector") + _deliver_scale( + group, node.inputs[6], scale, x=x, y=y, label="instance_on_points scale", + error="instance_on_points scale= expects Float/Int or Vector", combine_y=-80, + ) if rotation is not None: - if isinstance(rotation, DeferredConstant) and rotation.typ == TYPE_VECTOR: - rotation = DeferredConstant(TYPE_ROTATION, rotation.value) - elif _is_const_vector_like(rotation): - rotation = DeferredConstant(TYPE_ROTATION, tuple(rotation)) - elif isinstance(rotation, Value) and rotation.typ == TYPE_VECTOR: - rotation = _euler_to_rotation(group, rotation, x - 180, y - 120) - else: - raise CompileError("instance_on_points rotation= expects Vector in radians") - deliver_input(group, node.inputs[5], rotation, context="instance_on_points rotation") + _deliver_euler_rotation( + group, node.inputs[5], rotation, x=x, y=y, + label="instance_on_points rotation", + error="instance_on_points rotation= expects Vector in radians", + ) out = Value(node.outputs[0], TYPE_GEOMETRY) if realize: return _realize_instances(group, out, x + 240, y) diff --git a/blender/ir_lowering.py b/blender/ir_lowering.py index f94d453..728d40b 100644 --- a/blender/ir_lowering.py +++ b/blender/ir_lowering.py @@ -12,7 +12,7 @@ from ..errors import CompileError from ..compiler_identities import BindingId, InputDeclarationId from ..semantic.group_context import GroupContextSlot -from .nodes import _bool_value, _color_value, _rotation_value, _vector_value, _boolean_math, _combine_xyz_mixed, _compare, _int_value, _integer_math, _math, _new_node, _separate_xyz, _string_value, _switch, _value, _vector_math +from .nodes import _boolean_math, _combine_xyz_mixed, _compare, _integer_math, _math, _new_node, _separate_xyz, _switch, _vector_math from .geometry import ( _capture_attribute_geometry, _cube_geometry, @@ -67,7 +67,7 @@ ) from .values import ObjectValue, Value, DeferredConstant, make_value from .input_delivery import deliver_input, require_output -from ..semantic.callable_contracts import canonicalize_group_input_default, source_argument_type_matches +from ..semantic.callable_contracts import source_argument_type_matches from ..semantic.ir import IRFunctionMaterializationMode from .interface import _create_group_input_socket, _create_interface_panel, _set_socket_default from ..function_instances import ( @@ -592,26 +592,6 @@ def _source_call_owner_scope(operation): return direct_library_owner_scope_for_id(function_id) -def _inline_constant_value(context, typ, value, x, y): - """Materialize a detached call argument/default as one typed runtime socket.""" - value = canonicalize_group_input_default(typ, value) - if typ is TYPE_FLOAT: - return _value(context.group, value, x, y) - if typ is TYPE_INT: - return _int_value(context.group, value, x, y) - if typ is TYPE_BOOL: - return _bool_value(context.group, value, x, y) - if typ is TYPE_STRING: - return _string_value(context.group, value, x, y) - if typ is TYPE_VECTOR: - return _vector_value(context.group, value, x, y) - if typ is TYPE_COLOR: - return _color_value(context.group, value, x, y) - if typ is TYPE_ROTATION: - return _rotation_value(context.group, value, x, y) - raise CompileError(f"Internal error: unsupported inline default of type {typ}") - - def _inline_runtime_value(context, expected, actual, x, y): """Detach physical Values while retaining deferred arguments until use.""" if not isinstance(actual, (Value, DeferredConstant)) or not source_argument_type_matches(expected, actual.typ): diff --git a/tests/unit/test_inline_lowering.py b/tests/unit/test_inline_lowering.py index b2a0371..8a925da 100644 --- a/tests/unit/test_inline_lowering.py +++ b/tests/unit/test_inline_lowering.py @@ -7,6 +7,7 @@ import pytest from NodeForge.blender import ir_lowering as backend +from NodeForge.blender import nodes as node_factories from NodeForge.blender.values import Value, DeferredConstant from NodeForge.errors import CompileError from NodeForge.semantic.ir import IRInputDeclaration @@ -24,20 +25,8 @@ def _host_only_physical_output_stub(monkeypatch): original = backend.require_output def require(group, operand, *, context="constant", allow_native_conversion=False): - if type(group) is object: - if isinstance(operand, Value): - return operand - if isinstance(operand, DeferredConstant): - emit = { - NFType.FLOAT: backend._value, - NFType.INT: backend._int_value, - NFType.BOOL: backend._bool_value, - NFType.STRING: backend._string_value, - NFType.VECTOR: backend._vector_value, - NFType.COLOR: backend._color_value, - NFType.ROTATION: backend._rotation_value, - }[operand.typ] - return emit(group, operand.value) + if type(group) is object and isinstance(operand, Value): + return operand # Host-only fake sockets have no Blender RNA owner. return original(group, operand, context=context, allow_native_conversion=allow_native_conversion) @@ -58,33 +47,14 @@ def _lower_inline(source, monkeypatch, runtime_values=()): assert len(operations) == 1 operation = operations[0] calls = [] - monkeypatch.setattr(backend, '_value', _emit_stub_value(calls, 'Float', NFType.FLOAT)) - monkeypatch.setattr(backend, '_int_value', _emit_stub_value(calls, 'Int', NFType.INT)) - monkeypatch.setattr(backend, '_bool_value', _emit_stub_value(calls, 'Bool', NFType.BOOL)) - monkeypatch.setattr(backend, '_string_value', _emit_stub_value(calls, 'String', NFType.STRING)) - monkeypatch.setattr(backend, '_vector_value', _emit_stub_value(calls, 'Vector', NFType.VECTOR)) - monkeypatch.setattr(backend, '_color_value', _emit_stub_value(calls, 'Color', NFType.COLOR)) - monkeypatch.setattr(backend, '_rotation_value', _emit_stub_value(calls, 'Rotation', NFType.ROTATION)) + monkeypatch.setattr(node_factories, '_value', _emit_stub_value(calls, 'Float', NFType.FLOAT)) + monkeypatch.setattr(node_factories, '_int_value', _emit_stub_value(calls, 'Int', NFType.INT)) + monkeypatch.setattr(node_factories, '_bool_value', _emit_stub_value(calls, 'Bool', NFType.BOOL)) + monkeypatch.setattr(node_factories, '_string_value', _emit_stub_value(calls, 'String', NFType.STRING)) + monkeypatch.setattr(node_factories, '_vector_value', _emit_stub_value(calls, 'Vector', NFType.VECTOR)) + monkeypatch.setattr(node_factories, '_color_value', _emit_stub_value(calls, 'Color', NFType.COLOR)) + monkeypatch.setattr(node_factories, '_rotation_value', _emit_stub_value(calls, 'Rotation', NFType.ROTATION)) monkeypatch.setattr(backend, '_math', _emit_stub_value(calls, 'Math', NFType.FLOAT)) - from NodeForge.blender.values import DeferredConstant - - def fake_required_output(group, operand, *, context="constant", allow_native_conversion=False): - """Host-only stubs have no Blender RNA; use their typed fake producers.""" - if isinstance(operand, Value): - return operand - assert isinstance(operand, DeferredConstant) - producer = { - NFType.FLOAT: backend._value, - NFType.INT: backend._int_value, - NFType.BOOL: backend._bool_value, - NFType.STRING: backend._string_value, - NFType.VECTOR: backend._vector_value, - NFType.COLOR: backend._color_value, - NFType.ROTATION: backend._rotation_value, - }[operand.typ] - return producer(group, operand.value) - - monkeypatch.setattr(backend, 'require_output', fake_required_output) context = backend.BlenderIRLoweringContext( group=object(), runtime_bindings={}, source_callable_session=session, function_materializer=object(), function_materialization_context=object(), @@ -149,17 +119,19 @@ def test_inline_rotation_default_materializes_once(monkeypatch): assert angles == tuple(normalize_float_constant(v) for v in (0.1, -0.2, 7.0)) -def test_inline_rotation_static_materializer_uses_same_canonical_contract(monkeypatch): - """An already-bound static Rotation value uses the same inline adapter.""" - calls = [] - monkeypatch.setattr(backend, '_rotation_value', _emit_stub_value(calls, 'Rotation', NFType.ROTATION)) - result = backend._inline_constant_value( - SimpleNamespace(group=object()), NFType.ROTATION, [0.1, -0.2, 7.0], 10, 20, - ) +def test_inline_rotation_output_materializer_uses_same_canonical_contract(monkeypatch): + """The active output boundary canonicalizes and shares a Rotation constant.""" + from NodeForge.blender.input_delivery import require_output from NodeForge.semantic.numeric_semantics import normalize_float_constant - assert result.typ is NFType.ROTATION - assert calls == [('Rotation', (tuple(normalize_float_constant(v) for v in (0.1, -0.2, 7.0)), 10, 20))] + calls = [] + monkeypatch.setattr(node_factories, '_rotation_value', _emit_stub_value(calls, 'Rotation', NFType.ROTATION)) + group = object() + value = DeferredConstant(NFType.ROTATION, [0.1, -0.2, 7.0]) + first = require_output(group, value, context='inline default') + assert require_output(group, value, context='inline default') is first + assert first.typ is NFType.ROTATION + assert calls == [('Rotation', (tuple(normalize_float_constant(v) for v in (0.1, -0.2, 7.0)),))] def test_bound_inline_coerces_runtime_int_to_float(monkeypatch): @@ -227,7 +199,7 @@ def test_two_sibling_occurrences_receive_distinct_layout_lanes(monkeypatch): ''' calls, session = _analyze(source) native = [] - monkeypatch.setattr(backend, '_value', _emit_stub_value(native, 'Float', NFType.FLOAT)) + monkeypatch.setattr(node_factories, '_value', _emit_stub_value(native, 'Float', NFType.FLOAT)) monkeypatch.setattr(backend, '_math', _emit_stub_value(native, 'Math', NFType.FLOAT)) context = backend.BlenderIRLoweringContext( group=object(), runtime_bindings={}, source_callable_session=session, @@ -250,7 +222,7 @@ def test_inline_context_map_cannot_mutate_caller(monkeypatch): return value x = identity(2.0) ''') - monkeypatch.setattr(backend, '_value', _emit_stub_value([], 'Float', NFType.FLOAT)) + monkeypatch.setattr(node_factories, '_value', _emit_stub_value([], 'Float', NFType.FLOAT)) outer = Value(StubSocket(), NFType.VECTOR) context = backend.BlenderIRLoweringContext( group=object(), runtime_bindings={}, group_context_values={GroupContextSlot.GRID_UV: outer}, @@ -276,7 +248,7 @@ def test_inline_lowering_records_dependency_on_active_physical_frame(monkeypatch return value + 1.0 result = leaf(2.0) ''') - monkeypatch.setattr(backend, '_value', _emit_stub_value([], 'Float', NFType.FLOAT)) + monkeypatch.setattr(node_factories, '_value', _emit_stub_value([], 'Float', NFType.FLOAT)) monkeypatch.setattr(backend, '_math', _emit_stub_value([], 'Math', NFType.FLOAT)) trace = FunctionCompilationTrace() context = backend.BlenderIRLoweringContext( diff --git a/tests/unit/test_semantic_ir.py b/tests/unit/test_semantic_ir.py index 2aaa116..3f2e9c9 100644 --- a/tests/unit/test_semantic_ir.py +++ b/tests/unit/test_semantic_ir.py @@ -23,6 +23,7 @@ ) from NodeForge.errors import CompileError from NodeForge.blender import ir_lowering as blender_ir_lowering +from NodeForge.blender import nodes as node_factories from NodeForge.blender import geometry as geometry_backend from NodeForge.blender.values import Value from NodeForge.semantic.group_context import GROUP_CONTEXT_SPECS, GroupContextSlot @@ -772,8 +773,8 @@ def fake_math(group, operation, args, x=0, y=0): calls.append(("math", operation, x, y)) return Value(object(), TYPE_FLOAT) - monkeypatch.setattr(backend, "_value", fake_value) - monkeypatch.setattr(backend, "_int_value", fake_int_value) + monkeypatch.setattr(node_factories, "_value", fake_value) + monkeypatch.setattr(node_factories, "_int_value", fake_int_value) monkeypatch.setattr(backend, "_math", fake_math) result = backend.lower_expression(context, _lower("a * 2", bindings={"a": TYPE_FLOAT}), base_depth=3) @@ -820,7 +821,7 @@ def fake_boolean_math(group, operation, args, x=0, y=0): calls.append(("boolean_math", operation, x, y)) return Value(object(), TYPE_BOOL) - monkeypatch.setattr(backend, "_value", fake_value) + monkeypatch.setattr(node_factories, "_value", fake_value) monkeypatch.setattr(backend, "_math", fake_math) monkeypatch.setattr(backend, "_vector_math", fake_vector_math) monkeypatch.setattr(backend, "_boolean_math", fake_boolean_math) @@ -870,8 +871,8 @@ def fake_boolean_math(group, operation, args, x=0, y=0): calls.append(("boolean_math", operation, x, y)) return Value(object(), TYPE_BOOL) - monkeypatch.setattr(backend, "_value", fake_value) - monkeypatch.setattr(backend, "_int_value", fake_int_value) + monkeypatch.setattr(node_factories, "_value", fake_value) + monkeypatch.setattr(node_factories, "_int_value", fake_int_value) monkeypatch.setattr(backend, "_math", fake_math) monkeypatch.setattr(backend, "_compare", fake_compare) monkeypatch.setattr(backend, "_boolean_math", fake_boolean_math) @@ -899,8 +900,8 @@ def fake_int_value(group, value, x=0, y=0): def fake_math(group, operation, args, x=0, y=0): return Value(object(), TYPE_VECTOR) - monkeypatch.setattr(backend, "_value", fake_value) - monkeypatch.setattr(backend, "_int_value", fake_int_value) + monkeypatch.setattr(node_factories, "_value", fake_value) + monkeypatch.setattr(node_factories, "_int_value", fake_int_value) monkeypatch.setattr(backend, "_math", fake_math) with pytest.raises(CompileError, match="expected type FLOAT, got VECTOR"): @@ -947,7 +948,7 @@ def fake_separate_xyz(group, value, component, x=0, y=0): calls.append(("component", component, x, y)) return Value(object(), TYPE_FLOAT) - monkeypatch.setattr(backend, "_value", fake_value) + monkeypatch.setattr(node_factories, "_value", fake_value) monkeypatch.setattr(backend, "_math", fake_math) monkeypatch.setattr(backend, "_vector_math", fake_vector_math) monkeypatch.setattr(backend, "_boolean_math", fake_boolean_math) From 0ec08710d3a8ed9b155115d491e148cc7e36b0bc Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 15:27:00 +0000 Subject: [PATCH 13/14] chore(release): consolidate Issue #67 changelog and bump to 0.97.8 --- __init__.py | 2 +- blender_manifest.toml | 2 +- dev/CHANGELOG.md | 11 +++++++++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/__init__.py b/__init__.py index 8020af2..af719c7 100644 --- a/__init__.py +++ b/__init__.py @@ -1,6 +1,6 @@ """NodeForge Blender addon package.""" -NODEFORGE_VERSION = (0, 97, 4) +NODEFORGE_VERSION = (0, 97, 8) bl_info = { "name": "NodeForge", "author": "nachitima", diff --git a/blender_manifest.toml b/blender_manifest.toml index fa8b397..cb829ec 100644 --- a/blender_manifest.toml +++ b/blender_manifest.toml @@ -1,6 +1,6 @@ schema_version = "1.0.0" id = "nodeforge" -version = "0.97.4" +version = "0.97.8" name = "NodeForge" tagline = "Compile a procedural DSL into Blender Geometry Nodes" maintainer = "nachitima" diff --git a/dev/CHANGELOG.md b/dev/CHANGELOG.md index 3a3e228..efa65f5 100644 --- a/dev/CHANGELOG.md +++ b/dev/CHANGELOG.md @@ -820,3 +820,14 @@ lifecycle. - Added Blender characterization sources, deterministic graph baselines and focused assertions for Python Extension API v2 inline/grouped placement, nested calls, DynamicResults, compacted semantic dependencies, and Capture Attribute Rotation. - Extended characterization snapshots to retain Capture Attribute item types, domain and unlinked Float item defaults without changing existing recorded cases. + +## 0.97.8 + +- Added consumer-aware typed constant delivery across raw Blender nodes, Math/Compare/Vector operators, geometry builtins, dynamic Bundle inputs, and inline/grouped functions, storing eligible literals in native input defaults instead of creating redundant constant nodes. +- Preserved connected constants for implicit/contextual inputs (Set Position, Mesh to Points, Noise and contextual group interfaces), native behavior of omitted inputs, runtime value identity and named Vector sharing. +- Preserved Float32/Int32 types, Bool comparisons, Color/Rotation input semantics, typed Bundle item ordering, and physical ownership across grouped calls, extensions and control flow. +- Preserved raw-node schema-v2 input realization modes and dynamic Bundle defaults across Compile, Update, Reload and transactional rollback. +- Enabled known inline String constants to populate literal-only Menu inputs through aliases, nested calls and multiple consumers, while rejecting runtime String connections and invalid Menu values. +- Retained one shared physical producer for multi-consumer non-String inline operands (including Bool Compare, points() count and cube() scale) and shared String producers for runtime-capable consumers. +- Consolidated duplicated scale/Euler conversion logic in geometry builtins and removed the unused legacy inline constant materializer. +- Added Blender 5.2 characterization, regression and package integration tests covering constant topology, native evaluation, type validation, inline sharing and graph updates. From 61bd096df7d9f6cfd29d6ed3798375b9590ba3f4 Mon Sep 17 00:00:00 2001 From: denikryt Date: Mon, 23 Nov 2026 03:26:53 +0200 Subject: [PATCH 14/14] docs updated --- docs/BUILTINS.md | 28 ++++++++++++++++++++++++++-- docs/WRITING_FUNCTIONS.md | 4 +++- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/docs/BUILTINS.md b/docs/BUILTINS.md index 63e434e..65d94b5 100644 --- a/docs/BUILTINS.md +++ b/docs/BUILTINS.md @@ -785,7 +785,7 @@ Creates a Blender node directly. Use this for Blender node types that are not ex `bl_idname`, node properties, socket selectors, output aliases, and type tokens are compile-time declarations. Runtime values are allowed inside `inputs={...}` and are linked to the selected Blender input sockets. `props=` is applied before socket selectors are resolved, so selectors see the node configuration produced by those properties. Reusing a [base-tree Group Input](#base-tree-group-input) checks its existing properties instead. -Supported type tokens are `Float`, `Int`, `Bool`, `Vector`, `Color`, `Geometry`, `Material`, `Object`, `String`, and `Bundle`. A `Color`-typed result maps exactly to Blender `NodeSocketColor`; `typ=Color` is a strict output type assertion. Color input sockets accept four-component RGBA tuple literals as defaults. +Supported type tokens are `Float`, `Int`, `Bool`, `Vector`, `Color`, `Rotation`, `Geometry`, `Material`, `Object`, `String`, and `Bundle`. A `Color`-typed result maps exactly to Blender `NodeSocketColor`; `typ=Color` is a strict output type assertion. Color input sockets accept four-component RGBA tuple literals as defaults. ```python def split_color(factor: Float) -> Float: @@ -799,13 +799,37 @@ These strict `typ=` declarations are distinct from the explicit Capture/Store `t | --- | --- | --- | --- | | `bl_idname` | compile-time `String` | required | Blender node type identifier, for example `"ShaderNodeMath"`. | | `props` | literal dict | `{}` | Blender node properties assigned before socket resolution. Custom properties are not supported. | -| `inputs` | literal dict | `{}` | Maps input socket selectors to literal defaults, runtime values, or a literal list for multi-input fanout. | +| `inputs` | literal dict | `{}` | Maps input socket selectors to literal values, runtime values, or a literal list for multi-input fanout. See [Input values](#input-values). | | `output` | socket selector | required in single-output mode | Output socket returned by the call. | | `typ` | type token | required in single-output mode | NodeForge type of `output`. | | `outputs` | literal dict | required in multi-output mode | Maps NodeForge result aliases to type tokens or explicit `(selector, TypeToken)` pairs. | Returns: one runtime value in single-output mode; a named multi-output result in `outputs=` mode. +### Input values + +Constants can be stored directly on input sockets, as with **Size** below: + +```python +shape = node("GeometryNodeMeshCube", inputs={"Size": (2.0, 1.0, 1.5)}, + output="Mesh", typ=Geometry) +``` + +NodeForge creates a constant node when a link is needed, for example on Set Position's **Position** input. Omit an `inputs` entry to keep Blender's native unconnected behavior. Named `vector(...)` results keep their shared output. + +### Menu inputs + +Menu inputs accept valid, nonempty String enum names, including constants passed through inline `.nf` calls. Runtime String sockets are unsupported. + +```python +def resample(geometry: Geometry, mode: String = "Count", __inline__=True) -> Geometry: + return node("GeometryNodeResampleCurve", + inputs={"Curve": geometry, ID("Mode"): mode}, + output="Curve", typ=Geometry) + +result = resample(line((0, 0, 0), (1, 0, 0)), mode="Length") +``` + ### Socket selectors A raw-node socket selector has one of three forms: diff --git a/docs/WRITING_FUNCTIONS.md b/docs/WRITING_FUNCTIONS.md index 4339483..1dc2b29 100644 --- a/docs/WRITING_FUNCTIONS.md +++ b/docs/WRITING_FUNCTIONS.md @@ -59,7 +59,9 @@ DEFAULT_SIZE = 2.0 shape = make_cube() ``` -For a grouped call, omitting an optional argument leaves its socket unlinked, using the declared default. An inline call materializes the same default as a typed runtime value in the caller tree. Here, the unlinked `size` input defaults to `2.0`. Constants in the calling module do not replace defaults in an imported function. Defaults cannot refer to function parameters. +Grouped calls leave omitted optional inputs unlinked, using the declared default (`size = 2.0` above). Explicit constants can use Group Node input defaults. Inline calls may use [socket defaults or constant nodes](BUILTINS.md#input-values). These rules also apply to `.nf` functions imported from Local, Examples, and packages. + +Constants in the calling module do not replace defaults in an imported function. Defaults cannot refer to function parameters. Use `panel([geometry, offset], name="Transform", collapsed=True)` at the start of a function body to group its inputs in Blender's interface. Panels change socket layout while positional arguments continue to follow the function declaration. See [Interface Panels](BUILTINS.md#interface-panels).