@babylonjs-toolkit/agent 1.2.16 → 1.2.21

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 (70) hide show
  1. package/README.md +3 -2
  2. package/package.json +1 -1
  3. package/skills/bt-blender/SKILL.md +448 -0
  4. package/skills/bt-blender/THIRD_PARTY_NOTICES.md +141 -0
  5. package/skills/bt-blender/references/art-style-and-genre.md +173 -0
  6. package/skills/bt-blender/references/characters-and-creatures.md +644 -0
  7. package/skills/bt-blender/references/environments.md +478 -0
  8. package/skills/bt-blender/references/game-engine-export.md +284 -0
  9. package/skills/bt-blender/references/geometry-nodes.md +447 -0
  10. package/skills/bt-blender/references/hard-surface.md +724 -0
  11. package/skills/bt-blender/references/procedural-generation.md +358 -0
  12. package/skills/bt-blender/references/rigging-and-animation.md +1080 -0
  13. package/skills/bt-blender/references/sculpting-and-retopology.md +544 -0
  14. package/skills/bt-blender/references/uv-and-pbr-materials.md +381 -0
  15. package/skills/bt-blender/references/vehicles.md +637 -0
  16. package/skills/bt-blender/scripts/blender/__pycache__/construction_kit.cpython-313.pyc +0 -0
  17. package/skills/bt-blender/scripts/blender/__pycache__/geometry_nodes_builders.cpython-313.pyc +0 -0
  18. package/skills/bt-blender/scripts/blender/__pycache__/image_measure.cpython-313.pyc +0 -0
  19. package/skills/bt-blender/scripts/blender/__pycache__/reference_traces.cpython-313.pyc +0 -0
  20. package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
  21. package/skills/bt-blender/scripts/blender/blueprint.py +293 -0
  22. package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
  23. package/skills/bt-blender/scripts/blender/construction_kit.py +1770 -0
  24. package/skills/bt-blender/scripts/blender/coverage_check.py +221 -0
  25. package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
  26. package/skills/bt-blender/scripts/blender/evidence_sheet.py +243 -0
  27. package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
  28. package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
  29. package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
  30. package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
  31. package/skills/bt-blender/scripts/blender/image_measure.py +917 -0
  32. package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
  33. package/skills/bt-blender/scripts/blender/measure_stations.py +496 -0
  34. package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
  35. package/skills/bt-blender/scripts/blender/overlay_sheet.py +238 -0
  36. package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
  37. package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
  38. package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
  39. package/skills/bt-blender/scripts/blender/reference_traces.py +344 -0
  40. package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
  41. package/skills/bt-blender/scripts/blender/review_render.py +358 -0
  42. package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
  43. package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
  44. package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
  45. package/skills/bt-blender/scripts/blender/trace.py +283 -0
  46. package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
  47. package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
  48. package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
  49. package/skills/bt-blender/scripts/blender/world_gate.py +231 -0
  50. package/skills/bt-blender/scripts/bt-blender.mjs +333 -0
  51. package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
  52. package/skills/bt-execute/SKILL.md +2 -1
  53. package/skills/bt-gauntlet/SKILL.md +30 -20
  54. package/skills/bt-gauntlet/references/critic-rubrics.md +106 -7
  55. package/skills/bt-gauntlet/references/loop-templates.md +23 -3
  56. package/skills/bt-gauntlet/references/spec-composition.md +20 -1
  57. package/skills/bt-gauntlet/references/target-images.md +27 -0
  58. package/skills/bt-gauntlet/references/unity-pipeline.md +41 -4
  59. package/skills/bt-gauntlet/references/workspace.md +90 -6
  60. package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
  61. package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
  62. package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
  63. package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
  64. package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
  65. package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
  66. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
  67. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
  68. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
  69. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
  70. package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
