@babylonjs-toolkit/agent 1.2.15 → 1.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +8 -2
  2. package/lib/diskinfo/cli.js +40 -6
  3. package/lib/diskinfo/report.js +28 -15
  4. package/package.json +1 -1
  5. package/skills/bt-blender/SKILL.md +386 -0
  6. package/skills/bt-blender/THIRD_PARTY_NOTICES.md +141 -0
  7. package/skills/bt-blender/references/art-style-and-genre.md +173 -0
  8. package/skills/bt-blender/references/characters-and-creatures.md +644 -0
  9. package/skills/bt-blender/references/environments.md +478 -0
  10. package/skills/bt-blender/references/game-engine-export.md +284 -0
  11. package/skills/bt-blender/references/geometry-nodes.md +447 -0
  12. package/skills/bt-blender/references/hard-surface.md +720 -0
  13. package/skills/bt-blender/references/procedural-generation.md +358 -0
  14. package/skills/bt-blender/references/rigging-and-animation.md +1080 -0
  15. package/skills/bt-blender/references/sculpting-and-retopology.md +544 -0
  16. package/skills/bt-blender/references/uv-and-pbr-materials.md +381 -0
  17. package/skills/bt-blender/references/vehicles.md +632 -0
  18. package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
  19. package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
  20. package/skills/bt-blender/scripts/blender/construction_kit.py +1710 -0
  21. package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
  22. package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
  23. package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
  24. package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
  25. package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
  26. package/skills/bt-blender/scripts/blender/image_measure.py +568 -0
  27. package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
  28. package/skills/bt-blender/scripts/blender/measure_stations.py +486 -0
  29. package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
  30. package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
  31. package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
  32. package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
  33. package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
  34. package/skills/bt-blender/scripts/blender/review_render.py +358 -0
  35. package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
  36. package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
  37. package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
  38. package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
  39. package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
  40. package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
  41. package/skills/bt-blender/scripts/blender/world_gate.py +219 -0
  42. package/skills/bt-blender/scripts/bt-blender.mjs +329 -0
  43. package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
  44. package/skills/bt-gauntlet/SKILL.md +6 -6
  45. package/skills/bt-gauntlet/references/critic-rubrics.md +71 -4
  46. package/skills/bt-gauntlet/references/spec-composition.md +13 -0
  47. package/skills/bt-gauntlet/references/unity-pipeline.md +18 -2
  48. package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
  49. package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
  50. package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
  51. package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
  52. package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
  53. package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
  54. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
  55. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
  56. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
  57. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
  58. package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
