@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
@@ -160,7 +160,8 @@ def connected_to_border(candidates: np.ndarray) -> np.ndarray:
160
160
  return candidates & full
161
161
 
162
162
 
163
- def subject_mask(rgba: np.ndarray, background_tolerance: float = DEFAULT_BACKGROUND_TOLERANCE) -> np.ndarray:
163
+ def subject_mask(rgba: np.ndarray, background_tolerance: float = DEFAULT_BACKGROUND_TOLERANCE,
164
+ remove_specks: bool = True) -> np.ndarray:
164
165
  """
165
166
  Separates the subject from its background. A transparent image uses its alpha. Otherwise the background
166
167
  colour is the median of the image border, and only background-coloured pixels connected to the border
@@ -169,20 +170,37 @@ def subject_mask(rgba: np.ndarray, background_tolerance: float = DEFAULT_BACKGRO
169
170
  :param rgba: float array (height, width, 4), values 0..1.
170
171
  :param background_tolerance: Largest per-channel difference (0..1) from the background colour that
171
172
  still counts as background.
173
+ :param remove_specks: Open the mask (erode, then dilate) to drop single-pixel noise. The opening also
174
+ nicks every convex corner by one pixel, so a tracer that keeps only the largest region turns it off.
172
175
  :returns: Boolean (height, width), True on the subject.
173
176
  """
174
177
  alpha = rgba[:, :, 3]
175
178
  if alpha.min() < 0.5:
176
179
  return alpha > 0.5
180
+ mask = ~connected_to_border(background_like(rgba, background_tolerance))
181
+ # An opening removes single-pixel specks of noise without moving the outline.
182
+ return dilate(erode(mask)) if remove_specks else mask
183
+
184
+
185
+ def background_like(rgba: np.ndarray, background_tolerance: float = DEFAULT_BACKGROUND_TOLERANCE) -> np.ndarray:
186
+ """
187
+ Pixels that look like the background, wherever they are: transparent pixels of an image with alpha, or
188
+ else pixels within the tolerance of the border colour (the median of the image border). Inside a subject
189
+ these are openings, or light details the same colour as the background.
190
+
191
+ :param rgba: float array (height, width, 4), values 0..1.
192
+ :param background_tolerance: Largest per-channel difference (0..1) from the border colour.
193
+ :returns: Boolean (height, width).
194
+ """
195
+ alpha = rgba[:, :, 3]
196
+ if alpha.min() < 0.5:
197
+ return alpha <= 0.5
177
198
  height, width = alpha.shape
178
199
  border = max(2, int(min(width, height) * BORDER_SAMPLE_FRACTION))
179
200
  strips = np.concatenate((rgba[:border, :, :3].reshape(-1, 3), rgba[-border:, :, :3].reshape(-1, 3),
180
201
  rgba[:, :border, :3].reshape(-1, 3), rgba[:, -border:, :3].reshape(-1, 3)))
181
202
  background = np.median(strips, axis=0)
182
- background_like = np.abs(rgba[:, :, :3] - background).max(axis=2) <= background_tolerance
183
- mask = ~connected_to_border(background_like)
184
- # An opening removes single-pixel specks of noise without moving the outline.
185
- return dilate(erode(mask))
203
+ return np.abs(rgba[:, :, :3] - background).max(axis=2) <= background_tolerance
186
204
 
187
205
 
188
206
  def apply_crop(mask: np.ndarray, crop) -> np.ndarray:
@@ -566,3 +584,334 @@ def _stamp(image: np.ndarray, columns: np.ndarray, rows: np.ndarray, color, thic
566
584
  pixel_columns = np.floor(columns).astype(int) + column_offset
567
585
  keep = (pixel_rows >= 0) & (pixel_rows < height) & (pixel_columns >= 0) & (pixel_columns < width)
568
586
  image[pixel_rows[keep], pixel_columns[keep], :3] = color
587
+
588
+
589
+ # ---------------------------------------------------------------------------------------------------------
590
+ # Connected regions, outlines and polylines: shared by trace, overlay-sheet and coverage-check.
591
+ # ---------------------------------------------------------------------------------------------------------
592
+
593
+ # Corner-lattice steps of a traced outline, clockwise on screen (row 0 at the top): right, down, left, up.
594
+ OUTLINE_DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
595
+
596
+ # Query points per block when measuring point-to-segment distances (bounds the points x segments work array).
597
+ DISTANCE_BLOCK_POINTS = 256
598
+
599
+
600
+ def mask_runs(mask: np.ndarray) -> np.ndarray:
601
+ """
602
+ Run-length encodes a boolean mask row by row.
603
+
604
+ :param mask: Boolean (height, width).
605
+ :returns: int64 (N, 3) array of (row, first column, end column) with the end exclusive, in row order.
606
+ """
607
+ height, width = mask.shape
608
+ padded = np.zeros((height, width + 2), dtype=np.int8)
609
+ padded[:, 1:-1] = mask
610
+ changes = np.diff(padded, axis=1)
611
+ start_rows, start_columns = np.nonzero(changes == 1)
612
+ _, end_columns = np.nonzero(changes == -1)
613
+ return np.column_stack((start_rows, start_columns, end_columns)).astype(np.int64)
614
+
615
+
616
+ def _find_root(parents: list, index: int) -> int:
617
+ """Union-find root with path halving."""
618
+ while parents[index] != index:
619
+ parents[index] = parents[parents[index]]
620
+ index = parents[index]
621
+ return index
622
+
623
+
624
+ def _run_roots(runs: np.ndarray) -> np.ndarray:
625
+ """Component root per run: runs on neighbouring rows that share a column are joined (4-connectivity)."""
626
+ parents = list(range(len(runs)))
627
+ row_starts = np.searchsorted(runs[:, 0], np.arange(int(runs[:, 0].max()) + 2)) if len(runs) else []
628
+ for row in range(1, len(row_starts) - 1):
629
+ previous = range(row_starts[row - 1], row_starts[row])
630
+ current = range(row_starts[row], row_starts[row + 1])
631
+ if not previous or not current:
632
+ continue
633
+ upper, lower = previous.start, current.start
634
+ while upper < previous.stop and lower < current.stop:
635
+ if runs[upper, 1] < runs[lower, 2] and runs[lower, 1] < runs[upper, 2]:
636
+ upper_root, lower_root = _find_root(parents, upper), _find_root(parents, lower)
637
+ if upper_root != lower_root:
638
+ parents[max(upper_root, lower_root)] = min(upper_root, lower_root)
639
+ if runs[upper, 2] < runs[lower, 2]:
640
+ upper += 1
641
+ else:
642
+ lower += 1
643
+ return np.array([_find_root(parents, index) for index in range(len(runs))], dtype=np.int64)
644
+
645
+
646
+ def component_regions(mask: np.ndarray, minimum_area_px: int = 1) -> list:
647
+ """
648
+ The 4-connected regions of a mask, largest first.
649
+
650
+ :param mask: Boolean (height, width).
651
+ :param minimum_area_px: Regions smaller than this many pixels are left out.
652
+ :returns: [{"area_px", "bbox": [left, top, right, bottom] (right / bottom exclusive), "centroid":
653
+ [column, row], "touches_border"}] sorted by area, largest first.
654
+ """
655
+ runs = mask_runs(mask)
656
+ if not len(runs):
657
+ return []
658
+ roots = _run_roots(runs)
659
+ height, width = mask.shape
660
+ lengths = runs[:, 2] - runs[:, 1]
661
+ regions = []
662
+ for root in np.unique(roots):
663
+ own = runs[roots == root]
664
+ own_lengths = lengths[roots == root]
665
+ area = int(own_lengths.sum())
666
+ if area < minimum_area_px:
667
+ continue
668
+ centre_columns = (own[:, 1] + own[:, 2]) / 2.0
669
+ regions.append({
670
+ "area_px": area,
671
+ "bbox": [int(own[:, 1].min()), int(own[:, 0].min()), int(own[:, 2].max()), int(own[:, 0].max()) + 1],
672
+ "centroid": [round(float((centre_columns * own_lengths).sum() / area), 2),
673
+ round(float(((own[:, 0] + 0.5) * own_lengths).sum() / area), 2)],
674
+ "touches_border": bool(own[:, 0].min() == 0 or own[:, 0].max() == height - 1
675
+ or own[:, 1].min() == 0 or own[:, 2].max() == width)})
676
+ return sorted(regions, key=lambda region: -region["area_px"])
677
+
678
+
679
+ def largest_component(mask: np.ndarray) -> np.ndarray:
680
+ """
681
+ Keeps only the largest 4-connected region of a mask (stray specks, labels and shadows fall away).
682
+
683
+ :param mask: Boolean (height, width).
684
+ :returns: Boolean mask of the largest region (empty when the mask is empty).
685
+ """
686
+ runs = mask_runs(mask)
687
+ result = np.zeros_like(mask, dtype=bool)
688
+ if not len(runs):
689
+ return result
690
+ roots = _run_roots(runs)
691
+ lengths = runs[:, 2] - runs[:, 1]
692
+ areas = np.bincount(roots, weights=lengths)
693
+ for row, first, end in runs[roots == int(np.argmax(areas))]:
694
+ result[row, first:end] = True
695
+ return result
696
+
697
+
698
+ def hole_mask(mask: np.ndarray) -> np.ndarray:
699
+ """
700
+ The holes of a mask: background regions (4-connected) that do not reach the image border.
701
+
702
+ :param mask: Boolean (height, width).
703
+ :returns: Boolean mask of every hole pixel.
704
+ """
705
+ background = ~mask
706
+ runs = mask_runs(background)
707
+ holes = np.zeros_like(mask, dtype=bool)
708
+ if not len(runs):
709
+ return holes
710
+ roots = _run_roots(runs)
711
+ height, width = mask.shape
712
+ on_border = (runs[:, 0] == 0) | (runs[:, 0] == height - 1) | (runs[:, 1] == 0) | (runs[:, 2] == width)
713
+ border_roots = set(np.unique(roots[on_border]).tolist())
714
+ for (row, first, end), root in zip(runs, roots):
715
+ if int(root) not in border_roots:
716
+ holes[row, first:end] = True
717
+ return holes
718
+
719
+
720
+ def _boundary_edges(mask: np.ndarray) -> dict:
721
+ """Directed pixel-edge boundary of a mask, clockwise on screen: {start corner: [end corners]}."""
722
+ padded = np.pad(mask, 1)
723
+ inside = padded[1:-1, 1:-1]
724
+ edges = {}
725
+ sides = ((padded[:-2, 1:-1], (0, 0), (1, 0)), (padded[1:-1, 2:], (1, 0), (1, 1)),
726
+ (padded[2:, 1:-1], (1, 1), (0, 1)), (padded[1:-1, :-2], (0, 1), (0, 0)))
727
+ for neighbour, start_offset, end_offset in sides:
728
+ rows, columns = np.nonzero(inside & ~neighbour)
729
+ for row, column in zip(rows.tolist(), columns.tolist()):
730
+ start = (column + start_offset[0], row + start_offset[1])
731
+ edges.setdefault(start, []).append((column + end_offset[0], row + end_offset[1]))
732
+ return edges
733
+
734
+
735
+ def _next_corner(edges: dict, corner: tuple, heading: tuple) -> tuple:
736
+ """Takes the outgoing edge at a corner, turning right first where two loops touch, so loops never cross."""
737
+ candidates = edges[corner]
738
+ if len(candidates) > 1:
739
+ def turn(end):
740
+ step = (end[0] - corner[0], end[1] - corner[1])
741
+ return -(heading[0] * step[1] - heading[1] * step[0])
742
+ candidates.sort(key=turn)
743
+ end = candidates.pop(0)
744
+ if not candidates:
745
+ del edges[corner]
746
+ return end
747
+
748
+
749
+ def signed_area(points: np.ndarray) -> float:
750
+ """Shoelace area of a closed polygon (positive for clockwise on screen)."""
751
+ columns, rows = points[:, 0], points[:, 1]
752
+ return 0.5 * float(np.dot(columns, np.roll(rows, -1)) - np.dot(rows, np.roll(columns, -1)))
753
+
754
+
755
+ def _drop_collinear(points: np.ndarray) -> np.ndarray:
756
+ """Removes corners where a closed lattice polyline goes straight on."""
757
+ before = points - np.roll(points, 1, axis=0)
758
+ after = np.roll(points, -1, axis=0) - points
759
+ turning = (before[:, 0] * after[:, 1] - before[:, 1] * after[:, 0]) != 0
760
+ return points[turning]
761
+
762
+
763
+ def outline_loops(mask: np.ndarray) -> list:
764
+ """
765
+ Every closed boundary of a mask, traced along pixel edges, so a loop's extent is exactly the pixels'
766
+ extent (continuous pixel coordinates, pixel (i, j) covers [i, i + 1) x [j, j + 1)).
767
+
768
+ :param mask: Boolean (height, width).
769
+ :returns: [(N, 2) float arrays of (column, row) corners], largest enclosed area first. Outer boundaries
770
+ run clockwise on screen, hole boundaries counter-clockwise.
771
+ """
772
+ edges = _boundary_edges(mask)
773
+ loops = []
774
+ while edges:
775
+ start = next(iter(edges))
776
+ corner, heading, points = start, (1, 0), [start]
777
+ while True:
778
+ end = _next_corner(edges, corner, heading)
779
+ heading = (end[0] - corner[0], end[1] - corner[1])
780
+ corner = end
781
+ if corner == start:
782
+ break
783
+ points.append(corner)
784
+ loops.append(_drop_collinear(np.array(points, dtype=np.float64)))
785
+ return sorted(loops, key=lambda loop: -abs(signed_area(loop)))
786
+
787
+
788
+ def _simplify_open(points: np.ndarray, tolerance: float) -> np.ndarray:
789
+ """Ramer-Douglas-Peucker on an open polyline, iterative; keeps both ends."""
790
+ keep = np.zeros(len(points), dtype=bool)
791
+ keep[0] = keep[-1] = True
792
+ stack = [(0, len(points) - 1)]
793
+ while stack:
794
+ first, last = stack.pop()
795
+ if last - first < 2:
796
+ continue
797
+ chord = points[last] - points[first]
798
+ length = float(np.hypot(*chord))
799
+ offsets = points[first + 1:last] - points[first]
800
+ if length < NUMERIC_FLOOR:
801
+ distances = np.hypot(offsets[:, 0], offsets[:, 1])
802
+ else:
803
+ distances = np.abs(offsets[:, 0] * chord[1] - offsets[:, 1] * chord[0]) / length
804
+ farthest = int(np.argmax(distances))
805
+ if distances[farthest] > tolerance:
806
+ middle = first + 1 + farthest
807
+ keep[middle] = True
808
+ stack.extend(((first, middle), (middle, last)))
809
+ return points[keep]
810
+
811
+
812
+ def simplify_polyline(points: np.ndarray, tolerance: float, closed: bool = True) -> np.ndarray:
813
+ """
814
+ Simplifies a polyline (Ramer-Douglas-Peucker): no removed point lies farther than `tolerance` from the
815
+ result. A closed loop is split at its first point and the point farthest from it, so both halves keep
816
+ their extremes.
817
+
818
+ :param points: (N, 2) array.
819
+ :param tolerance: Largest allowed deviation, in the points' units; 0 or less returns a copy.
820
+ :param closed: True for a closed loop (the last point joins the first).
821
+ :returns: The simplified (M, 2) array (a closed loop is returned without repeating its first point).
822
+ """
823
+ if tolerance <= 0 or len(points) < 4:
824
+ return points.copy()
825
+ if not closed:
826
+ return _simplify_open(points, tolerance)
827
+ farthest = int(np.argmax(np.hypot(*(points - points[0]).T)))
828
+ first_half = _simplify_open(points[:farthest + 1], tolerance)
829
+ second_half = _simplify_open(np.vstack((points[farthest:], points[:1])), tolerance)
830
+ return np.vstack((first_half, second_half[1:-1]))
831
+
832
+
833
+ def polyline_boundary(points: np.ndarray, station_index: int, station: float, closed: bool = True):
834
+ """
835
+ Where a polyline crosses a station line, read along the other coordinate.
836
+
837
+ :param points: (N, 2) array.
838
+ :param station_index: 0 when the station is a value of the first coordinate, 1 for the second.
839
+ :param station: The station value.
840
+ :param closed: True when the last point joins the first.
841
+ :returns: (smallest, largest) crossing of the other coordinate, or None when the line misses it.
842
+ """
843
+ starts = points if closed else points[:-1]
844
+ ends = np.roll(points, -1, axis=0) if closed else points[1:]
845
+ other_index = 1 - station_index
846
+ start_values, end_values = starts[:, station_index], ends[:, station_index]
847
+ spans = (np.minimum(start_values, end_values) <= station) & (station <= np.maximum(start_values, end_values))
848
+ crossings = []
849
+ for start, end in zip(starts[spans], ends[spans]):
850
+ run = end[station_index] - start[station_index]
851
+ if abs(run) < NUMERIC_FLOOR:
852
+ crossings.extend((start[other_index], end[other_index]))
853
+ else:
854
+ share = (station - start[station_index]) / run
855
+ crossings.append(start[other_index] + share * (end[other_index] - start[other_index]))
856
+ if not crossings:
857
+ return None
858
+ return float(min(crossings)), float(max(crossings))
859
+
860
+
861
+ def resample_polyline(points: np.ndarray, step: float, closed: bool = True) -> np.ndarray:
862
+ """
863
+ Points evenly spaced along a polyline by arc length, at most `step` apart, so every stretch of it weighs the
864
+ same in a measurement. Works in any dimension (pixel outlines, world curves).
865
+
866
+ :param points: (N, D) array.
867
+ :param step: Largest spacing between samples, in the points' units.
868
+ :param closed: True for a closed loop (the result does not repeat its first point).
869
+ :returns: (M, D) samples; the polyline's own end points are kept for an open polyline.
870
+ """
871
+ path = np.vstack((points, points[:1])) if closed else np.asarray(points, dtype=np.float64)
872
+ lengths = np.linalg.norm(np.diff(path, axis=0), axis=1)
873
+ keep = np.concatenate(([True], lengths > NUMERIC_FLOOR))
874
+ path, lengths = path[keep], lengths[lengths > NUMERIC_FLOOR]
875
+ along = np.concatenate(([0.0], np.cumsum(lengths)))
876
+ total = float(along[-1])
877
+ if total < NUMERIC_FLOOR:
878
+ return path[:1].copy()
879
+ intervals = max(1, int(np.ceil(total / step)))
880
+ samples = np.linspace(0.0, total, intervals + (0 if closed else 1), endpoint=not closed)
881
+ return np.column_stack([np.interp(samples, along, path[:, axis]) for axis in range(path.shape[1])])
882
+
883
+
884
+ def distances_to_segments(points: np.ndarray, starts: np.ndarray, ends: np.ndarray) -> np.ndarray:
885
+ """
886
+ The distance from every point to the nearest of a set of segments, in any dimension.
887
+
888
+ :param points: (N, D) query points.
889
+ :param starts: (S, D) segment start points.
890
+ :param ends: (S, D) segment end points.
891
+ :returns: (N,) distances, in the points' units.
892
+ """
893
+ directions = ends - starts
894
+ lengths = np.maximum(np.einsum("ij,ij->i", directions, directions), DIVISION_GUARD)
895
+ distances = np.empty(len(points), dtype=np.float64)
896
+ for first in range(0, len(points), DISTANCE_BLOCK_POINTS):
897
+ block = points[first:first + DISTANCE_BLOCK_POINTS]
898
+ offsets = block[:, None, :] - starts[None, :, :]
899
+ along = np.clip(np.einsum("psd,sd->ps", offsets, directions) / lengths, 0.0, 1.0)
900
+ gaps = offsets - along[:, :, None] * directions[None, :, :]
901
+ distances[first:first + len(block)] = np.sqrt(np.einsum("psd,psd->ps", gaps, gaps).min(axis=1))
902
+ return distances
903
+
904
+
905
+ def draw_polyline(image: np.ndarray, points: np.ndarray, color, thickness: int = 1, closed: bool = True) -> None:
906
+ """
907
+ Draws a polyline into an RGB(A) float image in place.
908
+
909
+ :param image: (height, width, 3 or 4) float array.
910
+ :param points: (N, 2) (column, row) points.
911
+ :param color: RGB tuple 0..1.
912
+ :param thickness: Line thickness in pixels.
913
+ :param closed: Also draw the segment from the last point back to the first.
914
+ """
915
+ count = len(points)
916
+ for index in range(count if closed else count - 1):
917
+ draw_segment(image, points[index], points[(index + 1) % count], color, thickness)
@@ -38,7 +38,9 @@ Spec (paths relative to the spec file):
38
38
  }]