@@ -0,0 +1,309 @@
1
+ """
2
+ World-registered orthographic views for bt-blender: the named straight views, the pixel frame that ties a
3
+ reference image to world coordinates, and Workbench renders of the model through a camera that covers
4
+ exactly the reference image's world window. A model that is too short or sits off its axis therefore
5
+ renders too short or off axis; nothing is re-centred or re-scaled away.
6
+
7
+ Portions adapted from majidmanzarpour/blender-game-skills (mirrored as Godsified/blender-game-skills-for-claude,
8
+ skills/blender-image-to-3d/scripts/world_gate.py: the orthographic camera placed over the reference
9
+ matte's world window) -- Copyright (c) 2026 Majid Manzarpour, MIT License:
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+
29
+ View names follow Blender's numpad views, with the model facing -Y (the glTF / BabylonJS forward):
30
+ front looks along +Y, back along -Y, right along -X (camera on +X), left along +X, top straight down and
31
+ bottom straight up. Image right is forward x up; image up is the listed up axis.
32
+ """
33
+ import contextlib
34
+ import os
35
+ from dataclasses import dataclass
36
+
37
+ import bpy
38
+ import numpy as np
39
+ from mathutils import Matrix, Vector
40
+
41
+ import construction_kit
42
+ import tool_common
43
+
44
+ # Camera forward and image-up direction (Blender world axes) for every named straight view.
45
+ VIEW_AXES = {
46
+ "front": ((0.0, 1.0, 0.0), (0.0, 0.0, 1.0)),
47
+ "back": ((0.0, -1.0, 0.0), (0.0, 0.0, 1.0)),
48
+ "right": ((-1.0, 0.0, 0.0), (0.0, 0.0, 1.0)),
49
+ "left": ((1.0, 0.0, 0.0), (0.0, 0.0, 1.0)),
50
+ "top": ((0.0, 0.0, -1.0), (0.0, 1.0, 0.0)),
51
+ "bottom": ((0.0, 0.0, 1.0), (0.0, -1.0, 0.0)),
52
+ }
53
+
54
+ AXIS_NAMES = ("x", "y", "z")
55
+
56
+ # Silhouette renders are made this many times larger than the reference, then averaged down.
57
+ DEFAULT_SUPERSAMPLE = 2
58
+
59
+ # Extra room between the camera and the model, in metres, beyond the model's own radius.
60
+ CAMERA_CLEARANCE_METRES = 1.0
61
+
62
+ # Name of the temporary camera; the leading underscore keeps it out of every tool's object list.
63
+ CAMERA_NAME = "_bt_view_camera"
64
+
65
+ # Flat grey used for shaded (studio-lit) renders.
66
+ SHADED_COLOR = (0.8, 0.8, 0.8)
67
+
68
+ # Near clip distance of the registered orthographic camera, metres.
69
+ ORTHO_CLIP_START = 0.001
70
+
71
+
72
+ @dataclass
73
+ class ViewBasis:
74
+ """The three world directions of a straight view, as numpy unit vectors."""
75
+
76
+ forward: np.ndarray
77
+ right: np.ndarray
78
+ up: np.ndarray
79
+
80
+
81
+ @dataclass
82
+ class PixelFrame:
83
+ """
84
+ Ties an image to world space: its size, its scale and the pixel where the world origin projects.
85
+ origin_column / origin_row are continuous pixel coordinates (row 0 at the top).
86
+ """
87
+
88
+ width: int
89
+ height: int
90
+ pixels_per_metre: float
91
+ origin_column: float
92
+ origin_row: float
93
+
94
+
95
+ def view_basis(view: str) -> ViewBasis:
96
+ """
97
+ The camera directions of a named straight view.
98
+
99
+ :param view: front, back, right, left, top or bottom.
100
+ :returns: The view's basis.
101
+ :raises ValueError: for an unknown view name.
102
+ """
103
+ if view not in VIEW_AXES:
104
+ raise ValueError(f"unknown view '{view}'; use one of {sorted(VIEW_AXES)}")
105
+ forward, up = (np.array(direction, dtype=np.float64) for direction in VIEW_AXES[view])
106
+ return ViewBasis(forward=forward, right=np.cross(forward, up), up=up)
107
+
108
+
109
+ def axis_of(direction: np.ndarray) -> tuple:
110
+ """
111
+ Names the world axis a unit axis vector lies on.
112
+
113
+ :param direction: A unit vector along +/-X, Y or Z.
114
+ :returns: (axis name, sign), e.g. ("y", -1.0).
115
+ """
116
+ index = int(np.argmax(np.abs(direction)))
117
+ return AXIS_NAMES[index], float(np.sign(direction[index]))
118
+
119
+
120
+ def world_to_pixel(points: np.ndarray, basis: ViewBasis, frame: PixelFrame) -> np.ndarray:
121
+ """
122
+ Projects world points into a view's image.
123
+
124
+ :param points: (N, 3) world positions in metres.
125
+ :param basis: The view's basis.
126
+ :param frame: The image's pixel frame.
127
+ :returns: (N, 2) continuous (column, row) pixel coordinates.
128
+ """
129
+ columns = frame.origin_column + (points @ basis.right) * frame.pixels_per_metre
130
+ rows = frame.origin_row - (points @ basis.up) * frame.pixels_per_metre
131
+ return np.column_stack((columns, rows))
132
+
133
+
134
+ def coordinate_to_pixel(coordinate: float, image_axis: str, frame: PixelFrame, sign: float) -> float:
135
+ """
136
+ Converts a world coordinate along one of the view's image axes into a pixel column or row.
137
+
138
+ :param coordinate: World coordinate in metres.
139
+ :param image_axis: "right" (gives a column) or "up" (gives a row).
140
+ :param frame: The image's pixel frame.
141
+ :param sign: +1 when the world axis points along the image axis, -1 when against it.
142
+ :returns: The continuous pixel coordinate.
143
+ """
144
+ if image_axis == "right":
145
+ return frame.origin_column + sign * coordinate * frame.pixels_per_metre
146
+ return frame.origin_row - sign * coordinate * frame.pixels_per_metre
147
+
148
+
149
+ def pixel_to_coordinate(pixel: float, image_axis: str, frame: PixelFrame, sign: float) -> float:
150
+ """
151
+ Inverse of coordinate_to_pixel.
152
+
153
+ :param pixel: Continuous pixel column ("right") or row ("up").
154
+ :param image_axis: "right" or "up".
155
+ :param frame: The image's pixel frame.
156
+ :param sign: +1 when the world axis points along the image axis, -1 when against it.
157
+ :returns: The world coordinate in metres.
158
+ """
159
+ if image_axis == "right":
160
+ return sign * (pixel - frame.origin_column) / frame.pixels_per_metre
161
+ return sign * (frame.origin_row - pixel) / frame.pixels_per_metre
162
+
163
+
164
+ @contextlib.contextmanager
165
+ def render_only(objects: list):
166
+ """
167
+ Hides every other renderable object (and every light) for the duration of a render, then restores them.
168
+
169
+ :param objects: The objects to keep visible.
170
+ """
171
+ keep = {candidate.name for candidate in objects}
172
+ saved = {}
173
+ for candidate in bpy.context.scene.objects:
174
+ if candidate.type in tool_common.GEOMETRY_TYPES or candidate.type == "LIGHT":
175
+ saved[candidate.name] = candidate.hide_render
176
+ candidate.hide_render = candidate.name not in keep
177
+ try:
178
+ yield
179
+ finally:
180
+ for name, hidden in saved.items():
181
+ if name in bpy.data.objects:
182
+ bpy.data.objects[name].hide_render = hidden
183
+
184
+
185
+ def view_camera() -> bpy.types.Object:
186
+ """The tool's camera, created on first use and made the scene camera."""
187
+ camera = bpy.data.objects.get(CAMERA_NAME)
188
+ if camera is None:
189
+ camera = bpy.data.objects.new(CAMERA_NAME, bpy.data.cameras.new(CAMERA_NAME))
190
+ bpy.context.scene.collection.objects.link(camera)
191
+ bpy.context.scene.camera = camera
192
+ return camera
193
+
194
+
195
+ def place_camera(camera: bpy.types.Object, basis: ViewBasis, look_at: np.ndarray, distance: float) -> None:
196
+ """
197
+ Points a camera along a view's forward direction with the view's up as image up.
198
+
199
+ :param camera: The camera object.
200
+ :param basis: The view's basis.
201
+ :param look_at: World point at the centre of the image.
202
+ :param distance: Distance from that point back to the camera, in metres.
203
+ """
204
+ rotation = Matrix((tuple(basis.right), tuple(basis.up), tuple(-basis.forward))).transposed()
205
+ camera.matrix_world = Matrix.Translation(Vector(look_at - basis.forward * distance)) @ rotation.to_4x4()
206
+
207
+
208
+ def _configure_workbench(mode: str, width: int, height: int) -> None:
209
+ """Sets up a transparent Workbench render: flat black for silhouettes, studio grey for shaded."""
210
+ scene = bpy.context.scene
211
+ scene.render.engine = "BLENDER_WORKBENCH"
212
+ scene.render.film_transparent = True
213
+ scene.render.image_settings.file_format = "PNG"
214
+ scene.render.image_settings.color_mode = "RGBA"
215
+ scene.render.resolution_x, scene.render.resolution_y = width, height
216
+ scene.render.resolution_percentage = 100
217
+ scene.view_settings.view_transform = "Standard"
218
+ shading = scene.display.shading
219
+ shading.color_type = "SINGLE"
220
+ shading.show_cavity = False
221
+ shading.show_object_outline = False
222
+ if mode == "silhouette":
223
+ shading.light = "FLAT"
224
+ shading.single_color = (0.0, 0.0, 0.0)
225
+ shading.show_shadows = False
226
+ else:
227
+ shading.light = "STUDIO"
228
+ shading.single_color = SHADED_COLOR
229
+ shading.show_shadows = False
230
+ shading.show_specular_highlight = True
231
+
232
+
233
+ def render_view(objects: list, view: str, frame: PixelFrame, path: str, mode: str = "silhouette",
234
+ supersample: int = DEFAULT_SUPERSAMPLE) -> np.ndarray:
235
+ """
236
+ Renders objects through an orthographic camera that covers exactly the frame's world window.
237
+
238
+ :param objects: Objects to render (everything else is hidden).
239
+ :param view: Named straight view.
240
+ :param frame: The reference image's pixel frame; the render has the same size and registration.
241
+ :param path: Where the full-size render is written (PNG).
242
+ :param mode: "silhouette" (flat black, alpha is the mask) or "shaded" (studio-lit grey).
243
+ :param supersample: Render this many times larger, then average down to the frame size.
244
+ :returns: float32 RGBA (frame.height, frame.width, 4), row 0 at the top.
245
+ :raises RuntimeError: when the render does not finish.
246
+ """
247
+ basis = view_basis(view)
248
+ points = np.concatenate([construction_kit.world_vertices(candidate) for candidate in objects])
249
+ center = points.mean(axis=0)
250
+ radius = float(np.linalg.norm(points - center, axis=1).max())
251
+ image_center_column = frame.width / 2.0
252
+ image_center_row = frame.height / 2.0
253
+ look_at = (basis.right * (image_center_column - frame.origin_column) / frame.pixels_per_metre
254
+ + basis.up * (frame.origin_row - image_center_row) / frame.pixels_per_metre)
255
+ # Slide the look-at point along the view axis to the model, so the clip range brackets it.
256
+ look_at = look_at + basis.forward * float((center - look_at) @ basis.forward)
257
+ distance = radius + CAMERA_CLEARANCE_METRES
258
+ camera = view_camera()
259
+ place_camera(camera, basis, look_at, distance)
260
+ camera.data.type = "ORTHO"
261
+ camera.data.sensor_fit = "HORIZONTAL"
262
+ camera.data.ortho_scale = frame.width / frame.pixels_per_metre
263
+ camera.data.clip_start = ORTHO_CLIP_START
264
+ camera.data.clip_end = distance * 2.0 + radius
265
+ _configure_workbench(mode, frame.width * supersample, frame.height * supersample)
266
+ bpy.context.scene.render.filepath = os.path.abspath(path)
267
+ with render_only(objects):
268
+ outcome = bpy.ops.render.render(write_still=True)
269
+ if "FINISHED" not in outcome:
270
+ raise RuntimeError(f"render did not finish: {outcome}")
271
+ pixels = tool_common.load_image(path)
272
+ blocks = pixels.reshape(frame.height, supersample, frame.width, supersample, 4)
273
+ return blocks.mean(axis=(1, 3))
274
+
275
+
276
+ def silhouette_mask(objects: list, view: str, frame: PixelFrame, path: str,
277
+ supersample: int = DEFAULT_SUPERSAMPLE) -> np.ndarray:
278
+ """
279
+ The model's silhouette in a reference frame.
280
+
281
+ :param objects: Objects to render.
282
+ :param view: Named straight view.
283
+ :param frame: The reference image's pixel frame.
284
+ :param path: Where the render is written.
285
+ :param supersample: Supersampling factor.
286
+ :returns: Boolean (frame.height, frame.width), True where the model covers the pixel.
287
+ """
288
+ return render_view(objects, view, frame, path, "silhouette", supersample)[:, :, 3] > 0.5
289
+
290
+
291
+ def frame_from_spec(view_spec: dict, width: int, height: int) -> PixelFrame:
292
+ """
293
+ Builds a pixel frame from a view entry of a spec file.
294
+
295
+ :param view_spec: Needs "pixels_per_metre" and "origin_pixel": [column, row] (the pixel where the
296
+ world origin projects: the vertical axis column and the ground row for side views).
297
+ :param width: Image width in pixels.
298
+ :param height: Image height in pixels.
299
+ :returns: The frame.
300
+ :raises ValueError: when a field is missing or invalid.
301
+ """
302
+ if "pixels_per_metre" not in view_spec or "origin_pixel" not in view_spec:
303
+ raise ValueError(f"view '{view_spec.get('name', '?')}' needs pixels_per_metre and origin_pixel")
304
+ pixels_per_metre = float(view_spec["pixels_per_metre"])
305
+ if pixels_per_metre <= 0:
306
+ raise ValueError("pixels_per_metre must be positive")
307
+ origin_column, origin_row = (float(value) for value in view_spec["origin_pixel"])
308
+ return PixelFrame(width=width, height=height, pixels_per_metre=pixels_per_metre,
309
+ origin_column=origin_column, origin_row=origin_row)
@@ -0,0 +1,238 @@
1
+ """
2
+ overlay_sheet -- the whole-silhouette check: every view's reference and model outlines on ONE sheet.
3
+
4
+ For each view the reference subject and the model (or a capture of it) are separated from their own border
5
+ background colours, so a capture may sit on a different solid colour than the reference. Each tile shows
6
+ the dimmed reference with the reference outline (amber) and the model outline (cyan), reference-only
7
+ regions shaded red (missing from the model) and model-only regions shaded blue (extra), and boxes round the
8
+ largest of them. The numbers per view: IoU, reference-only % and model-only % (of the reference area), and
9
+ the largest missing and extra regions (bounding box, area %, centroid), so an unbuilt region (a whole flank,
10
+ a wing) shows as a big reference-only blob instead of hiding in a close-up crop. Judge the whole shape in
11
+ every view on this sheet before any detail work.
12
+
13
+ Two ways to give the views (both may be combined):
14
+ - image pairs from any locked camera, perspective included, same size and framing required:
15
+ overlay-sheet --pair front=refs/front.png,captures/front.png [--pair ...] [--crop front=x0,y0,x1,y1]
16
+ - the registered straight views of a stations spec, the model rendered through each (a view with "frame"
17
+ uses that capture):
18
+ overlay-sheet --spec refs/spec.json --model asset.blend
19
+ Then: --out sheet.png [--min-iou 0.9] [--background-tolerance 0.08] [--tile 480]. Writes the sheet and
20
+ <sheet>.json; exits 1 while any view's IoU is below --min-iou.
21
+ """
22
+ import os
23
+ import sys
24
+
25
+ sys.dont_write_bytecode = True
26
+ SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
27
+ if SCRIPT_DIRECTORY not in sys.path:
28
+ sys.path.insert(0, SCRIPT_DIRECTORY)
29
+
30
+ import numpy as np # noqa: E402
31
+
32
+ import evidence_sheet # noqa: E402
33
+ import image_measure # noqa: E402
34
+ import ortho_views # noqa: E402
35
+ import tool_common # noqa: E402
36
+
37
+ TOOL_NAME = "overlay-sheet"
38
+
39
+ DEFAULT_MINIMUM_IOU = 0.90
40
+ DEFAULT_TILE_PIXELS = 480
41
+
42
+ # Missing / extra regions smaller than this share of the reference area (percent) are not listed.
43
+ DEFAULT_MINIMUM_REGION_PERCENT = 0.5
44
+ MAXIMUM_LISTED_REGIONS = 5
45
+
46
+ # Drawing.
47
+ REFERENCE_OUTLINE_COLOR = (1.0, 0.78, 0.1)
48
+ MODEL_OUTLINE_COLOR = (0.1, 0.85, 1.0)
49
+ REFERENCE_ONLY_COLOR = (0.95, 0.2, 0.2)
50
+ MODEL_ONLY_COLOR = (0.25, 0.45, 1.0)
51
+ SHADE_STRENGTH = 0.6
52
+ # The reference outline is drawn wider and first, so where the outlines coincide both stay visible.
53
+ REFERENCE_OUTLINE_PIXELS = 4
54
+ MODEL_OUTLINE_PIXELS = 2
55
+ LEGEND = "AMBER REFERENCE CYAN MODEL RED MISSING (REFERENCE ONLY) BLUE EXTRA (MODEL ONLY)"
56
+
57
+
58
+ def build_parser() -> tool_common.ToolArgumentParser:
59
+ """The tool's command-line options."""
60
+ parser = tool_common.ToolArgumentParser(prog=TOOL_NAME, description=__doc__.strip().splitlines()[0])
61
+ parser.add_argument("--pair", action="append", default=[], metavar="NAME=REFERENCE,CAPTURE",
62
+ help="a reference image and a capture of the model from the same locked camera")
63
+ parser.add_argument("--crop", action="append", default=[], metavar="NAME=X0,Y0,X1,Y1",
64
+ help="crop box (pixels) for a named view; overrides the spec's")
65
+ parser.add_argument("--spec", help="stations spec JSON: render the model through every registered view")
66
+ parser.add_argument("--model", help="model for --spec (.blend .glb .gltf .fbx .obj); default the spec's")
67
+ parser.add_argument("--objects", nargs="*", help="objects to render (default the spec's, else every visible mesh)")
68
+ parser.add_argument("--out", required=True, help="sheet image to write (PNG); the JSON goes beside it")
69
+ parser.add_argument("--min-iou", type=float, default=DEFAULT_MINIMUM_IOU)
70
+ parser.add_argument("--background-tolerance", type=float, default=image_measure.DEFAULT_BACKGROUND_TOLERANCE)
71
+ parser.add_argument("--min-region-percent", type=float, default=DEFAULT_MINIMUM_REGION_PERCENT,
72
+ help="smallest missing / extra region listed, percent of the reference area")
73
+ parser.add_argument("--tile", type=int, default=DEFAULT_TILE_PIXELS, help="longest side of each tile, pixels")
74
+ parser.add_argument("--supersample", type=int, default=ortho_views.DEFAULT_SUPERSAMPLE)
75
+ return parser
76
+
77
+
78
+ def parse_crops(entries: list) -> dict:
79
+ """`name=x0,y0,x1,y1` entries as {name: [x0, y0, x1, y1]}."""
80
+ crops = {}
81
+ for entry in entries:
82
+ name, separator, box = entry.partition("=")
83
+ values = box.split(",")
84
+ if not separator or len(values) != 4:
85
+ raise tool_common.OptionsError(f"--crop '{entry}': use name=x0,y0,x1,y1")
86
+ crops[name] = [float(value) for value in values]
87
+ return crops
88
+
89
+
90
+ def subject(rgba: np.ndarray, tolerance: float, crop) -> np.ndarray:
91
+ """The subject mask of an image: border-colour background removed, then cropped."""
92
+ return image_measure.apply_crop(image_measure.subject_mask(rgba, tolerance), crop)
93
+
94
+
95
+ def _regions(mask: np.ndarray, reference_area: float, minimum_percent: float) -> list:
96
+ """The largest regions of a difference mask, as percentages of the reference area."""
97
+ minimum_pixels = max(1, int(np.ceil(minimum_percent / 100.0 * reference_area)))
98
+ listed = []
99
+ for region in image_measure.component_regions(mask, minimum_pixels)[:MAXIMUM_LISTED_REGIONS]:
100
+ listed.append({"bbox": region["bbox"], "centroid": region["centroid"], "area_px": region["area_px"],
101
+ "area_percent": round(100.0 * region["area_px"] / reference_area, 2)})
102
+ return listed
103
+
104
+
105
+ def compare(reference: np.ndarray, model: np.ndarray, minimum_region_percent: float) -> dict:
106
+ """
107
+ Compares two silhouettes of the same framing.
108
+
109
+ :param reference: Reference subject mask.
110
+ :param model: Model / capture subject mask.
111
+ :param minimum_region_percent: Smallest region listed, percent of the reference area.
112
+ :returns: {"iou", "reference_only_percent", "model_only_percent", "missing_regions", "extra_regions"}.
113
+ """
114
+ reference_area = float(reference.sum())
115
+ if reference_area == 0:
116
+ raise ValueError("the reference holds no subject")
117
+ missing, extra = reference & ~model, model & ~reference
118
+ return {"iou": round(float((reference & model).sum()) / float((reference | model).sum()), 4),
119
+ "reference_only_percent": round(100.0 * float(missing.sum()) / reference_area, 2),
120
+ "model_only_percent": round(100.0 * float(extra.sum()) / reference_area, 2),
121
+ "missing_regions": _regions(missing, reference_area, minimum_region_percent),
122
+ "extra_regions": _regions(extra, reference_area, minimum_region_percent)}
123
+
124
+
125
+ def draw_tile(reference_rgba: np.ndarray, reference: np.ndarray, model: np.ndarray, numbers: dict,
126
+ tile_pixels: int) -> np.ndarray:
127
+ """The view's evidence picture at tile size: shading, both outlines and boxes round the listed regions."""
128
+ height, width = reference.shape
129
+ scale = evidence_sheet.fit_scale(height, width, tile_pixels)
130
+ tile_height, tile_width = max(1, round(height * scale)), max(1, round(width * scale))
131
+ picture = evidence_sheet.dimmed(evidence_sheet.resize(reference_rgba, tile_height, tile_width))
132
+ small_reference = evidence_sheet.resize_mask(reference, tile_height, tile_width)
133
+ small_model = evidence_sheet.resize_mask(model, tile_height, tile_width)
134
+ evidence_sheet.tint(picture, small_reference & ~small_model, REFERENCE_ONLY_COLOR, SHADE_STRENGTH)
135
+ evidence_sheet.tint(picture, small_model & ~small_reference, MODEL_ONLY_COLOR, SHADE_STRENGTH)
136
+ evidence_sheet.draw_mask_outline(picture, small_reference, REFERENCE_OUTLINE_COLOR, REFERENCE_OUTLINE_PIXELS)
137
+ evidence_sheet.draw_mask_outline(picture, small_model, MODEL_OUTLINE_COLOR, MODEL_OUTLINE_PIXELS)
138
+ for key, color in (("missing_regions", REFERENCE_ONLY_COLOR), ("extra_regions", MODEL_ONLY_COLOR)):
139
+ for region in numbers[key]:
140
+ evidence_sheet.draw_box(picture, [value * scale for value in region["bbox"]], color, 1)
141
+ return picture
142
+
143
+
144
+ def tile_label(name: str, numbers: dict, passed: bool) -> list:
145
+ """The tile's label lines: name, numbers, verdict and the largest missing region."""
146
+ lines = [name, f"IOU {numbers['iou']:.3f} REF-ONLY {numbers['reference_only_percent']:.1f}% "
147
+ f"MODEL-ONLY {numbers['model_only_percent']:.1f}%", evidence_sheet.verdict(passed)]
148
+ if numbers["missing_regions"]:
149
+ largest = numbers["missing_regions"][0]
150
+ lines.append((f"LARGEST MISSING {largest['area_percent']:.1f}% AT {largest['bbox']}", REFERENCE_ONLY_COLOR))
151
+ return lines
152
+
153
+
154
+ def _pair_views(options, crops: dict) -> list:
155
+ """Views from --pair: (name, reference RGBA, reference mask, model mask, source paths)."""
156
+ views = []
157
+ for entry in options.pair:
158
+ name, separator, paths = entry.partition("=")
159
+ files = paths.split(",")
160
+ if not separator or len(files) != 2:
161
+ raise tool_common.OptionsError(f"--pair '{entry}': use name=reference.png,capture.png")
162
+ reference_rgba, capture_rgba = (tool_common.load_image(path) for path in files)
163
+ if reference_rgba.shape[:2] != capture_rgba.shape[:2]:
164
+ raise ValueError(f"pair '{name}': the capture is {capture_rgba.shape[1]}x{capture_rgba.shape[0]}, the "
165
+ f"reference {reference_rgba.shape[1]}x{reference_rgba.shape[0]}; capture with the same "
166
+ "camera, size and framing")
167
+ crop = crops.get(name)
168
+ views.append((name, reference_rgba, subject(reference_rgba, options.background_tolerance, crop),
169
+ subject(capture_rgba, options.background_tolerance, crop),
170
+ {"reference": os.path.abspath(files[0]), "capture": os.path.abspath(files[1])}))
171
+ return views
172
+
173
+
174
+ def _spec_views(options, crops: dict, render_directory: str) -> list:
175
+ """Views from --spec: each registered view's reference and the model rendered through it (or its frame)."""
176
+ spec_path = os.path.abspath(options.spec)
177
+ spec_directory = os.path.dirname(spec_path)
178
+ spec = tool_common.load_json(spec_path)
179
+ view_specs = spec.get("views") or []
180
+ if not view_specs:
181
+ raise ValueError("the spec has no views")
182
+ needs_model = any(not view.get("frame") for view in view_specs)
183
+ objects = []
184
+ if needs_model:
185
+ model = options.model or (spec.get("model") and os.path.join(spec_directory, spec["model"]))
186
+ if not model:
187
+ raise tool_common.OptionsError("--spec needs --model (or a spec 'model')")
188
+ tool_common.load_model(model)
189
+ objects = tool_common.resolve_objects(options.objects or spec.get("objects"))
190
+ views = []
191
+ for view in view_specs:
192
+ name = view["name"]
193
+ image = os.path.normpath(os.path.join(spec_directory, view["image"]))
194
+ reference_rgba = tool_common.load_image(image)
195
+ tolerance = float(view.get("background_tolerance", options.background_tolerance))
196
+ crop = crops.get(name, view.get("crop"))
197
+ if view.get("frame"):
198
+ capture = os.path.normpath(os.path.join(spec_directory, view["frame"]))
199
+ model_mask = subject(tool_common.load_image(capture), tolerance, crop)
200
+ else:
201
+ frame = ortho_views.frame_from_spec(view, reference_rgba.shape[1], reference_rgba.shape[0])
202
+ capture = os.path.join(render_directory, f"{name}_silhouette.png")
203
+ model_mask = image_measure.apply_crop(ortho_views.silhouette_mask(
204
+ objects, view["view"], frame, capture, options.supersample), crop)
205
+ views.append((f"{name} ({view['view']})", reference_rgba, subject(reference_rgba, tolerance, crop), model_mask,
206
+ {"reference": image, "capture": capture}))
207
+ return views
208
+
209
+
210
+ def run(options) -> dict:
211
+ """
212
+ Compares every view and writes the sheet and its JSON.
213
+
214
+ :param options: Parsed options.
215
+ :returns: The tool result.
216
+ """
217
+ if not options.pair and not options.spec:
218
+ raise tool_common.OptionsError("give --pair name=reference,capture (repeatable) and / or --spec with --model")
219
+ crops = parse_crops(options.crop)
220
+ out_path = os.path.abspath(options.out)
221
+ render_directory = os.path.join(os.path.dirname(out_path), "overlay_renders")
222
+ views = _pair_views(options, crops) + (_spec_views(options, crops, render_directory) if options.spec else [])
223
+ results, tiles = [], []
224
+ for name, reference_rgba, reference, model, sources in views:
225
+ numbers = compare(reference, model, options.min_region_percent)
226
+ passed = numbers["iou"] >= options.min_iou
227
+ results.append({"name": name, **sources, **numbers, "pass": passed})
228
+ tiles.append((tile_label(name, numbers, passed), draw_tile(reference_rgba, reference, model, numbers, options.tile)))
229
+ sheet = evidence_sheet.compose_sheet(tiles, title_lines=[LEGEND])
230
+ report = {"pass": all(result["pass"] for result in results), "min_iou": options.min_iou,
231
+ "worst_iou": min(result["iou"] for result in results), "views": results,
232
+ "sheet": tool_common.save_image(out_path, sheet)}
233
+ report["report_json"] = tool_common.write_json(os.path.splitext(out_path)[0] + ".json", report)
234
+ return report
235
+
236
+
237
+ if __name__ == "__main__":
238
+ tool_common.run_tool(TOOL_NAME, build_parser(), run)