@@ -0,0 +1,190 @@
1
+ """
2
+ bt-blender style palette: the low-poly palette-atlas look (one small texture of flat colour cells, one
3
+ material, one draw per asset) and a value check for a palette, headless.
4
+
5
+ import style_palette as palette
6
+
7
+ image = palette.palette_image("Palette_Kit", colours, path="/absolute/path/palette.png")
8
+ material = palette.palette_material("Kit_Palette", image)
9
+ palette.paint_faces(obj, faces, colour_index=3)
10
+ palette.flat_shade(obj)
11
+ print(palette.value_report(colours))
12
+
13
+ Every asset of a style shares the same atlas layout, so swapping the image re-skins the whole kit, and
14
+ any number of assets draw with one material. Faces are mapped into a cell's middle half, so filtering and
15
+ mip-mapping never pull in a neighbouring colour.
16
+ """
17
+ import math
18
+
19
+ import bpy
20
+ import numpy as np
21
+
22
+ # Pixels per colour cell, and cells per atlas row (8 x 8 cells of 4 px = a 32 px atlas).
23
+ CELL_PIXELS = 4
24
+ ATLAS_COLUMNS = 8
25
+
26
+ # Share of a cell's width a painted face's UVs may use (centred), so bilinear filtering stays inside it.
27
+ CELL_USE = 0.5
28
+
29
+ # CIE L* constants (D65): the linear-light threshold and the cube-root branch.
30
+ LSTAR_EPSILON = 216.0 / 24389.0
31
+ LSTAR_KAPPA = 24389.0 / 27.0
32
+
33
+ # A face normal with a Z component above this is near vertical, so its UV frame uses X instead of Z.
34
+ NEAR_VERTICAL_Z = 0.9
35
+
36
+ # Smallest face extent the UV scaling divides by, so a degenerate face cannot divide by zero.
37
+ MINIMUM_EXTENT = 1e-9
38
+
39
+ # Rec. 709 luminance weights of linear red, green and blue.
40
+ LUMINANCE_WEIGHTS = (0.2126, 0.7152, 0.0722)
41
+
42
+
43
+ def _srgb_to_linear(channel: float) -> float:
44
+ """One sRGB channel (0..1) to linear light."""
45
+ return channel / 12.92 if channel <= 0.04045 else ((channel + 0.055) / 1.055) ** 2.4
46
+
47
+
48
+ def lightness(colour: tuple) -> float:
49
+ """
50
+ Perceived lightness L* (0 black .. 100 white) of an sRGB colour: the 'value' an artist means.
51
+
52
+ :param colour: (r, g, b) in sRGB 0..1.
53
+ :returns: L*.
54
+ """
55
+ luminance = sum(weight * _srgb_to_linear(channel) for weight, channel in zip(LUMINANCE_WEIGHTS, colour))
56
+ return 116.0 * luminance ** (1.0 / 3.0) - 16.0 if luminance > LSTAR_EPSILON else luminance * LSTAR_KAPPA
57
+
58
+
59
+ def value_report(colours: list, focal_indices=(), minimum_focal_contrast: float = 20.0) -> dict:
60
+ """
61
+ The value structure of a palette: lightness of every colour, the spread, and whether each focal colour
62
+ (gameplay pickups, the player, hazards) stands at least `minimum_focal_contrast` L* away from every
63
+ non-focal colour that covers large areas. A palette that only reads in colour fails the greyscale test.
64
+
65
+ :param colours: [(r, g, b)] sRGB 0..1.
66
+ :param focal_indices: Indices of the colours that must pop.
67
+ :param minimum_focal_contrast: Required L* distance of focal colours from the rest.
68
+ :returns: {"lightness", "spread", "focal": [{"index", "closest_other", "contrast", "ok"}], "pass"}.
69
+ """
70
+ values = [round(lightness(colour), 1) for colour in colours]
71
+ others = [value for index, value in enumerate(values) if index not in focal_indices]
72
+ focal = []
73
+ for index in focal_indices:
74
+ closest = min(others, key=lambda other: abs(other - values[index])) if others else values[index]
75
+ contrast = abs(closest - values[index])
76
+ focal.append({"index": index, "closest_other": closest, "contrast": round(contrast, 1), "ok": contrast >= minimum_focal_contrast})
77
+ return {"lightness": values, "spread": round(max(values) - min(values), 1), "focal": focal,
78
+ "pass": all(entry["ok"] for entry in focal)}
79
+
80
+
81
+ def palette_image(name: str, colours: list, path=None, cell_pixels: int = CELL_PIXELS,
82
+ columns: int = ATLAS_COLUMNS) -> bpy.types.Image:
83
+ """
84
+ A palette atlas: one flat cell per colour, row 0 at the bottom (UV V up). Save it as PNG and give the
85
+ engine texture point (nearest) filtering, or keep the cells at least 4 px so linear filtering of the
86
+ middle half never blends neighbours.
87
+
88
+ :param name: Image name.
89
+ :param colours: [(r, g, b)] sRGB 0..1; at most columns x columns.
90
+ :param path: Optional PNG path to save to.
91
+ :param cell_pixels: Pixels per cell side.
92
+ :param columns: Cells per row (the atlas is square).
93
+ :returns: The image.
94
+ :raises ValueError: when there are more colours than cells.
95
+ """
96
+ if len(colours) > columns * columns:
97
+ raise ValueError(f"{len(colours)} colours do not fit {columns} x {columns} cells")
98
+ size = columns * cell_pixels
99
+ pixels = np.ones((size, size, 4), dtype=np.float32)
100
+ for index, colour in enumerate(colours):
101
+ row, column = divmod(index, columns)
102
+ pixels[row * cell_pixels:(row + 1) * cell_pixels, column * cell_pixels:(column + 1) * cell_pixels, :3] = colour
103
+ image = bpy.data.images.new(name, size, size, alpha=False)
104
+ image.pixels.foreach_set(pixels.ravel())
105
+ if path:
106
+ image.filepath_raw = path
107
+ image.file_format = "PNG"
108
+ image.save()
109
+ return image
110
+
111
+
112
+ def palette_material(name: str, image: bpy.types.Image, roughness: float = 0.8) -> bpy.types.Material:
113
+ """
114
+ The one material every palette-painted asset shares: the atlas into Base Color with closest-pixel
115
+ interpolation, no metal, one roughness.
116
+
117
+ :param name: Material name.
118
+ :param image: The palette atlas.
119
+ :param roughness: Roughness for the whole style (stylised palettes usually read best matte, 0.6-0.9).
120
+ :returns: The material.
121
+ """
122
+ material = bpy.data.materials.new(name)
123
+ tree = material.node_tree
124
+ shader = next(node for node in tree.nodes if node.type == "BSDF_PRINCIPLED")
125
+ texture = tree.nodes.new("ShaderNodeTexImage")
126
+ texture.image, texture.interpolation = image, "Closest"
127
+ tree.links.new(texture.outputs["Color"], shader.inputs["Base Color"])
128
+ shader.inputs["Roughness"].default_value = roughness
129
+ shader.inputs["Metallic"].default_value = 0.0
130
+ return material
131
+
132
+
133
+ def paint_faces(obj: bpy.types.Object, face_indices, colour_index: int, columns: int = ATLAS_COLUMNS,
134
+ uv_name: str = "UVMap") -> None:
135
+ """
136
+ Paints faces one palette colour by mapping their UVs into the middle half of that colour's cell
137
+ (each face keeps its own shape, scaled down, so no UV face has zero area).
138
+
139
+ :param obj: Mesh object.
140
+ :param face_indices: Faces to paint (any iterable of indices).
141
+ :param colour_index: Palette cell.
142
+ :param columns: Cells per atlas row (must match palette_image).
143
+ :param uv_name: UV map, created if missing.
144
+ """
145
+ mesh = obj.data
146
+ layer = mesh.uv_layers.get(uv_name) or mesh.uv_layers.new(name=uv_name)
147
+ row, column = divmod(colour_index, columns)
148
+ cell = 1.0 / columns
149
+ centre = np.array([(column + 0.5) * cell, (row + 0.5) * cell])
150
+ for index in face_indices:
151
+ polygon = mesh.polygons[index]
152
+ normal = np.array(polygon.normal)
153
+ tangent = np.cross(normal, [0.0, 0.0, 1.0] if abs(normal[2]) < NEAR_VERTICAL_Z else [1.0, 0.0, 0.0])
154
+ tangent /= np.linalg.norm(tangent)
155
+ bitangent = np.cross(normal, tangent)
156
+ corners = np.array([[np.dot(mesh.vertices[mesh.loops[loop].vertex_index].co, axis) for axis in (tangent, bitangent)]
157
+ for loop in polygon.loop_indices])
158
+ corners -= corners.mean(axis=0)
159
+ reach = max(float(np.abs(corners).max()), MINIMUM_EXTENT)
160
+ for loop, corner in zip(polygon.loop_indices, corners):
161
+ layer.data[loop].uv = tuple(centre + corner / reach * cell * CELL_USE / 2.0)
162
+
163
+
164
+ def flat_shade(obj: bpy.types.Object) -> int:
165
+ """
166
+ The faceted low-poly look: every face flat-shaded. Each face then needs its own vertices on export
167
+ (a flat-shaded mesh ships about 3-4x the vertices of a smooth one), which is the price of the style.
168
+
169
+ :param obj: Mesh object.
170
+ :returns: Faces set flat.
171
+ """
172
+ mesh = obj.data
173
+ mesh.polygons.foreach_set("use_smooth", [False] * len(mesh.polygons))
174
+ mesh.update()
175
+ return len(mesh.polygons)
176
+
177
+
178
+ def silhouette_pixel_height(asset_height: float, distance: float, vertical_fov_degrees: float, screen_height: int) -> float:
179
+ """
180
+ How many pixels tall an asset is on screen: what review-render's --pixel-height should be. A feature
181
+ has to be about 10 px or more at this size to read; below that it belongs in the texture or nowhere.
182
+
183
+ :param asset_height: The asset's height in metres.
184
+ :param distance: Camera distance, metres.
185
+ :param vertical_fov_degrees: Camera vertical field of view.
186
+ :param screen_height: Screen height in pixels.
187
+ :returns: On-screen height in pixels.
188
+ """
189
+ visible_height = 2.0 * distance * math.tan(math.radians(vertical_fov_degrees) / 2.0)
190
+ return asset_height / visible_height * screen_height
@@ -0,0 +1,289 @@
1
+ """
2
+ Shared plumbing for the bt-blender tools: the command-line contract, scene loading, object selection and
3
+ image input / output.
4
+
5
+ Every tool follows one contract:
6
+ - it runs inside Blender: blender --background --factory-startup --python-exit-code 1 --python <tool>.py -- <options>
7
+ - it prints exactly one result line, RESULT_PREFIX followed by compact JSON;
8
+ - it exits 0 when it ran and its gate passed, 1 when its gate failed or it raised, 2 for bad options.
9
+ """
10
+ import argparse
11
+ import json
12
+ import os
13
+ import sys
14
+ import traceback
15
+
16
+ import bpy
17
+ import numpy as np
18
+
19
+ # Marks the single JSON result line on stdout; the launcher looks for it.
20
+ RESULT_PREFIX = "BT_BLENDER_RESULT "
21
+
22
+ # Exit codes shared by every tool.
23
+ EXIT_PASSED = 0
24
+ EXIT_FAILED = 1
25
+ EXIT_BAD_OPTIONS = 2
26
+
27
+ # Set this environment variable to print the Python traceback behind an error to stderr.
28
+ TRACEBACK_ENVIRONMENT_VARIABLE = "BT_BLENDER_TRACEBACK"
29
+
30
+ # Model formats a tool can load, by extension, with the import operator and its keyword arguments.
31
+ # FBX is imported with its leaf bones: ignore_leaf_bones drops the last bone of EVERY chain, real end bones
32
+ # (toes, hand slots) included, so it is used only when the file really carries "_end" leaf markers.
33
+ # glTF is imported without bone shapes: by default the importer adds a 2 m "Icosphere" display object (in a
34
+ # "glTF_not_exported" collection) to any file with a skin, which a tool would count as part of the asset
35
+ # (it made a 0.4 m rigged part re-import as 1.9 x 2.0 x 2.4 m on Blender 5.3.0).
36
+ GLTF_IMPORT_SETTINGS = {"disable_bone_shape": True}
37
+ IMPORTERS = {
38
+ ".glb": ("gltf", GLTF_IMPORT_SETTINGS),
39
+ ".gltf": ("gltf", GLTF_IMPORT_SETTINGS),
40
+ ".fbx": ("fbx", {}),
41
+ ".obj": ("obj", {}),
42
+ }
43
+
44
+ # Name suffix of the leaf bones an FBX exporter appends to every chain (Blender's add_leaf_bones).
45
+ LEAF_BONE_SUFFIX = "_end"
46
+
47
+ # Object types that render as geometry.
48
+ GEOMETRY_TYPES = {"MESH", "CURVE", "SURFACE", "FONT", "META"}
49
+
50
+ # Blender file formats by output image extension.
51
+ IMAGE_FORMATS = {".png": "PNG", ".jpg": "JPEG", ".jpeg": "JPEG", ".webp": "WEBP"}
52
+
53
+
54
+ class OptionsError(Exception):
55
+ """Raised for invalid command-line options, so the tool can report them as JSON instead of exiting."""
56
+
57
+
58
+ class ToolArgumentParser(argparse.ArgumentParser):
59
+ """An ArgumentParser that raises OptionsError instead of printing usage and exiting."""
60
+
61
+ def error(self, message):
62
+ """
63
+ Turns an argparse error into an exception the tool contract reports as JSON.
64
+
65
+ :param message: argparse's description of the problem.
66
+ :raises OptionsError: always.
67
+ """
68
+ raise OptionsError(message)
69
+
70
+
71
+ def script_arguments() -> list:
72
+ """
73
+ The arguments meant for the tool: everything after Blender's `--` separator.
74
+
75
+ :returns: The argument list (empty when there is no separator).
76
+ """
77
+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
78
+
79
+
80
+ def _json_default(value):
81
+ """Makes numpy scalars, arrays and tuples JSON-serialisable."""
82
+ if isinstance(value, np.generic):
83
+ return value.item()
84
+ if isinstance(value, np.ndarray):
85
+ return value.tolist()
86
+ if isinstance(value, (set, frozenset)):
87
+ return sorted(value)
88
+ return str(value)
89
+
90
+
91
+ def emit_result(result: dict) -> None:
92
+ """
93
+ Prints the single result line.
94
+
95
+ :param result: The tool's result; it must be JSON-serialisable (numpy values are converted).
96
+ """
97
+ print(RESULT_PREFIX + json.dumps(result, separators=(",", ":"), default=_json_default), flush=True)
98
+
99
+
100
+ def write_json(path: str, data: dict) -> str:
101
+ """
102
+ Writes a JSON evidence file, creating its folder.
103
+
104
+ :param path: Output path.
105
+ :param data: The data.
106
+ :returns: The absolute path written.
107
+ """
108
+ absolute = os.path.abspath(path)
109
+ os.makedirs(os.path.dirname(absolute), exist_ok=True)
110
+ with open(absolute, "w", encoding="utf-8") as handle:
111
+ json.dump(data, handle, indent=2, default=_json_default)
112
+ return absolute
113
+
114
+
115
+ def run_tool(tool_name: str, parser: argparse.ArgumentParser, run_function) -> None:
116
+ """
117
+ Parses the options, runs the tool, prints its result and exits with the contract's code.
118
+ A result whose "pass" is False exits 1; an exception is reported as {"ok": false, "error": ...}.
119
+
120
+ :param tool_name: Name reported in the result.
121
+ :param parser: The tool's ToolArgumentParser.
122
+ :param run_function: Callable taking the parsed options and returning the result dict.
123
+ """
124
+ try:
125
+ options = parser.parse_args(script_arguments())
126
+ except OptionsError as error:
127
+ emit_result({"ok": False, "tool": tool_name, "error": f"bad options: {error}", "usage": parser.format_usage().strip()})
128
+ sys.exit(EXIT_BAD_OPTIONS)
129
+ try:
130
+ result = run_function(options)
131
+ except OptionsError as error:
132
+ emit_result({"ok": False, "tool": tool_name, "error": f"bad options: {error}", "usage": parser.format_usage().strip()})
133
+ sys.exit(EXIT_BAD_OPTIONS)
134
+ except Exception as error: # the contract reports every failure as JSON
135
+ if os.environ.get(TRACEBACK_ENVIRONMENT_VARIABLE):
136
+ traceback.print_exc()
137
+ emit_result({"ok": False, "tool": tool_name, "error": f"{type(error).__name__}: {error}"})
138
+ sys.exit(EXIT_FAILED)
139
+ result = {"ok": True, "tool": tool_name, **result}
140
+ emit_result(result)
141
+ sys.exit(EXIT_PASSED if result.get("pass", True) else EXIT_FAILED)
142
+
143
+
144
+ def clear_scene() -> None:
145
+ """
146
+ Empties the scene. `--factory-startup` loads Blender's default Cube, Camera and Light, and a tool that
147
+ measured "every mesh" would measure that Cube too.
148
+ """
149
+ bpy.ops.wm.read_factory_settings(use_empty=True)
150
+
151
+
152
+ def load_model(path) -> None:
153
+ """
154
+ Opens a .blend, or imports a model into an empty scene. With no path the current scene is kept, which
155
+ is how a tool runs on a file opened on Blender's command line. An FBX keeps every bone; only when it
156
+ carries "_end" leaf markers is it re-imported with ignore_leaf_bones (guide 8.2a).
157
+
158
+ :param path: .blend, .glb, .gltf, .fbx or .obj path, or None.
159
+ :raises FileNotFoundError: when the file does not exist.
160
+ :raises ValueError: for an unsupported extension.
161
+ :raises RuntimeError: when the import operator does not finish.
162
+ """
163
+ if not path:
164
+ return
165
+ absolute = os.path.abspath(path)
166
+ if not os.path.isfile(absolute):
167
+ raise FileNotFoundError(f"model not found: {absolute}")
168
+ extension = os.path.splitext(absolute)[1].lower()
169
+ if extension == ".blend":
170
+ bpy.ops.wm.open_mainfile(filepath=absolute)
171
+ return
172
+ if extension not in IMPORTERS:
173
+ raise ValueError(f"unsupported model format '{extension}'; use .blend, {', '.join(IMPORTERS)}")
174
+ importer_name, keyword_arguments = IMPORTERS[extension]
175
+ _import(absolute, importer_name, keyword_arguments)
176
+ if importer_name == "fbx" and _has_leaf_markers():
177
+ _import(absolute, importer_name, dict(keyword_arguments, ignore_leaf_bones=True))
178
+
179
+
180
+ def _import(path: str, importer_name: str, keyword_arguments: dict) -> None:
181
+ """Imports one file into an emptied scene, raising when the operator does not finish."""
182
+ clear_scene()
183
+ if importer_name == "obj":
184
+ outcome = bpy.ops.wm.obj_import(filepath=path, **keyword_arguments)
185
+ else:
186
+ outcome = getattr(bpy.ops.import_scene, importer_name)(filepath=path, **keyword_arguments)
187
+ if "FINISHED" not in outcome:
188
+ raise RuntimeError(f"import of {path} did not finish: {outcome}")
189
+
190
+
191
+ def _has_leaf_markers() -> bool:
192
+ """True when an imported armature carries exporter-made leaf bones (names ending LEAF_BONE_SUFFIX)."""
193
+ return any(bone.name.endswith(LEAF_BONE_SUFFIX) for armature in bpy.data.armatures for bone in armature.bones)
194
+
195
+
196
+ def resolve_objects(names=None, types=("MESH",)) -> list:
197
+ """
198
+ The objects a tool works on: the named ones, or else every visible, renderable object of the given
199
+ types. Objects whose names start with "_" (cutters, helpers, cameras made by a tool) are skipped.
200
+
201
+ :param names: Object names, or None / empty for "all".
202
+ :param types: Accepted object types.
203
+ :returns: The objects.
204
+ :raises KeyError: when a named object is missing.
205
+ :raises ValueError: when nothing is left to work on.
206
+ """
207
+ if names:
208
+ missing = [name for name in names if name not in bpy.data.objects]
209
+ if missing:
210
+ raise KeyError(f"objects not found: {missing}")
211
+ objects = [bpy.data.objects[name] for name in names]
212
+ else:
213
+ objects = [candidate for candidate in bpy.context.scene.objects
214
+ if candidate.type in types and not candidate.name.startswith("_")
215
+ and candidate.visible_get() and not candidate.hide_render]
216
+ objects = [candidate for candidate in objects if candidate.type in types]
217
+ if not objects:
218
+ raise ValueError(f"no {'/'.join(types)} objects to work on")
219
+ return objects
220
+
221
+
222
+ def load_image(path: str) -> np.ndarray:
223
+ """
224
+ Loads an image as raw stored values (no colour management), row 0 at the top.
225
+
226
+ :param path: Any image format Blender reads.
227
+ :returns: float32 array (height, width, 4).
228
+ :raises FileNotFoundError: when the file does not exist.
229
+ :raises RuntimeError: when it is not a readable image.
230
+ """
231
+ absolute = os.path.abspath(path)
232
+ if not os.path.isfile(absolute):
233
+ raise FileNotFoundError(f"image not found: {absolute}")
234
+ try:
235
+ image = bpy.data.images.load(absolute, check_existing=False)
236
+ except RuntimeError as error:
237
+ raise RuntimeError(f"cannot read image '{absolute}': {error}") from error
238
+ image.colorspace_settings.name = "Non-Color"
239
+ width, height = image.size
240
+ pixels = np.empty(width * height * 4, dtype=np.float32)
241
+ image.pixels.foreach_get(pixels)
242
+ bpy.data.images.remove(image)
243
+ if width == 0 or height == 0:
244
+ raise RuntimeError(f"image '{absolute}' is empty")
245
+ return pixels.reshape(height, width, 4)[::-1].copy()
246
+
247
+
248
+ def save_image(path: str, pixels: np.ndarray) -> str:
249
+ """
250
+ Saves an RGB or RGBA float array (row 0 at the top, values 0..1) as an 8-bit image; values are written
251
+ as they are.
252
+
253
+ :param path: Output path; the extension picks the format (png, jpg, webp).
254
+ :param pixels: float array (height, width, 3 or 4).
255
+ :returns: The absolute path written.
256
+ :raises ValueError: for an unsupported extension.
257
+ """
258
+ absolute = os.path.abspath(path)
259
+ extension = os.path.splitext(absolute)[1].lower()
260
+ if extension not in IMAGE_FORMATS:
261
+ raise ValueError(f"unsupported image extension '{extension}'")
262
+ height, width = pixels.shape[:2]
263
+ rgba = np.ones((height, width, 4), dtype=np.float32)
264
+ channels = min(4, pixels.shape[2])
265
+ rgba[:, :, :channels] = np.clip(pixels[:, :, :channels], 0.0, 1.0)
266
+ image = bpy.data.images.new(os.path.basename(absolute), width, height, alpha=True)
267
+ image.colorspace_settings.name = "Non-Color"
268
+ image.pixels.foreach_set(rgba[::-1].ravel())
269
+ os.makedirs(os.path.dirname(absolute), exist_ok=True)
270
+ image.filepath_raw = absolute
271
+ image.file_format = IMAGE_FORMATS[extension]
272
+ image.save()
273
+ bpy.data.images.remove(image)
274
+ return absolute
275
+
276
+
277
+ def load_json(path: str) -> dict:
278
+ """
279
+ Reads a JSON spec file.
280
+
281
+ :param path: Path to the file.
282
+ :returns: The parsed object.
283
+ :raises FileNotFoundError: when the file does not exist.
284
+ """
285
+ absolute = os.path.abspath(path)
286
+ if not os.path.isfile(absolute):
287
+ raise FileNotFoundError(f"spec not found: {absolute}")
288
+ with open(absolute, "r", encoding="utf-8-sig") as handle:
289
+ return json.load(handle)