From d85380909d5777afc9070b70e12788089f75d9a6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 4 May 2026 13:43:19 +0100 Subject: [PATCH] Translate cartesian graphs and fork Geometry Script patch --- .gitignore | 1 + docs/research/geometry-script-fork-notes.md | 79 ++++++ docs/research/geonodes-translation-corpus.md | 18 +- docs/research/procedural-doctrine.md | 144 ++++++++++ .../shriinivas-cartesian-function-graphs.md | 172 ++++++++++++ .../shriinivas-cartesian-helper.md | 2 +- .../shriinivas_cartesian_helper.py | 187 +++++++++++-- notes/fresh-workspace-handoff.md | 23 +- ...d-tree-group-references-on-blender-4.patch | 48 ++++ state/evidence.jsonl | 2 + state/map.yaml | 8 +- tools/geometry_script_loader.py | 41 +++ tools/setup_geometry_script_clone.ps1 | 31 +++ tools/verify_cartesian_helper_behavior.py | 162 ----------- tools/verify_cartesian_translations.py | 256 ++++++++++++++++++ 15 files changed, 973 insertions(+), 201 deletions(-) create mode 100644 docs/research/geometry-script-fork-notes.md create mode 100644 docs/research/procedural-doctrine.md create mode 100644 docs/research/translations/shriinivas-cartesian-function-graphs.md create mode 100644 patches/geometry-script/0001-fix-nested-tree-group-references-on-blender-4.patch create mode 100644 tools/geometry_script_loader.py create mode 100644 tools/setup_geometry_script_clone.ps1 delete mode 100644 tools/verify_cartesian_helper_behavior.py create mode 100644 tools/verify_cartesian_translations.py diff --git a/.gitignore b/.gitignore index 14f836a..34af03b 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ __pycache__/ *.pyc .venv/ node_modules/ +external/ state/scratch-compaction-*.md experiments/renders/ experiments/blender-cache/ diff --git a/docs/research/geometry-script-fork-notes.md b/docs/research/geometry-script-fork-notes.md new file mode 100644 index 0000000..7eb444b --- /dev/null +++ b/docs/research/geometry-script-fork-notes.md @@ -0,0 +1,79 @@ +# Geometry Script Fork Notes + +VibeGeometry uses a repo-local Geometry Script clone at: + +```text +external/geometry-script +``` + +The clone currently tracks upstream: + +```text +https://github.com/carson-katri/geometry-script.git +``` + +Patch work belongs in this clone first, then in a fork branch/PR. Do not patch +the installed AppData add-on directly. That path is live installation state, not +source control, and it will quietly become a stupid little archaeological layer +if indulged. + +## Setup + +Run from the VibeGeometry repo root: + +```powershell +.\tools\setup_geometry_script_clone.ps1 +``` + +This clones upstream into `external/geometry-script`, creates or switches to the +patch branch, and applies the patch stored in: + +```text +patches/geometry-script/0001-fix-nested-tree-group-references-on-blender-4.patch +``` + +`external/` is intentionally ignored by the VibeGeometry repository. The clone +is source-controlled as its own repo, not smuggled into this repo as a pile of +vendor files. + +## Active Patch Branch + +Branch: + +```text +vibegeometry/blender-5-nested-tree-groups +``` + +Problem: + +- Geometry Script's `@tree` decorator returns a Python function intended to + create a nested node-group node when called inside another `@tree`. +- Under Blender 5.1, that returned function tries to call + `geometrynodegroup(...)`, but no such generated DSL symbol exists. +- Manually calling the generated `group(node_tree=...)` wrapper returned + `None` in the nested path, so callers could not access group outputs. + +Patch: + +- In Blender 4/5, create `GeometryNodeGroup` directly. +- Assign `result.node_tree = node_group`. +- Wire positional and keyword arguments into enabled group inputs with + Geometry Script's existing `set_or_create_link(...)` helper. +- Return `Type(...)` wrappers for each enabled group output. + +Verification: + +- `examples/geometry_script/shriinivas_cartesian_helper.py` loads + `external/geometry-script` through `tools/geometry_script_loader.py`. +- `VG Cartesian Circle` calls `vg_cartesian_helper(...)` twice inside its own + `@tree` body. +- Generated circle graph contains nested `GeometryNodeGroup` nodes. +- `tools/verify_cartesian_translations.py` verifies helper, line, parabola, and + circle behavior against the source `cartesian.blend` groups in Blender 5.1.1. + +## Fork/PR Todo + +- Add a remote for the maintained VibeGeometry fork once it exists. +- Push `vibegeometry/blender-5-nested-tree-groups` to that fork. +- Submit a focused upstream PR or keep the fork as the project toolchain if + upstream is inactive. diff --git a/docs/research/geonodes-translation-corpus.md b/docs/research/geonodes-translation-corpus.md index 3480de0..e8b4694 100644 --- a/docs/research/geonodes-translation-corpus.md +++ b/docs/research/geonodes-translation-corpus.md @@ -103,6 +103,17 @@ First completed translation entry: - Geometry Script recreation: `examples/geometry_script/shriinivas_cartesian_helper.py` +Completed Cartesian function graph entry: + +- `docs/research/translations/shriinivas-cartesian-function-graphs.md` +- Source groups: `Geometry Nodes Line`, `Geometry Nodes Parabola`, + `Geometry Nodes Circle` +- Verification: all translated graphs match evaluated source geometry in + Blender 5.1.1. Circle matches as a sorted vertex set because node expansion + changes vertex order while preserving shape. +- Toolchain note: `external/geometry-script` is patched so nested `@tree` calls + create `GeometryNodeGroup` nodes under Blender 5.1. + ## Extraction Workflow 1. Download one source `.blend` into an ignored experiment folder. @@ -124,9 +135,10 @@ First completed translation entry: opened `.blend` file into JSON. It records group interfaces, nodes, simple node properties, sockets, links, and modifier users. -`tools/verify_cartesian_helper_behavior.py` verifies the first translated helper -against its source group by wrapping both graphs in the same evaluator graph and -comparing evaluated mesh vertices. +`tools/verify_cartesian_translations.py` verifies the translated Cartesian +helper, line, parabola, and circle groups against their source groups by +wrapping each graph in the same evaluator graph and comparing evaluated mesh +vertices. Generated node groups must be referenced by an object/modifier or marked with `use_fake_user = True` before saving a `.blend`; otherwise Blender discards the diff --git a/docs/research/procedural-doctrine.md b/docs/research/procedural-doctrine.md new file mode 100644 index 0000000..f0226d1 --- /dev/null +++ b/docs/research/procedural-doctrine.md @@ -0,0 +1,144 @@ +# Procedural Geometry Doctrine + +This note distills what the translation corpus teaches about turning geometric +ideas into Geometry Script graphs. + +## Think In Pipelines + +Most useful procedural graphs are not magic knots. They are pipelines: + +```text +seed geometry -> sampled domain -> field math -> deformation -> realization +``` + +For the Cartesian examples: + +```text +line curve -> resampled curve points -> y=f(x) -> set position -> curve to mesh +``` + +The graph becomes legible when each stage has one job. If a stage cannot be +named in plain language, it is probably hiding either cleverness or confusion. +Both invoice later. + +## Curves Are Rails + +A curve is the rail the shape rides on. It can be a crude two-point line at +first. Detail comes later from resampling, profile thickness, and fields. + +Geometry Script calls: + +- `curve_line(...)` creates the rail. +- `resample_curve(count=...)` places regular stations along it. +- `curve_to_mesh(profile_curve=...)` gives it physical thickness. + +Use curves when the intended form is a path, stroke, vine, tube, branch, cable, +arc, contour, or function plot. + +## Fields Are Weather + +A field is not a stored list until Blender evaluates it. It is weather over the +geometry: every point can ask, "what is the value here?" + +In the Cartesian graphs: + +- `position()` asks each point where it currently is. +- `separate_xyz(position())` extracts the local X address. +- math nodes compute the new Y value at that address. +- `combine_xyz(...)` builds the target position field. + +Use fields when the graph should react to location, index, normal, random value, +attributes, or any other per-element condition. + +## Set Position Is The Hinge + +`Set Position` is where an invisible idea becomes shape. Before it, math is just +a promise. After it, the geometry has moved. + +The reliable pattern is: + +```text +source geometry ++ target position field +-> set_position(position=target) +``` + +For function curves, preserve X and Z from `Position`, then replace Y with the +formula output. This keeps the rail's sampling and bends only the dimension you +intend to control. + +## Profiles Make Curves Inspectable + +Curves can be visually thin or renderer-dependent. A circular profile turns a +curve into an inspectable mesh: + +```text +curve_circle(radius=thickness) -> curve_to_mesh(profile_curve=profile) +``` + +Think of `Curve to Mesh` as dragging a drill bit along a path. The path gives +direction; the profile gives body. + +## Attributes Are Optional Handles + +The Cartesian source graphs use: + +```text +named_attribute("radius").exists + ? named_attribute("radius").attribute + : 1.0 +``` + +This is a good control pattern. A graph can expose a broad global control like +`Thickness`, while also accepting a per-point or per-curve override when a +`radius` attribute exists. + +Use this when a graph should work plainly by default but become more expressive +when upstream geometry brings richer attributes. + +## Stack Abstractions Carefully + +There are two abstraction layers available: + +- Python authoring abstractions: helper functions that emit repeated node + patterns. +- Blender graph abstractions: reusable node groups nested inside other node + groups. + +The repo-local Geometry Script clone needed a Blender 5.1 patch before nested +`@tree` group references worked. After that patch, nested groups are the +preferred form for stable motifs with a named contract. Python helper functions +remain useful for tiny repeated node idioms or for sketching before a motif +deserves a public socket surface. + +Metaphor: a Python helper is a stencil. It draws the same shape again wherever +you place it. A node group is a machine part bolted into another machine. Both +are useful, but they fail differently. + +## Verify Shape, Not Just Vocabulary + +Matching node types is weak evidence. Matching evaluated output is strong +evidence. + +Use multiple checks: + +- Node vocabulary and link shape: catches obvious translation mistakes. +- Interface sockets: catches broken control contracts. +- Evaluated vertex comparison: catches semantic drift. +- Sorted vertex comparison: useful when generated geometry is identical but + join/order differs. +- Direct vertex comparison: needed when downstream topology order matters. + +The circle translation proves the distinction: the geometry matched exactly as +a set of vertices, but direct vertex order differed even after restoring nested +group reuse. Matching shape and matching topology order are related but not the +same promise. + +## Control Names Are Contracts + +Geometry Script may title-case parameter names. For user-facing groups, +post-generation cleanup can be needed to preserve source-compatible controls +such as `r`, `m`, `a`, `b`, and `c`. + +Do not treat socket names as cosmetic. They are the handles an agent or artist +will grab later. Bad handles make good machinery feel broken. diff --git a/docs/research/translations/shriinivas-cartesian-function-graphs.md b/docs/research/translations/shriinivas-cartesian-function-graphs.md new file mode 100644 index 0000000..dd38ae2 --- /dev/null +++ b/docs/research/translations/shriinivas-cartesian-function-graphs.md @@ -0,0 +1,172 @@ +# Translation: Shriinivas Cartesian Function Graphs + +## Source + +- Repository: https://github.com/Shriinivas/geometrynodes +- Source file: `cartesian.blend` +- Source groups: + - `Geometry Nodes Line` + - `Geometry Nodes Parabola` + - `Geometry Nodes Circle` +- Geometry Script recreation: + `examples/geometry_script/shriinivas_cartesian_helper.py` + +## Graph Family + +These groups are three versions of the same procedural sentence: + +```text +make a simple path +read each point's position +compute a new Y value from X +move the path into that shape +give the curve physical thickness +``` + +The source file uses this sentence to draw Cartesian function curves. The line +uses `y = m*x + value`. The parabola uses `y = a*x^2 + b*x + c`. The circle +uses the helper graph twice: + +```text +y = sqrt(r^2 - x^2) +y = -sqrt(r^2 - x^2) +``` + +then joins the upper and lower arcs before giving them thickness. + +## Translation Summary + +### Line + +Source group: `Geometry Nodes Line` + +Geometry Script group: `VG Cartesian Line` + +Mechanism: + +- Build a two-point `Curve Line` from origin to `(Length, 0, 0)`. +- Read the current field `Position`. +- Split position into X/Y/Z. +- Compute `y = m*x + Value`. +- Recombine `(x, y, z)`. +- Feed the vector into `Set Position`. +- Convert the resulting curve to mesh using a circular profile. + +Metaphor: the curve is a straight rail, and the position field is a set of +chalk marks along it. The math node chain tells each chalk mark how high to +stand. `Set Position` is the hand lifting those marks into place. + +### Parabola + +Source group: `Geometry Nodes Parabola` + +Geometry Script group: `VG Cartesian Parabola` + +Mechanism: + +- Build a line from `(Start, 0, 0)` to `(End, 0, 0)`. +- Resample it to `Sample Resolution` points. +- Read each point's X coordinate. +- Compute `y = a*x^2 + b*x + c`. +- Move the resampled curve with `Set Position`. +- Tube the curve with `Curve to Mesh`. + +Metaphor: resampling makes evenly spaced beads on a string. The parabola +formula is the jig that bends each bead upward or downward based on its X +address. + +The source group has two input sockets named `Resolution`; only the later one +drives `Resample Curve.Count`. The translation keeps the unused compatibility +input as `Resolution` and names the active control `Sample Resolution`. This is +one place where perfect socket-name mimicry would make the generated graph less +legible. + +### Circle + +Source group: `Geometry Nodes Circle` + +Geometry Script group: `VG Cartesian Circle` + +Mechanism: + +- Compute left and right X endpoints from `-r` and `r`. +- Build an upper arc with `sqrt(r^2 - x^2)`. +- Build a lower arc with the same helper and `Value = -1`. +- Move both arcs with `Set Position`. +- Join the two curves. +- Tube the joined curve with `Curve to Mesh`. + +Metaphor: the helper graph is a compass arm. Run it once above the axis and +once below the axis, then clamp the two strokes together into a full circle. + +The source graph reuses `NodeGroup.001` as nested group nodes. The installed +Geometry Script code initially failed in this path under Blender 5.1 because +its `@tree` returned function called a missing `geometrynodegroup(...)` symbol. +We patched the repo-local Geometry Script clone so nested `@tree` calls create +`GeometryNodeGroup` nodes directly, wire inputs, and expose typed outputs. + +The translation now calls `vg_cartesian_helper(...)` twice inside +`VG Cartesian Circle`, preserving the repeated motif as nested graph organs +instead of expanding it inline. + +## Control Surfaces + +These graphs expose the useful joints: + +- `Length`: extent of the line along X. +- `m`: line slope. +- `Value`: line Y offset, and helper polarity/amplitude. +- `Start` / `End`: sampled X range for the parabola. +- `a`, `b`, `c`: parabola coefficients. +- `r`: circle radius. +- `Thickness`: curve profile radius. +- `Sample Resolution`: number of samples before bending a curve. + +The important pattern is that controls should match geometric intent, not node +incidental detail. A user wants radius, slope, coefficient, and thickness; they +do not want to manage the third socket of a math node like a cursed vending +machine. + +## Verification + +Run: + +```powershell +& 'C:\Program Files (x86)\Steam\steamapps\common\Blender\blender.exe' --background '.\experiments\source-blends\shriinivas-cartesian.blend' --python '.\tools\verify_cartesian_translations.py' +``` + +Verification wraps each source and translated group in the same evaluator, +evaluates the resulting mesh, and compares vertices. + +Results from Blender 5.1.1: + +| Case | Vertices | Direct max delta | Sorted max delta | Status | +| --- | ---: | ---: | ---: | --- | +| Helper | 200 | 0.0 | 0.0 | accepted | +| Line | 64 | 0.0 | 0.0 | accepted | +| Parabola | 992 | 0.0 | 0.0 | accepted | +| Circle | 2368 | 1.2999999523162842 | 0.0 | accepted | + +Circle has identical geometry but different vertex order. For rendered geometry +and shape behavior, sorted vertex equality is the relevant check. For +simulations or downstream topology-sensitive processing, direct order would +matter and should be preserved deliberately. + +## Lessons + +- A field is weather over geometry: it has a value at every point, not one + value globally. `Position` is the weather station every point carries. +- `Set Position` is the hinge where an abstract formula becomes visible + geometry. +- `Curve to Mesh` is a lathe/extruder: it turns a weightless path into a tube by + dragging a profile along it. +- `Named Attribute` plus `Switch` is a graceful override hook: if a `radius` + attribute exists, use it; otherwise fall back to scale `1.0`. +- Nested Geometry Script `@tree` calls are now viable after the patch branch in + `external/geometry-script`. Use them when a repeated motif deserves to remain + a named, inspectable organ in the generated Blender graph. +- Python helper functions are still useful for repeated authoring idioms that do + not need to survive as named node groups. +- Socket names are part of the control contract. Geometry Script title-cases + one-letter parameter names, so finalization currently renames `R`, `M`, `A`, + `B`, and `C` back to `r`, `m`, `a`, `b`, and `c`. diff --git a/docs/research/translations/shriinivas-cartesian-helper.md b/docs/research/translations/shriinivas-cartesian-helper.md index a33c38c..46b563c 100644 --- a/docs/research/translations/shriinivas-cartesian-helper.md +++ b/docs/research/translations/shriinivas-cartesian-helper.md @@ -126,7 +126,7 @@ the source mechanism. Behavior verification: ```powershell -& 'C:\Program Files (x86)\Steam\steamapps\common\Blender\blender.exe' --background '.\experiments\source-blends\shriinivas-cartesian.blend' --python '.\tools\verify_cartesian_helper_behavior.py' +& 'C:\Program Files (x86)\Steam\steamapps\common\Blender\blender.exe' --background '.\experiments\source-blends\shriinivas-cartesian.blend' --python '.\tools\verify_cartesian_translations.py' ``` The verification harness wraps both the source helper and the Geometry Script diff --git a/examples/geometry_script/shriinivas_cartesian_helper.py b/examples/geometry_script/shriinivas_cartesian_helper.py index e7dd957..026ac6d 100644 --- a/examples/geometry_script/shriinivas_cartesian_helper.py +++ b/examples/geometry_script/shriinivas_cartesian_helper.py @@ -3,26 +3,28 @@ Source: https://github.com/Shriinivas/geometrynodes/blob/main/cartesian.blend -The source group is named ``NodeGroup.001``. It creates a resampled curve line -and a vector field where Y is lifted by ``sqrt(r^2 - x^2) * value`` while X and -Z are preserved from the current position. +The first source group is named ``NodeGroup.001``. It creates a resampled curve +line and a vector field where Y is lifted by ``sqrt(r^2 - x^2) * value`` while +X and Z are preserved from the current position. The other groups in this file +translate the scene-facing line, parabola, and circle node groups from the same +source file. """ -import addon_utils +try: + from tools.geometry_script_loader import load_repo_geometry_script +except ModuleNotFoundError: + import sys + from pathlib import Path -addon_utils.enable("geometry-script-main", default_set=False, persistent=False) + sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + from tools.geometry_script_loader import load_repo_geometry_script + +load_repo_geometry_script() from geometry_script import * # noqa: F403 - Geometry Script exposes node functions as DSL globals. -@tree("VG Cartesian Helper") -def vg_cartesian_helper( - count: Int = 10, - start: Vector = (0.0, 0.0, 0.0), - end: Vector = (0.0, 0.0, 1.0), - r: Float = 1.0, - value: Float = 1.0, -): +def _cartesian_helper_nodes(count: Int, start: Vector, end: Vector, r: Float, value: Float): curve = curve_line(mode=CurveLine.Mode.POINTS, start=start, end=end) sampled_curve = curve.resample_curve(count=count) @@ -41,32 +43,157 @@ def vg_cartesian_helper( ) vector = combine_xyz(x=position_parts.x, y=y, z=position_parts.z) + return sampled_curve, vector + + +@tree("VG Cartesian Helper") +def vg_cartesian_helper( + count: Int = 10, + start: Vector = (0.0, 0.0, 0.0), + end: Vector = (0.0, 0.0, 1.0), + r: Float = 1.0, + value: Float = 1.0, +): + sampled_curve, vector = _cartesian_helper_nodes(count=count, start=start, end=end, r=r, value=value) return {"Curve": sampled_curve, "Vector": vector} +def _radius_scale(): + radius = named_attribute(data_type=NamedAttribute.DataType.FLOAT, name="radius") + return switch( + input_type=Switch.InputType.FLOAT, + switch=radius.exists, + false=1.0, + true=radius.attribute, + ) + + +def _tube_curve(curve: Geometry, thickness: Float): + profile = curve_circle(mode=CurveCircle.Mode.RADIUS, resolution=32, radius=thickness) + return curve.curve_to_mesh(profile_curve=profile, scale=_radius_scale()) + + +@tree("VG Cartesian Line") +def vg_cartesian_line( + geometry: Geometry, + resolution: Int = 10, + length: Float = 0.5, + m: Float = 0.5, + value: Float = 0.5, + thickness: Float = 1.0, +): + del geometry, resolution + + end = combine_xyz(x=length, y=0.0, z=0.0) + curve = curve_line(mode=CurveLine.Mode.POINTS, start=(0.0, 0.0, 0.0), end=end) + parts = separate_xyz(vector=position()) + y = math( + operation=Math.Operation.ADD, + value=(math(operation=Math.Operation.MULTIPLY, value=(parts.x, m)), value), + ) + vector = combine_xyz(x=parts.x, y=y, z=parts.z) + positioned = curve.set_position(position=vector) + return _tube_curve(positioned, thickness) + + +@tree("VG Cartesian Parabola") +def vg_cartesian_parabola( + geometry: Geometry, + resolution: Int = 10, + sample_resolution: Int = 100, + start: Float = 0.0, + end: Float = 0.0, + a: Float = 2.0, + b: Float = 2.0, + c: Float = 0.5, + thickness: Float = 1.0, +): + del geometry, resolution + + curve_start = combine_xyz(x=start, y=0.0, z=0.0) + curve_end = combine_xyz(x=end, y=0.0, z=0.0) + curve = curve_line(mode=CurveLine.Mode.POINTS, start=curve_start, end=curve_end) + sampled = curve.resample_curve(count=sample_resolution) + + parts = separate_xyz(vector=position()) + x_squared = math(operation=Math.Operation.POWER, value=(parts.x, 2.0)) + ax_squared = math(operation=Math.Operation.MULTIPLY, value=(x_squared, a)) + bx = math(operation=Math.Operation.MULTIPLY, value=(parts.x, b)) + y = math( + operation=Math.Operation.ADD, + value=(math(operation=Math.Operation.ADD, value=(ax_squared, bx)), c), + ) + vector = combine_xyz(x=parts.x, y=y, z=parts.z) + positioned = sampled.set_position(position=vector) + return _tube_curve(positioned, thickness) + + +@tree("VG Cartesian Circle") +def vg_cartesian_circle( + geometry: Geometry, + resolution: Int = 10, + r: Float = 0.5, + thickness: Float = 1.0, +): + del geometry + + left = combine_xyz(x=math(operation=Math.Operation.MULTIPLY, value=(r, -1.0)), y=0.0, z=0.0) + right = combine_xyz(x=r, y=0.0, z=0.0) + upper_curve, upper_vector = vg_cartesian_helper( + count=resolution, + start=left, + end=right, + r=r, + value=1.0, + ) + lower_curve, lower_vector = vg_cartesian_helper( + count=resolution, + start=left, + end=right, + r=r, + value=-1.0, + ) + + upper = upper_curve.set_position(position=upper_vector) + lower = lower_curve.set_position(position=lower_vector) + return _tube_curve(join_geometry(geometry=[upper, lower]), thickness) + + def _finalize_group(): import bpy - group = bpy.data.node_groups.get("VG Cartesian Helper") - if not group: - return None - group.use_fake_user = True - if hasattr(group, "interface"): - for item in group.interface.items_tree: - if item.item_type == "SOCKET" and item.in_out == "INPUT" and item.name == "R": - item.name = "r" - return group + groups = [] + for name in ("VG Cartesian Helper", "VG Cartesian Line", "VG Cartesian Parabola", "VG Cartesian Circle"): + group = bpy.data.node_groups.get(name) + if not group: + continue + group.use_fake_user = True + if hasattr(group, "interface"): + for item in group.interface.items_tree: + if item.item_type == "SOCKET" and item.in_out == "INPUT" and item.name == "R": + item.name = "r" + if item.item_type == "SOCKET" and item.in_out == "INPUT" and item.name in {"M", "A", "B", "C"}: + item.name = item.name.lower() + if ( + item.item_type == "SOCKET" + and item.in_out == "OUTPUT" + and item.name == "Result" + and name != "VG Cartesian Helper" + ): + item.name = "Geometry" + groups.append(group) + return groups _finalize_group() if __name__ == "__main__": - group = _finalize_group() - print( - "VG_CARTESIAN_HELPER", - bool(group), - len(group.nodes) if group else -1, - len(group.links) if group else -1, - sorted(node.bl_idname for node in group.nodes) if group else [], - ) + for group in _finalize_group(): + print( + "VG_CARTESIAN_GROUP", + group.name, + len(group.nodes), + len(group.links), + sorted(set(node.bl_idname for node in group.nodes)), + ) diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 9a3d9df..3fc9a95 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -30,9 +30,24 @@ The first completed translation is `docs/research/translations/shriinivas-cartesian-helper.md`, backed by `examples/geometry_script/shriinivas_cartesian_helper.py`. -The current next action is to translate the source `Geometry Nodes Line` group -from `cartesian.blend` using the completed helper as the first reusable -subgraph, then render or visually inspect the generated line output. +The completed Cartesian function translation is +`docs/research/translations/shriinivas-cartesian-function-graphs.md`. It covers +`Geometry Nodes Line`, `Geometry Nodes Parabola`, and `Geometry Nodes Circle` +from `cartesian.blend`. + +`docs/research/procedural-doctrine.md` now stores the current intuitive model +for mapping geometric ideas to Geometry Script: curves as rails, fields as +weather, `Set Position` as the hinge, profiles as body, attributes as optional +handles, and Python helpers as authoring stencils. + +The repo-local Geometry Script clone has a Blender 5.1 patch for nested `@tree` +group reuse. See `docs/research/geometry-script-fork-notes.md`. +Run `.\tools\setup_geometry_script_clone.ps1` if `external/geometry-script` is +missing in a fresh workspace. + +The current next action is to select the next Tier 1 source graph from +`Shriinivas/geometrynodes`, preferably `piechart.blend` or `fieldvalue.blend`, +inspect its node groups, and add the next doctrine-backed translation entry. ## Important Invariants @@ -54,6 +69,8 @@ subgraph, then render or visually inspect the generated line output. - What should the first node graph manifest schema require versus merely allow? - What node-group inspection JSON shape is most useful for translating public `.blend` examples into Geometry Script? +- Should the Geometry Script nested-group patch be upstreamed, or should + VibeGeometry maintain a fork as its toolchain? - Which Blender 5.0+ APIs and node construction helpers should become the first stable builder layer? - What is the smallest useful render-review artifact? diff --git a/patches/geometry-script/0001-fix-nested-tree-group-references-on-blender-4.patch b/patches/geometry-script/0001-fix-nested-tree-group-references-on-blender-4.patch new file mode 100644 index 0000000..76ac4be --- /dev/null +++ b/patches/geometry-script/0001-fix-nested-tree-group-references-on-blender-4.patch @@ -0,0 +1,48 @@ +From 55085d0a4b7fed62fdbbb7a3375bf71d9874268f Mon Sep 17 00:00:00 2001 +From: Meta Vens +Date: Mon, 4 May 2026 13:41:12 +0100 +Subject: [PATCH] Fix nested tree group references on Blender 4+ + +--- + api/tree.py | 17 +++++++++++++---- + 1 file changed, 13 insertions(+), 4 deletions(-) + +diff --git a/api/tree.py b/api/tree.py +index d34dc81..b2250a9 100644 +--- a/api/tree.py ++++ b/api/tree.py +@@ -163,12 +163,21 @@ def tree(name): + # This lets @trees be used in other @trees via simple function calls. + def group_reference(*args, **kwargs): + if IS_BLENDER_4: +- result = geometrynodegroup(node_tree=node_group, *args, **kwargs) ++ result = State.current_node_tree.nodes.new('GeometryNodeGroup') ++ result.node_tree = node_group ++ enabled_inputs = [node_input for node_input in result.inputs if node_input.enabled] ++ for value, node_input in zip(args, enabled_inputs): ++ set_or_create_link(value, node_input) ++ for node_input in enabled_inputs[len(args):]: ++ argname = node_input.name.lower().replace(' ', '_') ++ if argname in kwargs: ++ set_or_create_link(kwargs[argname], node_input) + else: + result = group(node_tree=node_group, *args, **kwargs) + group_outputs = [] +- for group_output in result._socket.node.outputs: +- group_outputs.append(Type(group_output)) ++ for group_output in result.outputs: ++ if group_output.enabled: ++ group_outputs.append(Type(group_output)) + if len(group_outputs) == 1: + return group_outputs[0] + else: +@@ -178,4 +187,4 @@ def tree(name): + return build_tree + else: + tree_name = name.__name__ +- return build_tree(name) +\ No newline at end of file ++ return build_tree(name) +-- +2.53.0.windows.3 + diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 4447858..c3d675f 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -4,3 +4,5 @@ {"ts": "2026-05-04T12:11:47+00:00", "type": "research", "status": "accepted", "note": "Public Geometry Nodes learning material is mostly screenshots, videos, and downloadable .blend files. VibeGeometry should build durable Geometry Script knowledge by inspecting source .blend node groups, mapping one graph at a time in prose, then recreating and smoke-testing with local Geometry Script 5.1 signatures."} {"ts": "2026-05-04T12:21:06+00:00", "type": "implementation", "status": "accepted", "note": "Completed first Geometry Nodes translation corpus entry: inspected Shriinivas/cartesian.blend NodeGroup.001, mapped its curve/vector field flow, recreated it as examples/geometry_script/shriinivas_cartesian_helper.py, and smoke-tested generation/save/reinspection in Blender 5.1.1. Generated node groups need fake users or real users before saving."} {"ts": "2026-05-04T12:24:11+00:00", "type": "verification", "status": "accepted", "note": "Verified translated Shriinivas cartesian helper behavior against source NodeGroup.001 by wrapping both helpers as Curve+Vector -> Set Position -> Curve to Mesh and comparing evaluated mesh vertices. Test used Count=25, Start=(-0.45,0,0), End=(0.45,0,0), r=0.6, Value=1.25; source and translation both produced 200 vertices with max delta 0.0."} +{"ts": "2026-05-04T12:42:20+00:00", "type": "implementation", "status": "accepted", "note": "Translated and verified all four inspected Shriinivas/cartesian.blend graph groups: helper, line, parabola, and circle. Verification compares evaluated meshes in Blender 5.1.1; helper/line/parabola match direct vertex order with max delta 0.0, circle matches sorted vertex set with max sorted delta 0.0."} +{"ts": "2026-05-04T12:42:20+00:00", "type": "tooling", "status": "accepted", "note": "Reverted direct AppData Geometry Script surgery. Cloned upstream Geometry Script into ignored external/geometry-script, committed local branch vibegeometry/blender-5-nested-tree-groups with nested @tree group fix, stored patch under patches/geometry-script, and added setup_geometry_script_clone.ps1 plus loader so VibeGeometry uses the repo-local patched clone."} diff --git a/state/map.yaml b/state/map.yaml index b6104f1..085109a 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -60,10 +60,14 @@ current_artifacts: - notes/vibegeometry-current-system-map.md - notes/vibegeometry-implementation-plan.md - docs/architecture/pipeline-overview.md + - docs/research/procedural-doctrine.md + - docs/research/geometry-script-fork-notes.md tools: - tools/vibegeometry_state.py - tools/vibegeometry_prepare_compaction.py - tools/inspect_blend_node_groups.py + - tools/verify_cartesian_translations.py + - tools/geometry_script_loader.py pending_contracts: - schemas/scene-brief.schema.json - schemas/node-graph-manifest.schema.json @@ -78,5 +82,5 @@ data_flow: - If state grows faster than understanding, cut it back. current_status: - summary: VibeGeometry has an initial persistence scaffold plus the first Geometry Nodes translation corpus entry: a small helper group from Shriinivas/cartesian.blend recreated with Geometry Script and smoke-tested in Blender 5.1.1. - next_action: Translate the source `Geometry Nodes Line` group from `cartesian.blend` using the completed helper as the first reusable subgraph, then render or visually inspect the generated line output. + summary: VibeGeometry has an initial persistence scaffold plus verified Geometry Script translations for all four inspected Shriinivas/cartesian.blend groups: helper, line, parabola, and circle. + next_action: Select the next Tier 1 source graph from Shriinivas/geometrynodes, preferably `piechart.blend` or `fieldvalue.blend`, inspect its node groups, and add the next doctrine-backed translation entry. diff --git a/tools/geometry_script_loader.py b/tools/geometry_script_loader.py new file mode 100644 index 0000000..b7f3284 --- /dev/null +++ b/tools/geometry_script_loader.py @@ -0,0 +1,41 @@ +"""Load the repo-local Geometry Script clone for Blender scripts.""" + +from __future__ import annotations + +import importlib.util +import sys +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +GEOMETRY_SCRIPT_DIR = ROOT / "external" / "geometry-script" +GEOMETRY_SCRIPT_INIT = GEOMETRY_SCRIPT_DIR / "__init__.py" + + +def load_repo_geometry_script(): + """Import the repo-local Geometry Script clone as ``geometry_script``.""" + if not GEOMETRY_SCRIPT_INIT.exists(): + raise FileNotFoundError( + f"Geometry Script clone not found: {GEOMETRY_SCRIPT_INIT}. " + "Run tools/setup_geometry_script_clone.ps1 from the repo root." + ) + + existing = sys.modules.get("geometry_script") + if existing is not None and getattr(existing, "__file__", None) == str(GEOMETRY_SCRIPT_INIT): + return existing + + for name in list(sys.modules): + if name == "geometry_script" or name.startswith("geometry_script."): + del sys.modules[name] + + spec = importlib.util.spec_from_file_location( + "geometry_script", + GEOMETRY_SCRIPT_INIT, + submodule_search_locations=[str(GEOMETRY_SCRIPT_DIR)], + ) + if spec is None or spec.loader is None: + raise RuntimeError(f"Could not load Geometry Script from {GEOMETRY_SCRIPT_INIT}") + module = importlib.util.module_from_spec(spec) + sys.modules["geometry_script"] = module + spec.loader.exec_module(module) + return module diff --git a/tools/setup_geometry_script_clone.ps1 b/tools/setup_geometry_script_clone.ps1 new file mode 100644 index 0000000..6dad7f4 --- /dev/null +++ b/tools/setup_geometry_script_clone.ps1 @@ -0,0 +1,31 @@ +param( + [string]$RepoUrl = "https://github.com/carson-katri/geometry-script.git", + [string]$Branch = "vibegeometry/blender-5-nested-tree-groups" +) + +$ErrorActionPreference = "Stop" + +$root = Resolve-Path (Join-Path $PSScriptRoot "..") +$target = Join-Path $root "external\geometry-script" +$patch = Join-Path $root "patches\geometry-script\0001-fix-nested-tree-group-references-on-blender-4.patch" + +if (!(Test-Path $target)) { + New-Item -ItemType Directory -Force (Split-Path $target) | Out-Null + git clone $RepoUrl $target +} + +git -C $target fetch origin + +$branches = git -C $target branch --list $Branch +if ($branches) { + git -C $target switch $Branch +} else { + git -C $target switch -c $Branch origin/main +} + +$alreadyApplied = git -C $target log --oneline --grep "Fix nested tree group references on Blender 4+" -1 +if (!$alreadyApplied) { + git -C $target am $patch +} + +git -C $target status --short --branch diff --git a/tools/verify_cartesian_helper_behavior.py b/tools/verify_cartesian_helper_behavior.py deleted file mode 100644 index c3fbe4c..0000000 --- a/tools/verify_cartesian_helper_behavior.py +++ /dev/null @@ -1,162 +0,0 @@ -"""Compare source and Geometry Script cartesian helper behavior. - -Run with Blender from the repository root: - - blender --background experiments/source-blends/shriinivas-cartesian.blend --python tools/verify_cartesian_helper_behavior.py -""" - -from __future__ import annotations - -import importlib.util -import json -import math -import sys -from pathlib import Path - -import bpy - - -ROOT = Path(__file__).resolve().parents[1] -TRANSLATION = ROOT / "examples" / "geometry_script" / "shriinivas_cartesian_helper.py" - -TEST_INPUTS = { - "Count": 25, - "Start": (-0.45, 0.0, 0.0), - "End": (0.45, 0.0, 0.0), - "r": 0.6, - "Value": 1.25, -} - - -def _load_translation() -> None: - spec = importlib.util.spec_from_file_location("vg_cartesian_helper_translation", TRANSLATION) - if spec is None or spec.loader is None: - raise RuntimeError(f"Could not load translation script: {TRANSLATION}") - module = importlib.util.module_from_spec(spec) - sys.modules[spec.name] = module - spec.loader.exec_module(module) - - -def _new_geometry_group(name: str) -> bpy.types.GeometryNodeTree: - if name in bpy.data.node_groups: - bpy.data.node_groups.remove(bpy.data.node_groups[name]) - group = bpy.data.node_groups.new(name, "GeometryNodeTree") - group.is_modifier = True - group.interface.new_socket(name="Geometry", in_out="INPUT", socket_type="NodeSocketGeometry") - group.interface.new_socket(name="Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry") - return group - - -def _socket_by_name(sockets, name: str): - for socket in sockets: - if socket.name == name: - return socket - raise KeyError(name) - - -def _set_input_defaults(group_node, values: dict[str, object]) -> None: - for name, value in values.items(): - socket = _socket_by_name(group_node.inputs, name) - socket.default_value = value - - -def _build_wrapper(name: str, helper_group: bpy.types.GeometryNodeTree) -> bpy.types.GeometryNodeTree: - wrapper = _new_geometry_group(name) - nodes = wrapper.nodes - links = wrapper.links - - group_input = nodes.new("NodeGroupInput") - group_input.location = (-900, 0) - group_output = nodes.new("NodeGroupOutput") - group_output.location = (500, 0) - - helper = nodes.new("GeometryNodeGroup") - helper.node_tree = helper_group - helper.location = (-700, 0) - _set_input_defaults(helper, TEST_INPUTS) - - set_position = nodes.new("GeometryNodeSetPosition") - set_position.location = (-350, 0) - profile = nodes.new("GeometryNodeCurvePrimitiveCircle") - profile.location = (-350, -220) - _socket_by_name(profile.inputs, "Resolution").default_value = 8 - _socket_by_name(profile.inputs, "Radius").default_value = 0.01 - - curve_to_mesh = nodes.new("GeometryNodeCurveToMesh") - curve_to_mesh.location = (80, 0) - - links.new(_socket_by_name(helper.outputs, "Curve"), _socket_by_name(set_position.inputs, "Geometry")) - links.new(_socket_by_name(helper.outputs, "Vector"), _socket_by_name(set_position.inputs, "Position")) - links.new(_socket_by_name(set_position.outputs, "Geometry"), _socket_by_name(curve_to_mesh.inputs, "Curve")) - links.new(_socket_by_name(profile.outputs, "Curve"), _socket_by_name(curve_to_mesh.inputs, "Profile Curve")) - links.new(_socket_by_name(curve_to_mesh.outputs, "Mesh"), _socket_by_name(group_output.inputs, "Geometry")) - return wrapper - - -def _evaluated_vertices(group: bpy.types.GeometryNodeTree) -> list[tuple[float, float, float]]: - mesh = bpy.data.meshes.new(group.name + " Input Mesh") - obj = bpy.data.objects.new(group.name + " Object", mesh) - bpy.context.collection.objects.link(obj) - modifier = obj.modifiers.new(group.name + " Modifier", "NODES") - modifier.node_group = group - - depsgraph = bpy.context.evaluated_depsgraph_get() - evaluated = obj.evaluated_get(depsgraph) - evaluated_mesh = evaluated.to_mesh() - try: - return [tuple(vertex.co) for vertex in evaluated_mesh.vertices] - finally: - evaluated.to_mesh_clear() - - -def _bounds(vertices: list[tuple[float, float, float]]) -> dict[str, list[float]]: - return { - "min": [min(vertex[i] for vertex in vertices) for i in range(3)], - "max": [max(vertex[i] for vertex in vertices) for i in range(3)], - } - - -def _compare(source_vertices, translated_vertices) -> dict[str, object]: - if len(source_vertices) != len(translated_vertices): - return { - "ok": False, - "reason": "vertex_count_mismatch", - "source_vertex_count": len(source_vertices), - "translated_vertex_count": len(translated_vertices), - } - max_delta = 0.0 - total_delta = 0.0 - for source, translated in zip(source_vertices, translated_vertices): - delta = math.dist(source, translated) - max_delta = max(max_delta, delta) - total_delta += delta - return { - "ok": max_delta <= 1e-6, - "source_vertex_count": len(source_vertices), - "translated_vertex_count": len(translated_vertices), - "max_vertex_delta": max_delta, - "mean_vertex_delta": total_delta / len(source_vertices) if source_vertices else 0.0, - "source_bounds": _bounds(source_vertices), - "translated_bounds": _bounds(translated_vertices), - } - - -def main() -> int: - source_helper = bpy.data.node_groups.get("NodeGroup.001") - if source_helper is None: - raise RuntimeError("Source helper node group 'NodeGroup.001' was not found.") - - _load_translation() - translated_helper = bpy.data.node_groups.get("VG Cartesian Helper") - if translated_helper is None: - raise RuntimeError("Translated helper node group 'VG Cartesian Helper' was not found.") - - source_wrapper = _build_wrapper("VG Verify Source Cartesian Helper", source_helper) - translated_wrapper = _build_wrapper("VG Verify Translated Cartesian Helper", translated_helper) - result = _compare(_evaluated_vertices(source_wrapper), _evaluated_vertices(translated_wrapper)) - print("VG_CARTESIAN_HELPER_BEHAVIOR " + json.dumps(result, sort_keys=True)) - return 0 if result["ok"] else 1 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tools/verify_cartesian_translations.py b/tools/verify_cartesian_translations.py new file mode 100644 index 0000000..30986d4 --- /dev/null +++ b/tools/verify_cartesian_translations.py @@ -0,0 +1,256 @@ +"""Compare Shriinivas cartesian source graphs against Geometry Script translations. + +Run with Blender from the repository root: + + blender --background experiments/source-blends/shriinivas-cartesian.blend --python tools/verify_cartesian_translations.py +""" + +from __future__ import annotations + +import importlib.util +import json +import math +import sys +from pathlib import Path +from typing import Any + +import bpy + + +ROOT = Path(__file__).resolve().parents[1] +TRANSLATION = ROOT / "examples" / "geometry_script" / "shriinivas_cartesian_helper.py" + + +HELPER_INPUTS = { + "Count": 25, + "Start": (-0.45, 0.0, 0.0), + "End": (0.45, 0.0, 0.0), + "r": 0.6, + "Value": 1.25, +} + +GRAPH_CASES = [ + { + "case": "line", + "source": "Geometry Nodes Line", + "translated": "VG Cartesian Line", + "inputs": { + "Resolution": 17, + "Length": 1.15, + "m": -0.35, + "Value": 0.25, + "Thickness": 0.035, + }, + }, + { + "case": "parabola", + "source": "Geometry Nodes Parabola", + "translated": "VG Cartesian Parabola", + "inputs": { + "Resolution": 31, + "Sample Resolution": 31, + "Start": -0.7, + "End": 0.8, + "a": 0.55, + "b": -0.25, + "c": 0.1, + "Thickness": 0.025, + }, + }, + { + "case": "circle", + "source": "Geometry Nodes Circle", + "translated": "VG Cartesian Circle", + "inputs": { + "Resolution": 37, + "r": 0.65, + "Thickness": 0.02, + }, + }, +] + + +def _load_translation() -> None: + spec = importlib.util.spec_from_file_location("vg_cartesian_translation", TRANSLATION) + if spec is None or spec.loader is None: + raise RuntimeError(f"Could not load translation script: {TRANSLATION}") + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + + +def _new_geometry_group(name: str) -> bpy.types.GeometryNodeTree: + if name in bpy.data.node_groups: + bpy.data.node_groups.remove(bpy.data.node_groups[name]) + group = bpy.data.node_groups.new(name, "GeometryNodeTree") + group.is_modifier = True + group.interface.new_socket(name="Geometry", in_out="INPUT", socket_type="NodeSocketGeometry") + group.interface.new_socket(name="Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry") + return group + + +def _socket_by_name(sockets: Any, name: str): + for socket in sockets: + if socket.name == name: + return socket + raise KeyError(name) + + +def _set_inputs(group_node: bpy.types.GeometryNode, values: dict[str, object]) -> None: + for socket in group_node.inputs: + if socket.name not in values: + continue + value = values[socket.name] + if isinstance(value, list): + socket.default_value = value.pop(0) + else: + socket.default_value = value + + +def _build_helper_eval_wrapper(name: str, helper_group: bpy.types.GeometryNodeTree) -> bpy.types.GeometryNodeTree: + wrapper = _new_geometry_group(name) + nodes = wrapper.nodes + links = wrapper.links + + group_output = nodes.new("NodeGroupOutput") + helper = nodes.new("GeometryNodeGroup") + helper.node_tree = helper_group + _set_inputs(helper, HELPER_INPUTS) + + set_position = nodes.new("GeometryNodeSetPosition") + profile = nodes.new("GeometryNodeCurvePrimitiveCircle") + _socket_by_name(profile.inputs, "Resolution").default_value = 8 + _socket_by_name(profile.inputs, "Radius").default_value = 0.01 + curve_to_mesh = nodes.new("GeometryNodeCurveToMesh") + + links.new(_socket_by_name(helper.outputs, "Curve"), _socket_by_name(set_position.inputs, "Geometry")) + links.new(_socket_by_name(helper.outputs, "Vector"), _socket_by_name(set_position.inputs, "Position")) + links.new(_socket_by_name(set_position.outputs, "Geometry"), _socket_by_name(curve_to_mesh.inputs, "Curve")) + links.new(_socket_by_name(profile.outputs, "Curve"), _socket_by_name(curve_to_mesh.inputs, "Profile Curve")) + links.new(_socket_by_name(curve_to_mesh.outputs, "Mesh"), _socket_by_name(group_output.inputs, "Geometry")) + return wrapper + + +def _build_group_eval_wrapper( + name: str, + graph_group: bpy.types.GeometryNodeTree, + inputs: dict[str, object], +) -> bpy.types.GeometryNodeTree: + wrapper = _new_geometry_group(name) + nodes = wrapper.nodes + links = wrapper.links + + group_input = nodes.new("NodeGroupInput") + group_output = nodes.new("NodeGroupOutput") + graph = nodes.new("GeometryNodeGroup") + graph.node_tree = graph_group + _set_inputs(graph, inputs) + + if any(socket.name == "Geometry" for socket in graph.inputs): + links.new(_socket_by_name(group_input.outputs, "Geometry"), _socket_by_name(graph.inputs, "Geometry")) + links.new(_socket_by_name(graph.outputs, "Geometry"), _socket_by_name(group_output.inputs, "Geometry")) + return wrapper + + +def _evaluated_vertices(group: bpy.types.GeometryNodeTree) -> list[tuple[float, float, float]]: + mesh = bpy.data.meshes.new(group.name + " Input Mesh") + obj = bpy.data.objects.new(group.name + " Object", mesh) + bpy.context.collection.objects.link(obj) + modifier = obj.modifiers.new(group.name + " Modifier", "NODES") + modifier.node_group = group + + depsgraph = bpy.context.evaluated_depsgraph_get() + evaluated = obj.evaluated_get(depsgraph) + evaluated_mesh = evaluated.to_mesh() + try: + return [tuple(vertex.co) for vertex in evaluated_mesh.vertices] + finally: + evaluated.to_mesh_clear() + + +def _bounds(vertices: list[tuple[float, float, float]]) -> dict[str, list[float]]: + return { + "min": [min(vertex[i] for vertex in vertices) for i in range(3)], + "max": [max(vertex[i] for vertex in vertices) for i in range(3)], + } + + +def _compare(case: str, source_vertices, translated_vertices) -> dict[str, object]: + if len(source_vertices) != len(translated_vertices): + return { + "case": case, + "ok": False, + "reason": "vertex_count_mismatch", + "source_vertex_count": len(source_vertices), + "translated_vertex_count": len(translated_vertices), + "source_bounds": _bounds(source_vertices) if source_vertices else None, + "translated_bounds": _bounds(translated_vertices) if translated_vertices else None, + } + max_delta = 0.0 + total_delta = 0.0 + for source, translated in zip(source_vertices, translated_vertices): + delta = math.dist(source, translated) + max_delta = max(max_delta, delta) + total_delta += delta + sorted_source = sorted(source_vertices) + sorted_translated = sorted(translated_vertices) + max_sorted_delta = 0.0 + total_sorted_delta = 0.0 + for source, translated in zip(sorted_source, sorted_translated): + delta = math.dist(source, translated) + max_sorted_delta = max(max_sorted_delta, delta) + total_sorted_delta += delta + return { + "case": case, + "ok": max_delta <= 1e-6 or max_sorted_delta <= 1e-6, + "source_vertex_count": len(source_vertices), + "translated_vertex_count": len(translated_vertices), + "max_vertex_delta": max_delta, + "mean_vertex_delta": total_delta / len(source_vertices) if source_vertices else 0.0, + "max_sorted_vertex_delta": max_sorted_delta, + "mean_sorted_vertex_delta": total_sorted_delta / len(source_vertices) if source_vertices else 0.0, + "source_bounds": _bounds(source_vertices), + "translated_bounds": _bounds(translated_vertices), + } + + +def main() -> int: + _load_translation() + results = [] + + source_helper = bpy.data.node_groups.get("NodeGroup.001") + translated_helper = bpy.data.node_groups.get("VG Cartesian Helper") + if source_helper is None or translated_helper is None: + raise RuntimeError("Source or translated helper group was not found.") + results.append( + _compare( + "helper", + _evaluated_vertices(_build_helper_eval_wrapper("VG Verify Source Helper", source_helper)), + _evaluated_vertices(_build_helper_eval_wrapper("VG Verify Translated Helper", translated_helper)), + ) + ) + + for case in GRAPH_CASES: + source = bpy.data.node_groups.get(case["source"]) + translated = bpy.data.node_groups.get(case["translated"]) + if source is None or translated is None: + raise RuntimeError(f"Missing group for case {case['case']}: {case['source']} / {case['translated']}") + results.append( + _compare( + case["case"], + _evaluated_vertices( + _build_group_eval_wrapper("VG Verify Source " + case["case"], source, case["inputs"]) + ), + _evaluated_vertices( + _build_group_eval_wrapper("VG Verify Translated " + case["case"], translated, case["inputs"]) + ), + ) + ) + + ok = all(result["ok"] for result in results) + print("VG_CARTESIAN_TRANSLATION_BEHAVIOR " + json.dumps({"ok": ok, "results": results}, sort_keys=True)) + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main())