@babylonjs-toolkit/agent 1.2.18 → 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 (28) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/skills/bt-blender/SKILL.md +81 -19
  4. package/skills/bt-blender/references/hard-surface.md +9 -5
  5. package/skills/bt-blender/references/vehicles.md +14 -9
  6. package/skills/bt-blender/scripts/blender/__pycache__/construction_kit.cpython-313.pyc +0 -0
  7. package/skills/bt-blender/scripts/blender/__pycache__/geometry_nodes_builders.cpython-313.pyc +0 -0
  8. package/skills/bt-blender/scripts/blender/__pycache__/image_measure.cpython-313.pyc +0 -0
  9. package/skills/bt-blender/scripts/blender/__pycache__/reference_traces.cpython-313.pyc +0 -0
  10. package/skills/bt-blender/scripts/blender/blueprint.py +293 -0
  11. package/skills/bt-blender/scripts/blender/construction_kit.py +61 -1
  12. package/skills/bt-blender/scripts/blender/coverage_check.py +221 -0
  13. package/skills/bt-blender/scripts/blender/evidence_sheet.py +243 -0
  14. package/skills/bt-blender/scripts/blender/image_measure.py +354 -5
  15. package/skills/bt-blender/scripts/blender/measure_stations.py +11 -1
  16. package/skills/bt-blender/scripts/blender/overlay_sheet.py +238 -0
  17. package/skills/bt-blender/scripts/blender/reference_traces.py +344 -0
  18. package/skills/bt-blender/scripts/blender/trace.py +283 -0
  19. package/skills/bt-blender/scripts/blender/world_gate.py +17 -5
  20. package/skills/bt-blender/scripts/bt-blender.mjs +4 -0
  21. package/skills/bt-execute/SKILL.md +2 -1
  22. package/skills/bt-gauntlet/SKILL.md +24 -14
  23. package/skills/bt-gauntlet/references/critic-rubrics.md +37 -5
  24. package/skills/bt-gauntlet/references/loop-templates.md +23 -3
  25. package/skills/bt-gauntlet/references/spec-composition.md +7 -1
  26. package/skills/bt-gauntlet/references/target-images.md +27 -0
  27. package/skills/bt-gauntlet/references/unity-pipeline.md +24 -3
  28. package/skills/bt-gauntlet/references/workspace.md +90 -6