39
39
  }
40
40
  The station axis must be one of the view's two image axes; each station measures the silhouette extent
41
- along the other one.
41
+ along the other one. A spec with "require_traces": "traces.json" (relative to the spec) first runs the trace
42
+ gate: every measured object must carry the `bt_traces` stamp of that file's current contents
43
+ (construction_kit.stamp_traces), or the tool fails without measuring.
42
44
  """
43
45
  import math
44
46
  import os
@@ -56,6 +58,7 @@ import numpy as np # noqa: E402
56
58
  import construction_kit # noqa: E402
57
59
  import image_measure # noqa: E402
58
60
  import ortho_views # noqa: E402
61
+ import reference_traces # noqa: E402
59
62
  import tool_common # noqa: E402
60
63
 
61
64
  TOOL_NAME = "measure-stations"
@@ -471,6 +474,11 @@ def run(options) -> dict:
471
474
  needs_model = any(not view.get("frame") for view in views_spec)
472
475
  objects = tool_common.resolve_objects(options.objects or spec.get("objects")) if needs_model else []
473
476
  out_directory = os.path.abspath(options.out or os.path.join(spec_directory, "stations_evidence"))
477
+ trace_gate = reference_traces.required_traces_gate(spec, spec_directory, objects)
478
+ if trace_gate and not trace_gate["pass"]:
479
+ report = {"pass": False, "message": trace_gate["message"], "trace_gate": trace_gate, "views": []}
480
+ report["stations_json"] = tool_common.write_json(os.path.join(out_directory, "stations.json"), report)
481
+ return report
474
482
  views = [measure_view(view, objects, out_directory, spec_directory, options.supersample) for view in views_spec]
475
483
  summary = _summary(views)
476
484
  failing = (summary["stations"]["WRONG"] + summary["stations"]["MISSING"]
@@ -478,6 +486,8 @@ def run(options) -> dict:
478
486
  report = {"pass": failing == 0, "summary": summary, "views": views,
479
487
  "shading_continuity": _dihedral_report(objects, options.max_dihedral) if objects else {},
480
488
  "max_dihedral_degrees": options.max_dihedral}
489
+ if trace_gate:
490
+ report["trace_gate"] = trace_gate
481
491
  report["stations_json"] = tool_common.write_json(os.path.join(out_directory, "stations.json"), report)
482
492
  return report
483
493
 
@@ -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)