@babylonjs-toolkit/agent 1.2.16 → 1.2.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/package.json +1 -1
- package/skills/bt-blender/SKILL.md +386 -0
- package/skills/bt-blender/THIRD_PARTY_NOTICES.md +141 -0
- package/skills/bt-blender/references/art-style-and-genre.md +173 -0
- package/skills/bt-blender/references/characters-and-creatures.md +644 -0
- package/skills/bt-blender/references/environments.md +478 -0
- package/skills/bt-blender/references/game-engine-export.md +284 -0
- package/skills/bt-blender/references/geometry-nodes.md +447 -0
- package/skills/bt-blender/references/hard-surface.md +720 -0
- package/skills/bt-blender/references/procedural-generation.md +358 -0
- package/skills/bt-blender/references/rigging-and-animation.md +1080 -0
- package/skills/bt-blender/references/sculpting-and-retopology.md +544 -0
- package/skills/bt-blender/references/uv-and-pbr-materials.md +381 -0
- package/skills/bt-blender/references/vehicles.md +632 -0
- package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
- package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
- package/skills/bt-blender/scripts/blender/construction_kit.py +1710 -0
- package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
- package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
- package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
- package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
- package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
- package/skills/bt-blender/scripts/blender/image_measure.py +568 -0
- package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
- package/skills/bt-blender/scripts/blender/measure_stations.py +486 -0
- package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
- package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
- package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
- package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
- package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
- package/skills/bt-blender/scripts/blender/review_render.py +358 -0
- package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
- package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
- package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
- package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
- package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
- package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
- package/skills/bt-blender/scripts/blender/world_gate.py +219 -0
- package/skills/bt-blender/scripts/bt-blender.mjs +329 -0
- package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
- package/skills/bt-gauntlet/SKILL.md +6 -6
- package/skills/bt-gauntlet/references/critic-rubrics.md +71 -4
- package/skills/bt-gauntlet/references/spec-composition.md +13 -0
- package/skills/bt-gauntlet/references/unity-pipeline.md +18 -2
- package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
"""
|
|
2
|
+
measure_stations -- measure a model against reference images at stations, for size AND form.
|
|
3
|
+
|
|
4
|
+
For every reference view (an image, its pixels-per-metre, the pixel where the world origin projects and
|
|
5
|
+
the named straight view it shows), the model is rendered through an orthographic camera registered to
|
|
6
|
+
exactly that image (or a captured frame from the game's own locked camera is used instead). At each
|
|
7
|
+
station both silhouettes are measured the same way:
|
|
8
|
+
- size: the silhouette extent across the station line, graded MATCH (<= 3 % or <= 1 cm),
|
|
9
|
+
CLOSE (<= 6 %) or WRONG (> 6 %); the exact cross-section extent of the mesh is reported beside it;
|
|
10
|
+
- form: corner radii (graded within 15 %) and luminance ramps across rolls (how wide the shading
|
|
11
|
+
transition is, and whether it changes in one step like a crease). The reference radius, and the model's
|
|
12
|
+
when it comes from a captured frame, is a circle fit on the outline. A rendered model's radius is the
|
|
13
|
+
exact equal-depth radius of its geometry, r = d / (1 / sin(a / 2) - 1), from the distance d of its
|
|
14
|
+
projected edges to the corner where the fitted flats meet: a subdivided edge is not a circle, and its
|
|
15
|
+
circle fit read 0.038-0.086 m for one 0.05 m corner depending on which points counted as the arc;
|
|
16
|
+
- shading continuity of the mesh itself: the largest dihedral across smooth edges.
|
|
17
|
+
|
|
18
|
+
Writes <out>/stations.json and one evidence image per view (reference | model | overlay, station lines
|
|
19
|
+
coloured by grade, corner circles drawn). Exits 1 while any station or corner is WRONG.
|
|
20
|
+
|
|
21
|
+
blender --background --factory-startup --python-exit-code 1 --python measure_stations.py -- \
|
|
22
|
+
--spec stations_spec.json [--model model.blend] [--objects Body Nose] [--out evidence/]
|
|
23
|
+
|
|
24
|
+
Spec (paths relative to the spec file):
|
|
25
|
+
{
|
|
26
|
+
"model": "model.blend", optional; --model wins
|
|
27
|
+
"objects": ["Body"], optional; default every visible mesh
|
|
28
|
+
"views": [{
|
|
29
|
+
"name": "top", "view": "top", view: front back right left top bottom
|
|
30
|
+
"image": "refs/top.png",
|
|
31
|
+
"pixels_per_metre": 500, "origin_pixel": [512, 300],
|
|
32
|
+
"crop": [left, top, right, bottom], optional, pixels
|
|
33
|
+
"background_tolerance": 0.08, optional
|
|
34
|
+
"frame": "captures/top.png", optional: a captured model image instead of a render
|
|
35
|
+
"stations": {"axis": "y", "count": 10, "positions": [0.12, -0.4]},
|
|
36
|
+
"corners": [{"name": "shoulder", "quadrant": "top_right", "region": [left, top, right, bottom]}],
|
|
37
|
+
"ramps": [{"name": "roll", "axis": "z", "position": 0.25}]
|
|
38
|
+
}]
|
|
39
|
+
}
|
|
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.
|
|
42
|
+
"""
|
|
43
|
+
import math
|
|
44
|
+
import os
|
|
45
|
+
import sys
|
|
46
|
+
|
|
47
|
+
sys.dont_write_bytecode = True
|
|
48
|
+
SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
|
|
49
|
+
if SCRIPT_DIRECTORY not in sys.path:
|
|
50
|
+
sys.path.insert(0, SCRIPT_DIRECTORY)
|
|
51
|
+
|
|
52
|
+
import bmesh # noqa: E402
|
|
53
|
+
import bpy # noqa: E402
|
|
54
|
+
import numpy as np # noqa: E402
|
|
55
|
+
|
|
56
|
+
import construction_kit # noqa: E402
|
|
57
|
+
import image_measure # noqa: E402
|
|
58
|
+
import ortho_views # noqa: E402
|
|
59
|
+
import tool_common # noqa: E402
|
|
60
|
+
|
|
61
|
+
TOOL_NAME = "measure-stations"
|
|
62
|
+
|
|
63
|
+
# Evidence colours (RGB 0..1) by grade, plus the corner-circle colour.
|
|
64
|
+
GRADE_COLORS = {"MATCH": (0.1, 0.7, 0.25), "CLOSE": (0.95, 0.65, 0.1), "WRONG": (0.9, 0.15, 0.15),
|
|
65
|
+
"MISSING": (0.9, 0.15, 0.15), "NO_REFERENCE": (0.5, 0.5, 0.5)}
|
|
66
|
+
CORNER_COLOR = (0.1, 0.75, 0.95)
|
|
67
|
+
|
|
68
|
+
# Overlay colours: both silhouettes, reference only, model only, neither.
|
|
69
|
+
OVERLAY_BOTH = (0.6, 0.6, 0.6)
|
|
70
|
+
OVERLAY_REFERENCE_ONLY = (0.9, 0.25, 0.25)
|
|
71
|
+
OVERLAY_MODEL_ONLY = (0.25, 0.45, 0.95)
|
|
72
|
+
OVERLAY_EMPTY = (1.0, 1.0, 1.0)
|
|
73
|
+
|
|
74
|
+
# Dimming applied to the reference image outside its crop box.
|
|
75
|
+
OUTSIDE_CROP_DIMMING = 0.35
|
|
76
|
+
|
|
77
|
+
# Smooth edges sharper than this (degrees) break a rounded form's shading continuity.
|
|
78
|
+
DEFAULT_MAXIMUM_DIHEDRAL = 20.0
|
|
79
|
+
|
|
80
|
+
# How a corner's model radius was measured.
|
|
81
|
+
EQUAL_DEPTH_METHOD = "equal_depth"
|
|
82
|
+
CIRCLE_FIT_METHOD = "circle_fit"
|
|
83
|
+
|
|
84
|
+
# Keeps the point-to-segment projection finite for zero-length edges.
|
|
85
|
+
SEGMENT_LENGTH_GUARD = 1e-30
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def build_parser() -> tool_common.ToolArgumentParser:
|
|
89
|
+
"""The tool's command-line options."""
|
|
90
|
+
parser = tool_common.ToolArgumentParser(prog=TOOL_NAME, description=__doc__.strip().splitlines()[0])
|
|
91
|
+
parser.add_argument("--spec", required=True, help="stations spec JSON")
|
|
92
|
+
parser.add_argument("--model", help="model to measure (.blend .glb .gltf .fbx .obj); overrides the spec")
|
|
93
|
+
parser.add_argument("--objects", nargs="*", help="objects to measure; overrides the spec")
|
|
94
|
+
parser.add_argument("--out", help="evidence folder (default: <spec folder>/stations_evidence)")
|
|
95
|
+
parser.add_argument("--supersample", type=int, default=ortho_views.DEFAULT_SUPERSAMPLE)
|
|
96
|
+
parser.add_argument("--max-dihedral", type=float, default=DEFAULT_MAXIMUM_DIHEDRAL,
|
|
97
|
+
help="degrees; smooth edges sharper than this are listed as shading breaks")
|
|
98
|
+
return parser
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _resolve(spec_directory: str, path):
|
|
102
|
+
"""A spec path made absolute against the spec's folder."""
|
|
103
|
+
return None if path is None else os.path.normpath(os.path.join(spec_directory, path))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _image_axes(view: str) -> dict:
|
|
107
|
+
"""Maps the view's two image axes to world axis names and signs."""
|
|
108
|
+
basis = ortho_views.view_basis(view)
|
|
109
|
+
right_axis, right_sign = ortho_views.axis_of(basis.right)
|
|
110
|
+
up_axis, up_sign = ortho_views.axis_of(basis.up)
|
|
111
|
+
return {"right": (right_axis, right_sign), "up": (up_axis, up_sign)}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _station_layout(view_spec: dict, axes: dict) -> tuple:
|
|
115
|
+
"""Which image axis the stations run along, which one is measured, and the world axis names."""
|
|
116
|
+
stations = view_spec.get("stations") or {}
|
|
117
|
+
station_axis = str(stations.get("axis", "")).lower()
|
|
118
|
+
if station_axis == axes["up"][0]:
|
|
119
|
+
return "up", "right", station_axis, axes["right"][0]
|
|
120
|
+
if station_axis == axes["right"][0]:
|
|
121
|
+
return "right", "up", station_axis, axes["up"][0]
|
|
122
|
+
raise ValueError(f"view '{view_spec['name']}': station axis '{station_axis}' is not one of its image axes "
|
|
123
|
+
f"({axes['right'][0]}, {axes['up'][0]})")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _measure_extent(mask: np.ndarray, station_image_axis: str, pixel: float):
|
|
127
|
+
"""Silhouette extent (pixels) across one station line: along a row for "up" stations, else a column."""
|
|
128
|
+
if station_image_axis == "up":
|
|
129
|
+
return image_measure.extent_along_row(mask, pixel)
|
|
130
|
+
return image_measure.extent_along_column(mask, pixel)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _station_positions(view_spec: dict, reference_mask: np.ndarray, frame, layout: tuple, axes: dict) -> list:
|
|
134
|
+
"""Station world positions: the listed ones plus `count` evenly spaced over the reference subject."""
|
|
135
|
+
stations = view_spec.get("stations") or {}
|
|
136
|
+
station_image_axis = layout[0]
|
|
137
|
+
sign = axes[station_image_axis][1]
|
|
138
|
+
positions = [float(value) for value in stations.get("positions", [])]
|
|
139
|
+
count = int(stations.get("count", 0))
|
|
140
|
+
bounds = image_measure.subject_bounds(reference_mask)
|
|
141
|
+
if count and bounds is None:
|
|
142
|
+
raise ValueError(f"view '{view_spec['name']}': no subject found in the reference image")
|
|
143
|
+
if count:
|
|
144
|
+
low_pixel, high_pixel = (bounds[0], bounds[2]) if station_image_axis == "right" else (bounds[1], bounds[3])
|
|
145
|
+
ends = sorted(ortho_views.pixel_to_coordinate(pixel, station_image_axis, frame, sign)
|
|
146
|
+
for pixel in (low_pixel, high_pixel))
|
|
147
|
+
positions += [ends[0] + (ends[1] - ends[0]) * (index + 0.5) / count for index in range(count)]
|
|
148
|
+
if not positions:
|
|
149
|
+
raise ValueError(f"view '{view_spec['name']}': give stations.count or stations.positions")
|
|
150
|
+
return sorted(set(round(position, 6) for position in positions))
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _interval_metres(extent, image_axis: str, frame, sign: float) -> list:
|
|
154
|
+
"""A pixel extent as a sorted world interval in metres."""
|
|
155
|
+
return sorted(round(ortho_views.pixel_to_coordinate(pixel, image_axis, frame, sign), 5) for pixel in extent)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _measure_station(position: float, context: dict) -> dict:
|
|
159
|
+
"""Measures one station on the reference and the model, and grades it."""
|
|
160
|
+
frame, axes = context["frame"], context["axes"]
|
|
161
|
+
station_image_axis, measured_image_axis, station_axis, measured_axis = context["layout"]
|
|
162
|
+
pixel = ortho_views.coordinate_to_pixel(position, station_image_axis, frame, axes[station_image_axis][1])
|
|
163
|
+
reference_extent = _measure_extent(context["reference_mask"], station_image_axis, pixel)
|
|
164
|
+
model_extent = _measure_extent(context["model_mask"], station_image_axis, pixel)
|
|
165
|
+
record = {"position_m": position, "axis": station_axis, "measures": measured_axis, "pixel": round(pixel, 2)}
|
|
166
|
+
measured_sign = axes[measured_image_axis][1]
|
|
167
|
+
if reference_extent is not None:
|
|
168
|
+
record["reference_px"] = round(reference_extent[1] - reference_extent[0], 2)
|
|
169
|
+
record["reference_m"] = round(record["reference_px"] / frame.pixels_per_metre, 5)
|
|
170
|
+
record["reference_interval_m"] = _interval_metres(reference_extent, measured_image_axis, frame, measured_sign)
|
|
171
|
+
if model_extent is not None:
|
|
172
|
+
record["model_px"] = round(model_extent[1] - model_extent[0], 2)
|
|
173
|
+
record["model_m"] = round(record["model_px"] / frame.pixels_per_metre, 5)
|
|
174
|
+
record["model_interval_m"] = _interval_metres(model_extent, measured_image_axis, frame, measured_sign)
|
|
175
|
+
if context["objects"]:
|
|
176
|
+
section = construction_kit.section_extent(context["objects"], position, station_axis.upper(),
|
|
177
|
+
measured_axis.upper())
|
|
178
|
+
record["model_section_m"] = None if section is None else round(section[1] - section[0], 5)
|
|
179
|
+
if reference_extent is None:
|
|
180
|
+
record["grade"] = "NO_REFERENCE"
|
|
181
|
+
elif model_extent is None:
|
|
182
|
+
record["grade"] = "MISSING"
|
|
183
|
+
else:
|
|
184
|
+
record["delta_px"] = round(record["model_px"] - record["reference_px"], 2)
|
|
185
|
+
record.update(image_measure.grade_delta(record["reference_m"], record["model_m"]))
|
|
186
|
+
record["image_extents"] = {"reference": reference_extent, "model": model_extent}
|
|
187
|
+
return record
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _projected_edges(objects: list, view: str) -> np.ndarray:
|
|
191
|
+
"""Every evaluated mesh edge of the objects projected onto the view's image plane: (E, 2, 2) metres along
|
|
192
|
+
the view's right and up axes."""
|
|
193
|
+
basis = ortho_views.view_basis(view)
|
|
194
|
+
projection = np.column_stack((basis.right, basis.up))
|
|
195
|
+
depsgraph = bpy.context.evaluated_depsgraph_get()
|
|
196
|
+
segments = []
|
|
197
|
+
for obj in objects:
|
|
198
|
+
evaluated = obj.evaluated_get(depsgraph)
|
|
199
|
+
mesh = evaluated.to_mesh()
|
|
200
|
+
if mesh is None:
|
|
201
|
+
evaluated.to_mesh_clear()
|
|
202
|
+
continue
|
|
203
|
+
try:
|
|
204
|
+
coordinates = np.empty(len(mesh.vertices) * 3)
|
|
205
|
+
mesh.vertices.foreach_get("co", coordinates)
|
|
206
|
+
edges = np.empty(len(mesh.edges) * 2, dtype=np.int64)
|
|
207
|
+
mesh.edges.foreach_get("vertices", edges)
|
|
208
|
+
matrix = np.array(evaluated.matrix_world)
|
|
209
|
+
finally:
|
|
210
|
+
evaluated.to_mesh_clear()
|
|
211
|
+
world = coordinates.reshape(-1, 3) @ matrix[:3, :3].T + matrix[:3, 3]
|
|
212
|
+
segments.append((world @ projection)[edges.reshape(-1, 2)])
|
|
213
|
+
return np.concatenate(segments) if segments else np.zeros((0, 2, 2))
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def equal_depth_radius(segments: np.ndarray, corner, interior_angle_degrees: float) -> float:
|
|
217
|
+
"""
|
|
218
|
+
The radius of the circular fillet that cuts a corner exactly as deep as the geometry does: d is the
|
|
219
|
+
distance from the sharp corner to the nearest projected edge, and r = d / (1 / sin(a / 2) - 1) for an
|
|
220
|
+
interior angle a (d = 0.414 r at 90 degrees). Exact for a true fillet, and the honest size of a
|
|
221
|
+
subdivided roll, whose limit curve is not a circle.
|
|
222
|
+
|
|
223
|
+
:param segments: (E, 2, 2) projected edges, metres.
|
|
224
|
+
:param corner: (u, v) of the sharp corner, metres, in the same plane.
|
|
225
|
+
:param interior_angle_degrees: Angle between the two flats inside the shape.
|
|
226
|
+
:returns: The radius in metres.
|
|
227
|
+
"""
|
|
228
|
+
point = np.asarray(corner, dtype=np.float64)
|
|
229
|
+
starts, directions = segments[:, 0], segments[:, 1] - segments[:, 0]
|
|
230
|
+
lengths = np.maximum(np.einsum("ij,ij->i", directions, directions), SEGMENT_LENGTH_GUARD)
|
|
231
|
+
along = np.clip(np.einsum("ij,ij->i", point - starts, directions) / lengths, 0.0, 1.0)
|
|
232
|
+
nearest = starts + directions * along[:, None]
|
|
233
|
+
depth = float(np.min(np.linalg.norm(nearest - point, axis=1)))
|
|
234
|
+
half_angle = np.radians(interior_angle_degrees) / 2.0
|
|
235
|
+
return depth / (1.0 / np.sin(half_angle) - 1.0)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _geometric_model_radius(fit, context: dict):
|
|
239
|
+
"""The model's equal-depth corner radius from its own geometry, or None without a usable corner."""
|
|
240
|
+
if not context["objects"] or fit is None or fit.get("corner") is None:
|
|
241
|
+
return None
|
|
242
|
+
frame = context["frame"]
|
|
243
|
+
column, row = fit["corner"]
|
|
244
|
+
corner = ((column - frame.origin_column) / frame.pixels_per_metre, (frame.origin_row - row) / frame.pixels_per_metre)
|
|
245
|
+
segments = _projected_edges(context["objects"], context["view"])
|
|
246
|
+
if len(segments) == 0:
|
|
247
|
+
return None
|
|
248
|
+
return equal_depth_radius(segments, corner, fit["interior_angle_degrees"])
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _measure_corner(corner_spec: dict, context: dict) -> dict:
|
|
252
|
+
"""
|
|
253
|
+
Fits the same corner on the reference and the model silhouettes and grades the radius. A rendered
|
|
254
|
+
model is graded by its equal-depth radius (model_circle_fit_radius_m keeps the circle fit beside it);
|
|
255
|
+
a captured frame by the circle fit.
|
|
256
|
+
"""
|
|
257
|
+
frame = context["frame"]
|
|
258
|
+
quadrant = corner_spec.get("quadrant", "top_right")
|
|
259
|
+
region = corner_spec.get("region")
|
|
260
|
+
record = {"name": corner_spec.get("name", quadrant), "quadrant": quadrant}
|
|
261
|
+
for source in ("reference", "model"):
|
|
262
|
+
fit = image_measure.corner_radius(context[f"{source}_mask"], quadrant, region)
|
|
263
|
+
record[f"{source}_fit"] = fit
|
|
264
|
+
record[f"{source}_radius_m"] = None if fit is None else round(fit["radius_px"] / frame.pixels_per_metre, 5)
|
|
265
|
+
record["model_circle_fit_radius_m"] = record["model_radius_m"]
|
|
266
|
+
record["model_radius_method"] = CIRCLE_FIT_METHOD
|
|
267
|
+
geometric = _geometric_model_radius(record["model_fit"], context)
|
|
268
|
+
if geometric is not None:
|
|
269
|
+
record["model_radius_m"] = round(geometric, 5)
|
|
270
|
+
record["model_radius_method"] = EQUAL_DEPTH_METHOD
|
|
271
|
+
if record["reference_radius_m"] and record["model_radius_m"] is not None:
|
|
272
|
+
record.update(image_measure.grade_radius(record["reference_radius_m"], record["model_radius_m"]))
|
|
273
|
+
else:
|
|
274
|
+
record["grade"] = "NO_REFERENCE" if not record["reference_radius_m"] else "MISSING"
|
|
275
|
+
return record
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _ramp_profile(gray: np.ndarray, mask: np.ndarray, image_axis: str, pixel: float):
|
|
279
|
+
"""Luminance and mask along one station line (a row for "up" stations, a column for "right")."""
|
|
280
|
+
index = int(math.floor(pixel))
|
|
281
|
+
if image_axis == "up":
|
|
282
|
+
return (gray[index], mask[index]) if 0 <= index < gray.shape[0] else (None, None)
|
|
283
|
+
return (gray[:, index], mask[:, index]) if 0 <= index < gray.shape[1] else (None, None)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _measure_ramp(ramp_spec: dict, context: dict) -> dict:
|
|
287
|
+
"""Compares the shading ramp across a roll on the reference and on the model's studio render."""
|
|
288
|
+
frame, axes = context["frame"], context["axes"]
|
|
289
|
+
axis = str(ramp_spec.get("axis", "")).lower()
|
|
290
|
+
image_axis = "up" if axis == axes["up"][0] else "right" if axis == axes["right"][0] else None
|
|
291
|
+
if image_axis is None:
|
|
292
|
+
raise ValueError(f"ramp '{ramp_spec.get('name')}': axis '{axis}' is not one of the view's image axes")
|
|
293
|
+
pixel = ortho_views.coordinate_to_pixel(float(ramp_spec["position"]), image_axis, frame, axes[image_axis][1])
|
|
294
|
+
record = {"name": ramp_spec.get("name", f"{axis}={ramp_spec['position']}"), "axis": axis,
|
|
295
|
+
"position_m": float(ramp_spec["position"])}
|
|
296
|
+
for source in ("reference", "model"):
|
|
297
|
+
gray, mask = _ramp_profile(context[f"{source}_gray"], context[f"{source}_mask"], image_axis, pixel)
|
|
298
|
+
ramp = None if gray is None else image_measure.luminance_ramp(gray, mask)
|
|
299
|
+
if ramp is not None:
|
|
300
|
+
for side in ("left", "right"):
|
|
301
|
+
ramp[f"{side}_ramp_m"] = round(ramp[f"{side}_ramp_px"] / frame.pixels_per_metre, 5)
|
|
302
|
+
record[source] = ramp
|
|
303
|
+
return record
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _dihedral_report(objects: list, maximum_degrees: float) -> dict:
|
|
307
|
+
"""Largest dihedral angle across smooth (unmarked) edges between smooth faces of the evaluated mesh."""
|
|
308
|
+
report = {}
|
|
309
|
+
depsgraph = bpy.context.evaluated_depsgraph_get()
|
|
310
|
+
for obj in objects:
|
|
311
|
+
edit_mesh = bmesh.new()
|
|
312
|
+
edit_mesh.from_object(obj, depsgraph)
|
|
313
|
+
angles = [math.degrees(edge.calc_face_angle(0.0)) for edge in edit_mesh.edges
|
|
314
|
+
if edge.smooth and len(edge.link_faces) == 2 and all(face.smooth for face in edge.link_faces)]
|
|
315
|
+
edit_mesh.free()
|
|
316
|
+
over = sum(1 for angle in angles if angle > maximum_degrees)
|
|
317
|
+
report[obj.name] = {"smooth_edges": len(angles), "max_dihedral_degrees": round(max(angles, default=0.0), 2),
|
|
318
|
+
"edges_over_limit": over}
|
|
319
|
+
return report
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _reference_panel(rgba: np.ndarray, crop) -> np.ndarray:
|
|
323
|
+
"""The reference composited over white, dimmed outside its crop box."""
|
|
324
|
+
panel = rgba[:, :, :3] * rgba[:, :, 3:4] + (1.0 - rgba[:, :, 3:4])
|
|
325
|
+
if crop is not None:
|
|
326
|
+
inside = image_measure.apply_crop(np.ones(panel.shape[:2], dtype=bool), crop)
|
|
327
|
+
panel[~inside] = panel[~inside] * OUTSIDE_CROP_DIMMING + (1.0 - OUTSIDE_CROP_DIMMING)
|
|
328
|
+
return panel.copy()
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _model_panel(model_rgba: np.ndarray) -> np.ndarray:
|
|
332
|
+
"""The model render (or captured frame) composited over white."""
|
|
333
|
+
return model_rgba[:, :, :3] * model_rgba[:, :, 3:4] + (1.0 - model_rgba[:, :, 3:4])
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _overlay_panel(reference_mask: np.ndarray, model_mask: np.ndarray) -> np.ndarray:
|
|
337
|
+
"""Grey where both silhouettes cover, red reference only, blue model only."""
|
|
338
|
+
panel = np.empty(reference_mask.shape + (3,), dtype=np.float32)
|
|
339
|
+
panel[:] = OVERLAY_EMPTY
|
|
340
|
+
panel[reference_mask & model_mask] = OVERLAY_BOTH
|
|
341
|
+
panel[reference_mask & ~model_mask] = OVERLAY_REFERENCE_ONLY
|
|
342
|
+
panel[~reference_mask & model_mask] = OVERLAY_MODEL_ONLY
|
|
343
|
+
return panel
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _draw_station(panel: np.ndarray, record: dict, station_image_axis: str, extent) -> None:
|
|
347
|
+
"""A thin station line across the panel plus a thick tick over the measured extent."""
|
|
348
|
+
color = GRADE_COLORS.get(record["grade"], GRADE_COLORS["NO_REFERENCE"])
|
|
349
|
+
height, width = panel.shape[:2]
|
|
350
|
+
pixel = record["pixel"]
|
|
351
|
+
if station_image_axis == "up":
|
|
352
|
+
image_measure.draw_segment(panel, (0, pixel), (width - 1, pixel), color, 1)
|
|
353
|
+
if extent is not None:
|
|
354
|
+
image_measure.draw_segment(panel, (extent[0], pixel), (extent[1], pixel), color, 3)
|
|
355
|
+
return
|
|
356
|
+
image_measure.draw_segment(panel, (pixel, 0), (pixel, height - 1), color, 1)
|
|
357
|
+
if extent is not None:
|
|
358
|
+
image_measure.draw_segment(panel, (pixel, extent[0]), (pixel, extent[1]), color, 3)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _write_evidence(path: str, context: dict, stations: list, corners: list) -> str:
|
|
362
|
+
"""Writes the reference | model | overlay evidence image for one view."""
|
|
363
|
+
panels = {"reference": _reference_panel(context["reference_rgba"], context["crop"]),
|
|
364
|
+
"model": _model_panel(context["model_rgba"]),
|
|
365
|
+
"overlay": _overlay_panel(context["reference_mask"], context["model_mask"])}
|
|
366
|
+
station_image_axis = context["layout"][0]
|
|
367
|
+
for name, panel in panels.items():
|
|
368
|
+
for record in stations:
|
|
369
|
+
source = "model" if name == "model" else "reference"
|
|
370
|
+
_draw_station(panel, record, station_image_axis, record["image_extents"][source])
|
|
371
|
+
for corner in corners:
|
|
372
|
+
for source in ("reference", "model"):
|
|
373
|
+
fit = corner.get(f"{source}_fit")
|
|
374
|
+
if fit and fit.get("center") and (name == source or name == "overlay"):
|
|
375
|
+
image_measure.draw_circle(panel, fit["center"], fit["radius_px"], CORNER_COLOR, 2)
|
|
376
|
+
gap = np.ones((panels["reference"].shape[0], 8, 3), dtype=np.float32)
|
|
377
|
+
sheet = np.concatenate((panels["reference"], gap, panels["model"], gap, panels["overlay"]), axis=1)
|
|
378
|
+
return tool_common.save_image(path, sheet)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _model_images(view_spec: dict, context: dict, out_directory: str, spec_directory: str, supersample: int) -> None:
|
|
382
|
+
"""Fills the context with the model's image, mask and luminance: a captured frame or a render."""
|
|
383
|
+
frame = context["frame"]
|
|
384
|
+
captured = _resolve(spec_directory, view_spec.get("frame"))
|
|
385
|
+
if captured:
|
|
386
|
+
rgba = tool_common.load_image(captured)
|
|
387
|
+
if rgba.shape[:2] != (frame.height, frame.width):
|
|
388
|
+
raise ValueError(f"view '{view_spec['name']}': the captured frame must match the reference size")
|
|
389
|
+
context["model_rgba"] = rgba
|
|
390
|
+
context["model_mask"] = image_measure.apply_crop(
|
|
391
|
+
image_measure.subject_mask(rgba, float(view_spec.get("background_tolerance", image_measure.DEFAULT_BACKGROUND_TOLERANCE))), context["crop"])
|
|
392
|
+
context["model_gray"] = image_measure.luminance(rgba)
|
|
393
|
+
return
|
|
394
|
+
name = view_spec["name"]
|
|
395
|
+
silhouette = os.path.join(out_directory, "renders", f"{name}_silhouette.png")
|
|
396
|
+
context["model_mask"] = ortho_views.silhouette_mask(context["objects"], view_spec["view"], frame, silhouette, supersample)
|
|
397
|
+
shaded = ortho_views.render_view(context["objects"], view_spec["view"], frame,
|
|
398
|
+
os.path.join(out_directory, "renders", f"{name}_shaded.png"), "shaded", supersample)
|
|
399
|
+
context["model_rgba"] = shaded
|
|
400
|
+
context["model_gray"] = image_measure.luminance(shaded)
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def measure_view(view_spec: dict, objects: list, out_directory: str, spec_directory: str, supersample: int) -> dict:
|
|
404
|
+
"""
|
|
405
|
+
Measures one reference view: stations, corners and ramps, plus its evidence image.
|
|
406
|
+
|
|
407
|
+
:param view_spec: One entry of the spec's "views".
|
|
408
|
+
:param objects: Model objects (empty when the view uses a captured frame only).
|
|
409
|
+
:param out_directory: Evidence folder.
|
|
410
|
+
:param spec_directory: Folder that relative spec paths start from.
|
|
411
|
+
:param supersample: Render supersampling.
|
|
412
|
+
:returns: The view's report.
|
|
413
|
+
"""
|
|
414
|
+
for key in ("name", "view", "image"):
|
|
415
|
+
if key not in view_spec:
|
|
416
|
+
raise ValueError(f"every view needs '{key}'")
|
|
417
|
+
reference_rgba = tool_common.load_image(_resolve(spec_directory, view_spec["image"]))
|
|
418
|
+
height, width = reference_rgba.shape[:2]
|
|
419
|
+
crop = view_spec.get("crop")
|
|
420
|
+
context = {"frame": ortho_views.frame_from_spec(view_spec, width, height), "crop": crop,
|
|
421
|
+
"objects": [] if view_spec.get("frame") else objects, "reference_rgba": reference_rgba,
|
|
422
|
+
"axes": _image_axes(view_spec["view"]), "view": view_spec["view"]}
|
|
423
|
+
context["reference_mask"] = image_measure.apply_crop(
|
|
424
|
+
image_measure.subject_mask(reference_rgba, float(view_spec.get("background_tolerance", image_measure.DEFAULT_BACKGROUND_TOLERANCE))), crop)
|
|
425
|
+
context["reference_gray"] = image_measure.luminance(reference_rgba)
|
|
426
|
+
context["layout"] = _station_layout(view_spec, context["axes"])
|
|
427
|
+
_model_images(view_spec, context, out_directory, spec_directory, supersample)
|
|
428
|
+
positions = _station_positions(view_spec, context["reference_mask"], context["frame"], context["layout"], context["axes"])
|
|
429
|
+
stations = [_measure_station(position, context) for position in positions]
|
|
430
|
+
corners = [_measure_corner(corner, context) for corner in view_spec.get("corners", [])]
|
|
431
|
+
ramps = [_measure_ramp(ramp, context) for ramp in view_spec.get("ramps", [])]
|
|
432
|
+
evidence = _write_evidence(os.path.join(out_directory, f"stations_{view_spec['name']}.png"), context, stations, corners)
|
|
433
|
+
for record in stations:
|
|
434
|
+
record.pop("image_extents")
|
|
435
|
+
return {"name": view_spec["name"], "view": view_spec["view"], "pixels_per_metre": context["frame"].pixels_per_metre,
|
|
436
|
+
"stations": stations, "corners": corners, "ramps": ramps, "evidence": evidence}
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _summary(views: list) -> dict:
|
|
440
|
+
"""Grade counts and the worst station across every view."""
|
|
441
|
+
counts = {grade: 0 for grade in GRADE_COLORS}
|
|
442
|
+
worst = None
|
|
443
|
+
for view in views:
|
|
444
|
+
for record in view["stations"]:
|
|
445
|
+
counts[record["grade"]] += 1
|
|
446
|
+
if "delta_percent" in record and (worst is None or abs(record["delta_percent"]) > abs(worst["delta_percent"])):
|
|
447
|
+
worst = {"view": view["name"], "position_m": record["position_m"], "delta_percent": record["delta_percent"],
|
|
448
|
+
"delta_m": record["delta_m"]}
|
|
449
|
+
corner_counts = {"MATCH": 0, "WRONG": 0, "MISSING": 0, "NO_REFERENCE": 0}
|
|
450
|
+
for view in views:
|
|
451
|
+
for corner in view["corners"]:
|
|
452
|
+
corner_counts[corner["grade"]] += 1
|
|
453
|
+
return {"stations": counts, "corners": corner_counts, "worst_station": worst}
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def run(options) -> dict:
|
|
457
|
+
"""
|
|
458
|
+
Runs the measurement described by the spec.
|
|
459
|
+
|
|
460
|
+
:param options: Parsed command-line options.
|
|
461
|
+
:returns: The tool result (also written to <out>/stations.json).
|
|
462
|
+
"""
|
|
463
|
+
spec_path = os.path.abspath(options.spec)
|
|
464
|
+
spec_directory = os.path.dirname(spec_path)
|
|
465
|
+
spec = tool_common.load_json(spec_path)
|
|
466
|
+
views_spec = spec.get("views") or []
|
|
467
|
+
if not views_spec:
|
|
468
|
+
raise ValueError("the spec has no views")
|
|
469
|
+
model_path = options.model or _resolve(spec_directory, spec.get("model"))
|
|
470
|
+
tool_common.load_model(model_path)
|
|
471
|
+
needs_model = any(not view.get("frame") for view in views_spec)
|
|
472
|
+
objects = tool_common.resolve_objects(options.objects or spec.get("objects")) if needs_model else []
|
|
473
|
+
out_directory = os.path.abspath(options.out or os.path.join(spec_directory, "stations_evidence"))
|
|
474
|
+
views = [measure_view(view, objects, out_directory, spec_directory, options.supersample) for view in views_spec]
|
|
475
|
+
summary = _summary(views)
|
|
476
|
+
failing = (summary["stations"]["WRONG"] + summary["stations"]["MISSING"]
|
|
477
|
+
+ summary["corners"]["WRONG"] + summary["corners"]["MISSING"])
|
|
478
|
+
report = {"pass": failing == 0, "summary": summary, "views": views,
|
|
479
|
+
"shading_continuity": _dihedral_report(objects, options.max_dihedral) if objects else {},
|
|
480
|
+
"max_dihedral_degrees": options.max_dihedral}
|
|
481
|
+
report["stations_json"] = tool_common.write_json(os.path.join(out_directory, "stations.json"), report)
|
|
482
|
+
return report
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
if __name__ == "__main__":
|
|
486
|
+
tool_common.run_tool(TOOL_NAME, build_parser(), run)
|