@@ -0,0 +1,344 @@
1
+ """
2
+ Traced reference outlines and design curves for bt-blender build scripts, and the stamp that proves a part
3
+ was built on them.
4
+
5
+ The `trace` tool writes traces.json: per reference view the subject's outline in image pixels and in world
6
+ metres on the view's plane, plus named design curves as world points. A build script reads it with
7
+ `construction_kit.load_traces(path)` (a TraceSet, which records every curve and view the build reads), lays its
8
+ blockout, sections, cage lines and loft rails on those curves, and stamps every part it built with
9
+ `construction_kit.stamp_traces(objects, path, curves_used=traces.accessed_curves)`. The stamp holds the traces
10
+ file's SHA-256 and the curves and views the build read (its provenance). A spec with "require_traces" makes
11
+ `world-gate` and `measure-stations` run the trace gate: the stamp must be current, and the geometry must follow
12
+ the traces (the `trace_adherence` module), so "built on the traced curves" is measured, not attested.
13
+
14
+ Pure Python and numpy: no bpy import (objects are only read and written through their custom properties).
15
+ """
16
+ import hashlib
17
+ import json
18
+ import os
19
+ from collections.abc import Mapping
20
+
21
+ import numpy as np
22
+
23
+ import image_measure
24
+
25
+ # Custom property holding the SHA-256 of the traces file a part was built on.
26
+ TRACES_PROPERTY = "bt_traces"
27
+
28
+ # Custom property holding the stamp's provenance: JSON {"curves": [...], "views": [...]} the build read.
29
+ PROVENANCE_PROPERTY = "bt_traces_provenance"
30
+
31
+ # Spec key naming the traces file (relative to the spec) every measured part must be stamped with.
32
+ REQUIRE_TRACES_KEY = "require_traces"
33
+
34
+ # Spec key listing, per object, the named design curves its surface must follow: {"Shell": ["side_top"]}.
35
+ TRACE_ADHERENCE_KEY = "trace_adherence"
36
+
37
+ # Side names accepted by the boundary lookups: the largest or smallest crossing.
38
+ SIDE_ALIASES = {"max": "max", "upper": "max", "min": "min", "lower": "min"}
39
+
40
+ AXIS_ORDER = ("x", "y", "z")
41
+
42
+ # Bytes read per step while hashing a file.
43
+ HASH_CHUNK_BYTES = 1 << 20
44
+
45
+
46
+ def file_sha256(path: str) -> str:
47
+ """
48
+ The SHA-256 of a file's bytes.
49
+
50
+ :param path: File path.
51
+ :returns: Lower-case hex digest.
52
+ :raises FileNotFoundError: when the file does not exist.
53
+ """
54
+ digest = hashlib.sha256()
55
+ with open(path, "rb") as handle:
56
+ for chunk in iter(lambda: handle.read(HASH_CHUNK_BYTES), b""):
57
+ digest.update(chunk)
58
+ return digest.hexdigest()
59
+
60
+
61
+ class AccessRecordingCurves(Mapping):
62
+ """
63
+ The named design curves of a TraceSet as a read-only mapping that records every curve read through it, so
64
+ `TraceSet.accessed_curves` lists what a build really used however it reached the curves.
65
+ """
66
+
67
+ def __init__(self, curves: dict, accessed: list):
68
+ """
69
+ :param curves: {name: (N, 3) world points}.
70
+ :param accessed: The list the names read are appended to (shared with the TraceSet).
71
+ """
72
+ self._curves = curves
73
+ self._accessed = accessed
74
+
75
+ def __getitem__(self, name: str) -> np.ndarray:
76
+ """One curve's world points (a copy); records the read."""
77
+ if name not in self._curves:
78
+ raise KeyError(f"no traced curve '{name}'; curves: {sorted(self._curves)}")
79
+ if name not in self._accessed:
80
+ self._accessed.append(name)
81
+ return self._curves[name].copy()
82
+
83
+ def __iter__(self):
84
+ """Curve names, in file order; iterating alone reads no curve."""
85
+ return iter(self._curves)
86
+
87
+ def __len__(self) -> int:
88
+ """Number of curves."""
89
+ return len(self._curves)
90
+
91
+
92
+ class TraceSet:
93
+ """
94
+ A loaded traces.json: per-view outlines on the view plane and named world curves.
95
+
96
+ Plane coordinates are in the order of the view's `plane_axes` (image right axis first, then image up),
97
+ e.g. ("y", "z") for a side view. World points are (x, y, z) in metres. Every curve and view the build
98
+ reads is recorded (`accessed_curves`, `accessed_views`) for the stamp's provenance.
99
+ """
100
+
101
+ def __init__(self, data: dict, path: str = None, sha256: str = None):
102
+ """
103
+ :param data: The parsed traces.json.
104
+ :param path: The file it came from, if any.
105
+ :param sha256: That file's SHA-256, if any.
106
+ """
107
+ self.data = data
108
+ self.path = path
109
+ self.sha256 = sha256
110
+ self.views = data.get("views") or {}
111
+ self._accessed_curves = []
112
+ self._accessed_views = []
113
+ self.curves = AccessRecordingCurves(
114
+ {name: np.array(curve["points_world"], dtype=np.float64).reshape(-1, 3)
115
+ for name, curve in (data.get("curves") or {}).items()}, self._accessed_curves)
116
+
117
+ @property
118
+ def accessed_curves(self) -> list:
119
+ """Names of the design curves read so far, in first-read order: pass to `stamp_traces(curves_used=...)`."""
120
+ return list(self._accessed_curves)
121
+
122
+ @property
123
+ def accessed_views(self) -> list:
124
+ """Names of the traced views whose outlines were read so far, in first-read order."""
125
+ return list(self._accessed_views)
126
+
127
+ def _view(self, view: str) -> dict:
128
+ """The record of one traced view, by its spec name; records the read."""
129
+ if view not in self.views:
130
+ raise KeyError(f"no traced view '{view}'; traced views: {sorted(self.views)}")
131
+ if view not in self._accessed_views:
132
+ self._accessed_views.append(view)
133
+ return self.views[view]
134
+
135
+ def curve(self, name: str) -> np.ndarray:
136
+ """
137
+ A named design curve.
138
+
139
+ :param name: Curve name from curves.json.
140
+ :returns: (N, 3) world points in metres.
141
+ :raises KeyError: for an unknown curve.
142
+ """
143
+ return self.curves[name]
144
+
145
+ def plane_axes(self, view: str) -> tuple:
146
+ """The view's two plane axes, image right first: e.g. ("y", "z")."""
147
+ return tuple(self._view(view)["plane_axes"])
148
+
149
+ def depth_axis(self, view: str) -> str:
150
+ """The world axis the view looks along (the one it cannot measure)."""
151
+ return self._view(view)["depth_axis"]
152
+
153
+ def outline(self, view: str) -> np.ndarray:
154
+ """
155
+ The subject's traced outer outline on the view plane.
156
+
157
+ :param view: Spec view name.
158
+ :returns: (N, 2) plane coordinates in metres, a closed loop (last point joins the first).
159
+ """
160
+ return np.array(self._view(view)["outline_world"], dtype=np.float64).reshape(-1, 2)
161
+
162
+ def outline_points(self, view: str, depth: float = 0.0) -> np.ndarray:
163
+ """
164
+ The traced outline as world points, lying in the plane depth_axis = depth.
165
+
166
+ :param view: Spec view name.
167
+ :param depth: Coordinate along the view's depth axis, metres.
168
+ :returns: (N, 3) world points.
169
+ """
170
+ plane = self.outline(view)
171
+ points = np.full((len(plane), 3), float(depth))
172
+ for column, axis in enumerate(self.plane_axes(view)):
173
+ points[:, AXIS_ORDER.index(axis)] = plane[:, column]
174
+ return points
175
+
176
+ def extent(self, view: str) -> dict:
177
+ """The outline's world interval on each plane axis: {axis: [minimum, maximum]} in metres."""
178
+ return dict(self._view(view)["extent_m"])
179
+
180
+ def outline_extent(self, view: str, axis: str, value: float):
181
+ """
182
+ The outline's extent across one station line.
183
+
184
+ :param view: Spec view name.
185
+ :param axis: The station axis, one of the view's plane axes (e.g. "y" in a side view).
186
+ :param value: The station's world coordinate on that axis, metres.
187
+ :returns: (minimum, maximum) of the other plane axis where the outline crosses the station, or None
188
+ when the station misses the outline.
189
+ :raises ValueError: when the axis is not on the view's plane.
190
+ """
191
+ axes = self.plane_axes(view)
192
+ if axis not in axes:
193
+ raise ValueError(f"view '{view}' shows {axes}, not '{axis}'")
194
+ return image_measure.polyline_boundary(self.outline(view), axes.index(axis), float(value))
195
+
196
+ def outline_boundary(self, view: str, axis: str, value: float, side: str = "max"):
197
+ """
198
+ One side of the outline at a station: e.g. the top line of a side view at a length station
199
+ (`outline_boundary("left", "y", 0.4, "max")` gives z), or the half-width of a top view
200
+ (`outline_boundary("top", "y", 0.4, "max")` gives x).
201
+
202
+ :param view: Spec view name.
203
+ :param axis: The station axis, one of the view's plane axes.
204
+ :param value: The station's world coordinate, metres.
205
+ :param side: "max" / "upper" or "min" / "lower" along the other plane axis.
206
+ :returns: The boundary coordinate in metres, or None when the station misses the outline.
207
+ """
208
+ if side not in SIDE_ALIASES:
209
+ raise ValueError(f"side must be one of {sorted(SIDE_ALIASES)}")
210
+ crossing = self.outline_extent(view, axis, value)
211
+ if crossing is None:
212
+ return None
213
+ return crossing[1] if SIDE_ALIASES[side] == "max" else crossing[0]
214
+
215
+
216
+ def load_traces(path: str) -> TraceSet:
217
+ """
218
+ Reads a traces.json written by the `trace` tool.
219
+
220
+ :param path: The file.
221
+ :returns: The TraceSet, carrying the file's SHA-256.
222
+ :raises FileNotFoundError: when the file does not exist.
223
+ """
224
+ absolute = os.path.abspath(path)
225
+ if not os.path.isfile(absolute):
226
+ raise FileNotFoundError(f"traces not found: {absolute} (run the trace tool first)")
227
+ with open(absolute, "r", encoding="utf-8") as handle:
228
+ data = json.load(handle)
229
+ return TraceSet(data, absolute, file_sha256(absolute))
230
+
231
+
232
+ def _views_of_curves(traces: TraceSet, curve_names: list) -> list:
233
+ """The traced views a set of curves was picked in or paired with, in first-use order."""
234
+ views = []
235
+ for name in curve_names:
236
+ record = traces.data["curves"][name]
237
+ for view in (record.get("view"), record.get("pair_view")):
238
+ if view and view not in views:
239
+ views.append(view)
240
+ return views
241
+
242
+
243
+ def _checked_names(names, known, kind: str) -> list:
244
+ """The given names without repeats, in order, after checking each one exists."""
245
+ unique = list(dict.fromkeys(names or []))
246
+ unknown = [name for name in unique if name not in known]
247
+ if unknown:
248
+ raise KeyError(f"unknown traced {kind}(s) {unknown}; the traces file has {sorted(known)}")
249
+ return unique
250
+
251
+
252
+ def stamp_objects(objects, path: str, curves_used=None, views_used=None) -> str:
253
+ """
254
+ Records on every object that it was built on this traces file, and from which curves and views.
255
+
256
+ :param objects: Blender objects (anything with item assignment for custom properties).
257
+ :param path: The traces file.
258
+ :param curves_used: Names of the design curves the build read (e.g. `TraceSet.accessed_curves`). Without
259
+ them the stamp is an attestation only, which the gate fails when the spec lists `trace_adherence`.
260
+ :param views_used: Names of the traced views whose outlines the build read (e.g. `TraceSet.accessed_views`);
261
+ default: the views the used curves were picked in or paired with.
262
+ :returns: The SHA-256 written to each object's `bt_traces` property.
263
+ :raises KeyError: for a curve or view name the traces file does not have.
264
+ """
265
+ traces = load_traces(path)
266
+ curves = _checked_names(curves_used, traces.curves, "curve")
267
+ views = _checked_names(views_used, traces.views, "view") if views_used else _views_of_curves(traces, curves)
268
+ provenance = json.dumps({"curves": curves, "views": views})
269
+ for obj in objects:
270
+ obj[TRACES_PROPERTY] = traces.sha256
271
+ obj[PROVENANCE_PROPERTY] = provenance
272
+ return traces.sha256
273
+
274
+
275
+ def stamp_provenance(obj) -> dict:
276
+ """
277
+ The curves and views an object's stamp says its build read.
278
+
279
+ :param obj: A Blender object.
280
+ :returns: {"curves": [...], "views": [...]}; both empty for a stamp without provenance.
281
+ """
282
+ try:
283
+ recorded = json.loads(obj.get(PROVENANCE_PROPERTY) or "{}")
284
+ except (TypeError, ValueError):
285
+ recorded = {}
286
+ return {"curves": list(recorded.get("curves") or []), "views": list(recorded.get("views") or [])}
287
+
288
+
289
+ def check_stamps(objects, traces_path: str, required_curves: dict = None, require_provenance: bool = False) -> dict:
290
+ """
291
+ Checks the stamps of the measured objects: every one carries the current traces file's SHA-256, and (when
292
+ asked) records the curves its build read, including every curve the spec says it must follow.
293
+
294
+ :param objects: The measured Blender objects.
295
+ :param traces_path: The required traces file.
296
+ :param required_curves: {object name: [curve names]} from the spec's `trace_adherence`.
297
+ :param require_provenance: Fail objects stamped without recorded curves ("attestation only").
298
+ :returns: {"pass", "traces", "sha256", "unstamped", "stale", "attestation_only", "missing_objects",
299
+ "unknown_curves", "unrecorded_curves", "provenance", "message"}.
300
+ """
301
+ absolute = os.path.abspath(traces_path)
302
+ required_curves = required_curves or {}
303
+ if not os.path.isfile(absolute):
304
+ return {"pass": False, "traces": absolute, "sha256": None, "unstamped": [obj.name for obj in objects],
305
+ "stale": [], "attestation_only": [], "missing_objects": [], "unknown_curves": {},
306
+ "unrecorded_curves": {}, "provenance": {},
307
+ "message": f"required traces file not found: {absolute}. Run the trace tool, build on its curves, "
308
+ "and stamp the parts from the build with construction_kit.stamp_traces."}
309
+ traces = load_traces(absolute)
310
+ names = [obj.name for obj in objects]
311
+ unstamped = [obj.name for obj in objects if not obj.get(TRACES_PROPERTY)]
312
+ stale = [obj.name for obj in objects if obj.get(TRACES_PROPERTY) and obj.get(TRACES_PROPERTY) != traces.sha256]
313
+ provenance = {obj.name: stamp_provenance(obj) for obj in objects if obj.get(TRACES_PROPERTY) == traces.sha256}
314
+ attestation_only = [name for name, record in provenance.items() if not record["curves"]]
315
+ missing_objects = [name for name in required_curves if name not in names]
316
+ unknown_curves = {name: [curve for curve in curves if curve not in traces.curves]
317
+ for name, curves in required_curves.items()}
318
+ unknown_curves = {name: curves for name, curves in unknown_curves.items() if curves}
319
+ unrecorded_curves = {name: [curve for curve in curves if curve not in provenance[name]["curves"]]
320
+ for name, curves in required_curves.items() if name in provenance}
321
+ unrecorded_curves = {name: curves for name, curves in unrecorded_curves.items() if curves}
322
+ problems = []
323
+ if unstamped:
324
+ problems.append(f"not built on the traces (no '{TRACES_PROPERTY}' stamp): {', '.join(unstamped)}")
325
+ if stale:
326
+ problems.append(f"stamped with an older traces file: {', '.join(stale)}")
327
+ if attestation_only and require_provenance:
328
+ problems.append(f"stamped without the curves the build read (attestation only): {', '.join(attestation_only)}")
329
+ if missing_objects:
330
+ problems.append(f"trace_adherence names objects that are not measured: {', '.join(missing_objects)}")
331
+ if unknown_curves:
332
+ problems.append(f"trace_adherence names curves the traces file lacks: {unknown_curves}")
333
+ if unrecorded_curves:
334
+ problems.append(f"the stamp does not record curves the part must follow: {unrecorded_curves}")
335
+ passed = not problems
336
+ message = ("every measured part is stamped with the current traces" if passed else
337
+ "trace gate failed: " + "; ".join(problems) + f". Build these parts on the curves in {absolute} "
338
+ "(construction_kit.load_traces) and stamp them from that build with the curves it read "
339
+ "(construction_kit.stamp_traces(parts, path, curves_used=traces.accessed_curves)); re-stamp after "
340
+ "re-tracing. Never answer a refusal by stamping: fix the build.")
341
+ return {"pass": passed, "traces": absolute, "sha256": traces.sha256, "unstamped": unstamped, "stale": stale,
342
+ "attestation_only": attestation_only, "missing_objects": missing_objects,
343
+ "unknown_curves": unknown_curves, "unrecorded_curves": unrecorded_curves, "provenance": provenance,
344
+ "message": message}
@@ -0,0 +1,283 @@
1
+ """
2
+ trace -- trace every reference view's subject outline, and named design curves, into world coordinates.
3
+
4
+ For each view of a stations spec the subject is separated from the border background colour (the view's
5
+ crop and background_tolerance apply) and the largest region is kept (stray specks, labels and shadows fall
6
+ away). Enclosed holes (transparent or background-coloured regions inside the subject) are filled for the
7
+ outer outline and traced on their own. The outline is followed along pixel edges, so its extent is exactly
8
+ the subject's, then simplified (--simplify-px). Every outline is written in image pixels AND in world metres
9
+ on the view's plane (its two image axes, e.g. y and z for a side view), with the subject's world extent per
10
+ axis.
11
+
12
+ --curves adds hand-picked design curves (a top line, a shoulder line, a plan edge):
13
+ {"curves": [{"name": "side_top_line", "view": "left", "points_px": [[x, y], ...],
14
+ "depth": 0.0, optional: coordinate on the view's depth axis
15
+ "pair_view": "top", optional: read the depth axis from another view
16
+ "pair_curve": "top_edge", optional: ... from this curve picked in the pair view
17
+ "pair_side": "max"}]} optional: ... else from the pair view's outline, max / min
18
+ Pairing convention: a curve picked in one view fixes the two axes that view shows; the axis it cannot see
19
+ (its depth axis) is read from the pair view, which must show that axis. The pair view shares one axis with
20
+ the curve's view: at every curve point the shared coordinate is kept, and the depth coordinate is read from
21
+ the pair curve (interpolated along the shared axis) or from the pair view's outline boundary at that shared
22
+ coordinate. Example: a side-view top line (y, z) paired with the top view's outline max side gets x = the
23
+ plan half-width at each y. Points beyond the pair source's range are clamped to its ends and counted.
24
+
25
+ Writes traces.json (read in a build script with construction_kit.load_traces; stamp the parts built on it
26
+ with construction_kit.stamp_traces) and trace_<view>.png previews: outline (green), holes (orange), design
27
+ curves (magenta) and the crop box (blue) on the dimmed reference.
28
+
29
+ node bt-blender.mjs trace --spec refs/spec.json --out refs/traces.json [--curves refs/curves.json]
30
+ [--simplify-px 1.5] [--preview-dir dir]
31
+ """
32
+ import os
33
+ import sys
34
+
35
+ sys.dont_write_bytecode = True
36
+ SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
37
+ if SCRIPT_DIRECTORY not in sys.path:
38
+ sys.path.insert(0, SCRIPT_DIRECTORY)
39
+
40
+ import numpy as np # noqa: E402
41
+
42
+ import evidence_sheet # noqa: E402
43
+ import image_measure # noqa: E402
44
+ import ortho_views # noqa: E402
45
+ import reference_traces # noqa: E402
46
+ import tool_common # noqa: E402
47
+
48
+ TOOL_NAME = "trace"
49
+
50
+ DEFAULT_SIMPLIFY_PIXELS = 1.5
51
+
52
+ # Holes smaller than this share of the subject's area are not traced (anti-aliasing specks).
53
+ MINIMUM_HOLE_SHARE = 0.001
54
+
55
+ # Preview colours and sizes.
56
+ OUTLINE_COLOR = (0.2, 0.95, 0.4)
57
+ HOLE_COLOR = (1.0, 0.6, 0.1)
58
+ CURVE_COLOR = (1.0, 0.25, 0.85)
59
+ CROP_COLOR = (0.3, 0.6, 1.0)
60
+ LINE_PIXELS = 2
61
+ CURVE_POINT_RADIUS = 3
62
+
63
+ # Decimal places kept for pixel and metre coordinates in traces.json.
64
+ PIXEL_DECIMALS = 2
65
+ METRE_DECIMALS = 5
66
+
67
+
68
+ def build_parser() -> tool_common.ToolArgumentParser:
69
+ """The tool's command-line options."""
70
+ parser = tool_common.ToolArgumentParser(prog=TOOL_NAME, description=__doc__.strip().splitlines()[0])
71
+ parser.add_argument("--spec", required=True, help="stations spec JSON: registered straight views")
72
+ parser.add_argument("--out", required=True, help="traces JSON to write")
73
+ parser.add_argument("--curves", help="named design curves picked in image pixels (JSON)")
74
+ parser.add_argument("--simplify-px", type=float, default=DEFAULT_SIMPLIFY_PIXELS,
75
+ help="largest deviation of the simplified outline from the pixel outline, pixels")
76
+ parser.add_argument("--preview-dir", help="folder for trace_<view>.png (default: the --out folder)")
77
+ return parser
78
+
79
+
80
+ def image_axes(view: str) -> dict:
81
+ """The view's image axes as world axis names and signs: {"right": (axis, sign), "up": (axis, sign)}."""
82
+ basis = ortho_views.view_basis(view)
83
+ return {"right": ortho_views.axis_of(basis.right), "up": ortho_views.axis_of(basis.up),
84
+ "depth": ortho_views.axis_of(basis.forward)}
85
+
86
+
87
+ def pixels_to_plane(points_px: np.ndarray, frame: ortho_views.PixelFrame, axes: dict) -> np.ndarray:
88
+ """
89
+ Converts (column, row) pixels into world coordinates on the view plane.
90
+
91
+ :param points_px: (N, 2) continuous pixel coordinates.
92
+ :param frame: The view's pixel frame.
93
+ :param axes: image_axes() of the view.
94
+ :returns: (N, 2) metres along (right axis, up axis).
95
+ """
96
+ right = ortho_views.pixel_to_coordinate(points_px[:, 0], "right", frame, axes["right"][1])
97
+ up = ortho_views.pixel_to_coordinate(points_px[:, 1], "up", frame, axes["up"][1])
98
+ return np.column_stack((right, up))
99
+
100
+
101
+ def subject_regions(view_spec: dict, rgba: np.ndarray) -> tuple:
102
+ """
103
+ The view's subject: the largest region of the cropped background-separated mask, and its holes: regions
104
+ enclosed by the subject that are transparent or background-coloured (openings, or light details the same
105
+ colour as the background; the outline stays filled either way).
106
+
107
+ :returns: (subject mask with holes filled, hole mask, number of smaller regions left out).
108
+ :raises ValueError: when the view holds no subject.
109
+ """
110
+ tolerance = float(view_spec.get("background_tolerance", image_measure.DEFAULT_BACKGROUND_TOLERANCE))
111
+ mask = image_measure.apply_crop(image_measure.subject_mask(rgba, tolerance, remove_specks=False), view_spec.get("crop"))
112
+ if not mask.any():
113
+ raise ValueError(f"view '{view_spec['name']}': no subject found in {view_spec['image']}")
114
+ subject = image_measure.largest_component(mask)
115
+ dropped = len(image_measure.component_regions(mask & ~subject))
116
+ filled = subject | image_measure.hole_mask(subject)
117
+ holes = filled & image_measure.background_like(rgba, tolerance)
118
+ return filled, holes, dropped
119
+
120
+
121
+ def trace_view(view_spec: dict, spec_directory: str, simplify_pixels: float) -> dict:
122
+ """
123
+ Traces one view.
124
+
125
+ :returns: The view's traces record, plus "_reference" (the image) and "_frame" for the caller's use.
126
+ """
127
+ image_path = os.path.normpath(os.path.join(spec_directory, view_spec["image"]))
128
+ rgba = tool_common.load_image(image_path)
129
+ height, width = rgba.shape[:2]
130
+ frame = ortho_views.frame_from_spec(view_spec, width, height)
131
+ axes = image_axes(view_spec["view"])
132
+ filled, holes, dropped = subject_regions({**view_spec, "image": image_path}, rgba)
133
+ outer = image_measure.outline_loops(filled)[0]
134
+ outline_px = image_measure.simplify_polyline(outer, simplify_pixels)
135
+ minimum_hole_area = MINIMUM_HOLE_SHARE * float(filled.sum())
136
+ hole_records = []
137
+ for loop in image_measure.outline_loops(holes):
138
+ area = image_measure.signed_area(loop)
139
+ if area < minimum_hole_area:
140
+ continue # a speck, or an island inside a hole (traced counter-clockwise, negative area)
141
+ simplified = image_measure.simplify_polyline(loop, simplify_pixels)
142
+ hole_records.append({"area_px": round(area, 1), "outline_px": np.round(simplified, PIXEL_DECIMALS).tolist(),
143
+ "outline_world": np.round(pixels_to_plane(simplified, frame, axes), METRE_DECIMALS).tolist()})
144
+ left, top = outer.min(axis=0)
145
+ right, bottom = outer.max(axis=0)
146
+ corners = pixels_to_plane(np.array([[left, top], [right, bottom]]), frame, axes)
147
+ extent = {axes["right"][0]: sorted(np.round(corners[:, 0], METRE_DECIMALS).tolist()),
148
+ axes["up"][0]: sorted(np.round(corners[:, 1], METRE_DECIMALS).tolist())}
149
+ return {"view": view_spec["view"], "image": image_path, "image_size_px": [width, height],
150
+ "pixels_per_metre": frame.pixels_per_metre, "origin_pixel": [frame.origin_column, frame.origin_row],
151
+ "crop": view_spec.get("crop"),
152
+ "image_axes": {key: {"axis": axis, "sign": sign} for key, (axis, sign) in axes.items()},
153
+ "plane_axes": [axes["right"][0], axes["up"][0]], "depth_axis": axes["depth"][0],
154
+ "bounds_px": [float(left), float(top), float(right), float(bottom)], "extent_m": extent,
155
+ "area_px": int(filled.sum()), "regions_left_out": dropped,
156
+ "outline_px": np.round(outline_px, PIXEL_DECIMALS).tolist(),
157
+ "outline_world": np.round(pixels_to_plane(outline_px, frame, axes), METRE_DECIMALS).tolist(),
158
+ "holes": hole_records, "_reference": rgba, "_frame": frame, "_axes": axes}
159
+
160
+
161
+ def _pair_depths(curve: dict, shared_axis: str, shared_values: np.ndarray, depth_axis: str, records: dict,
162
+ curve_specs: dict, trace_set: reference_traces.TraceSet) -> tuple:
163
+ """The depth coordinate of every curve point read from the pair view: (depths, clamped point count)."""
164
+ pair = records[curve["pair_view"]]
165
+ pair_axes = pair["plane_axes"]
166
+ if curve.get("pair_curve"):
167
+ source = curve_specs.get(curve["pair_curve"])
168
+ if source is None or source["view"] != curve["pair_view"]:
169
+ raise ValueError(f"curve '{curve['name']}': pair_curve '{curve['pair_curve']}' must be a curve picked in "
170
+ f"view '{curve['pair_view']}'")
171
+ plane = pixels_to_plane(np.array(source["points_px"], dtype=np.float64), pair["_frame"], pair["_axes"])
172
+ along, across = plane[:, pair_axes.index(shared_axis)], plane[:, pair_axes.index(depth_axis)]
173
+ order = np.argsort(along)
174
+ clamped = int(((shared_values < along.min()) | (shared_values > along.max())).sum())
175
+ return np.interp(shared_values, along[order], across[order]), clamped
176
+ side = curve.get("pair_side", "max")
177
+ low, high = trace_set.extent(curve["pair_view"])[shared_axis]
178
+ inside = np.clip(shared_values, low, high)
179
+ depths = [trace_set.outline_boundary(curve["pair_view"], shared_axis, value, side) for value in inside]
180
+ return np.array(depths, dtype=np.float64), int((inside != shared_values).sum())
181
+
182
+
183
+ def trace_curve(curve: dict, records: dict, curve_specs: dict, trace_set: reference_traces.TraceSet) -> dict:
184
+ """
185
+ Converts one picked design curve into world points.
186
+
187
+ :param curve: {"name", "view", "points_px", optional "depth", "pair_view", "pair_curve", "pair_side"}.
188
+ :param records: Traced views by name.
189
+ :param curve_specs: Every curve spec by name (pair curves are read from here).
190
+ :param trace_set: The traced views, for outline lookups.
191
+ :returns: The curve's traces record.
192
+ """
193
+ name = curve["name"]
194
+ if curve.get("view") not in records:
195
+ raise ValueError(f"curve '{name}': unknown view '{curve.get('view')}'")
196
+ points_px = np.array(curve.get("points_px") or [], dtype=np.float64).reshape(-1, 2)
197
+ if len(points_px) < 2:
198
+ raise ValueError(f"curve '{name}' needs at least two points_px")
199
+ record = records[curve["view"]]
200
+ plane_axes, depth_axis = record["plane_axes"], record["depth_axis"]
201
+ plane = pixels_to_plane(points_px, record["_frame"], record["_axes"])
202
+ world = np.zeros((len(plane), 3))
203
+ for column, axis in enumerate(plane_axes):
204
+ world[:, ortho_views.AXIS_NAMES.index(axis)] = plane[:, column]
205
+ clamped = 0
206
+ result = {"view": curve["view"], "points_px": points_px.round(PIXEL_DECIMALS).tolist()}
207
+ if curve.get("pair_view"):
208
+ if curve["pair_view"] not in records:
209
+ raise ValueError(f"curve '{name}': unknown pair_view '{curve['pair_view']}'")
210
+ pair_axes = records[curve["pair_view"]]["plane_axes"]
211
+ if depth_axis not in pair_axes:
212
+ raise ValueError(f"curve '{name}': pair_view '{curve['pair_view']}' shows {pair_axes}, not the "
213
+ f"{depth_axis} axis view '{curve['view']}' cannot see")
214
+ shared_axis = next(axis for axis in pair_axes if axis != depth_axis)
215
+ shared_values = plane[:, plane_axes.index(shared_axis)]
216
+ depths, clamped = _pair_depths({**curve, "name": name}, shared_axis, shared_values, depth_axis, records,
217
+ curve_specs, trace_set)
218
+ result.update({"pair_view": curve["pair_view"], "shared_axis": shared_axis,
219
+ "pair_source": f"curve {curve['pair_curve']}" if curve.get("pair_curve")
220
+ else f"outline {curve.get('pair_side', 'max')}"})
221
+ else:
222
+ depths = np.full(len(plane), float(curve.get("depth", 0.0)))
223
+ world[:, ortho_views.AXIS_NAMES.index(depth_axis)] = depths
224
+ result.update({"depth_axis": depth_axis, "points_world": world.round(METRE_DECIMALS).tolist(),
225
+ "clamped_points": clamped})
226
+ return result
227
+
228
+
229
+ def write_preview(name: str, record: dict, curves: dict, directory: str) -> str:
230
+ """Draws the traced outline, holes, curves and crop box on the dimmed reference; returns the file."""
231
+ picture = evidence_sheet.dimmed(record["_reference"])
232
+ if record["crop"]:
233
+ evidence_sheet.draw_box(picture, record["crop"], CROP_COLOR, 1)
234
+ image_measure.draw_polyline(picture, np.array(record["outline_px"]), OUTLINE_COLOR, LINE_PIXELS)
235
+ for hole in record["holes"]:
236
+ image_measure.draw_polyline(picture, np.array(hole["outline_px"]), HOLE_COLOR, LINE_PIXELS)
237
+ for curve_name, curve in curves.items():
238
+ if curve["view"] != name:
239
+ continue
240
+ points = np.array(curve["points_px"])
241
+ image_measure.draw_polyline(picture, points, CURVE_COLOR, LINE_PIXELS, closed=False)
242
+ for point in points:
243
+ image_measure.draw_circle(picture, point, CURVE_POINT_RADIUS, CURVE_COLOR)
244
+ evidence_sheet.draw_text(picture, curve_name, int(points[0][0]) + 4, int(points[0][1]) + 4, CURVE_COLOR)
245
+ evidence_sheet.draw_text(picture, f"{name} ({record['view']})", 6, 6, OUTLINE_COLOR)
246
+ return tool_common.save_image(os.path.join(directory, f"trace_{name}.png"), picture)
247
+
248
+
249
+ def run(options) -> dict:
250
+ """
251
+ Traces every view and curve and writes traces.json and the previews.
252
+
253
+ :param options: Parsed options.
254
+ :returns: The tool result.
255
+ """
256
+ spec_path = os.path.abspath(options.spec)
257
+ spec_directory = os.path.dirname(spec_path)
258
+ spec = tool_common.load_json(spec_path)
259
+ views = spec.get("views") or []
260
+ if not views:
261
+ raise ValueError("the spec has no views")
262
+ records = {view["name"]: trace_view(view, spec_directory, options.simplify_px) for view in views}
263
+ public = {name: {key: value for key, value in record.items() if not key.startswith("_")}
264
+ for name, record in records.items()}
265
+ trace_set = reference_traces.TraceSet({"views": public})
266
+ curve_list = tool_common.load_json(options.curves).get("curves", []) if options.curves else []
267
+ curve_specs = {curve["name"]: curve for curve in curve_list}
268
+ curves = {curve["name"]: trace_curve(curve, records, curve_specs, trace_set) for curve in curve_list}
269
+ out_path = os.path.abspath(options.out)
270
+ preview_directory = os.path.abspath(options.preview_dir or os.path.dirname(out_path))
271
+ previews = {name: write_preview(name, record, curves, preview_directory) for name, record in records.items()}
272
+ traces = {"spec": spec_path, "simplify_px": options.simplify_px, "views": public, "curves": curves}
273
+ tool_common.write_json(out_path, traces)
274
+ return {"pass": True, "traces": out_path, "sha256": reference_traces.file_sha256(out_path),
275
+ "views": {name: {"extent_m": record["extent_m"], "outline_points": len(record["outline_px"]),
276
+ "holes": len(record["holes"]), "regions_left_out": record["regions_left_out"],
277
+ "preview": previews[name]} for name, record in public.items()},
278
+ "curves": {name: {"points": len(curve["points_world"]), "clamped_points": curve["clamped_points"]}
279
+ for name, curve in curves.items()}}
280
+
281
+
282
+ if __name__ == "__main__":
283
+ tool_common.run_tool(TOOL_NAME, build_parser(), run)