@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.
Files changed (56) hide show
  1. package/README.md +3 -2
  2. package/package.json +1 -1
  3. package/skills/bt-blender/SKILL.md +386 -0
  4. package/skills/bt-blender/THIRD_PARTY_NOTICES.md +141 -0
  5. package/skills/bt-blender/references/art-style-and-genre.md +173 -0
  6. package/skills/bt-blender/references/characters-and-creatures.md +644 -0
  7. package/skills/bt-blender/references/environments.md +478 -0
  8. package/skills/bt-blender/references/game-engine-export.md +284 -0
  9. package/skills/bt-blender/references/geometry-nodes.md +447 -0
  10. package/skills/bt-blender/references/hard-surface.md +720 -0
  11. package/skills/bt-blender/references/procedural-generation.md +358 -0
  12. package/skills/bt-blender/references/rigging-and-animation.md +1080 -0
  13. package/skills/bt-blender/references/sculpting-and-retopology.md +544 -0
  14. package/skills/bt-blender/references/uv-and-pbr-materials.md +381 -0
  15. package/skills/bt-blender/references/vehicles.md +632 -0
  16. package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
  17. package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
  18. package/skills/bt-blender/scripts/blender/construction_kit.py +1710 -0
  19. package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
  20. package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
  21. package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
  22. package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
  23. package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
  24. package/skills/bt-blender/scripts/blender/image_measure.py +568 -0
  25. package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
  26. package/skills/bt-blender/scripts/blender/measure_stations.py +486 -0
  27. package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
  28. package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
  29. package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
  30. package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
  31. package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
  32. package/skills/bt-blender/scripts/blender/review_render.py +358 -0
  33. package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
  34. package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
  35. package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
  36. package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
  37. package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
  38. package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
  39. package/skills/bt-blender/scripts/blender/world_gate.py +219 -0
  40. package/skills/bt-blender/scripts/bt-blender.mjs +329 -0
  41. package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
  42. package/skills/bt-gauntlet/SKILL.md +6 -6
  43. package/skills/bt-gauntlet/references/critic-rubrics.md +71 -4
  44. package/skills/bt-gauntlet/references/spec-composition.md +13 -0
  45. package/skills/bt-gauntlet/references/unity-pipeline.md +18 -2
  46. package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
  47. package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
  48. package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
  49. package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
  50. package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
  51. package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
  52. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
  53. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
  54. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
  55. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
  56. package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
@@ -0,0 +1,568 @@
1
+ """
2
+ Image measurement for bt-blender: subject masks, silhouette extents, line and circle fits, luminance ramps,
3
+ station grading and simple drawing for evidence images.
4
+
5
+ Pure numpy: no bpy import, so it is cheap to import from any tool. Every image array here is in image order:
6
+ row 0 is the TOP of the image and column 0 its left edge, the way image editors report pixel positions.
7
+ A continuous pixel coordinate (column, row) has pixel (i, j) covering [i, i + 1) x [j, j + 1), so pixel
8
+ centres sit at +0.5.
9
+ """
10
+ import numpy as np
11
+
12
+ # Station grading bands (percent of the reference value) and the absolute allowance, in metres.
13
+ MATCH_PERCENT = 3.0
14
+ CLOSE_PERCENT = 6.0
15
+ MATCH_ABSOLUTE_METRES = 0.01
16
+
17
+ # Corner radii are graded against their own tolerance: a radius fit is noisier than a width.
18
+ RADIUS_TOLERANCE_PERCENT = 15.0
19
+
20
+ # The border flood fill runs on a grid whose long side is at most this many cells.
21
+ FLOOD_GRID_LONG_SIDE = 512
22
+
23
+ # Share of the image's short side sampled along each border to find the background colour.
24
+ BORDER_SAMPLE_FRACTION = 0.02
25
+
26
+ # Rec. 709 luminance weights.
27
+ LUMINANCE_WEIGHTS = np.array([0.2126, 0.7152, 0.0722], dtype=np.float32)
28
+
29
+ # A corner fit needs at least this many arc points to mean anything.
30
+ MINIMUM_ARC_POINTS = 5
31
+
32
+ # Gauss-Newton refinement steps for the geometric circle fit.
33
+ CIRCLE_REFINE_STEPS = 25
34
+
35
+ # Profile points closer than this to a fitted flat (in pixels) belong to the flat, not to the corner arc.
36
+ FLAT_TOLERANCE_PIXELS = 1.0
37
+
38
+ # Share of a corner region, measured from its inner edges, used to fit the two flats beside the arc.
39
+ FLAT_SAMPLE_FRACTION = 0.3
40
+
41
+ # A luminance ramp ends where the deviation from the plateau falls below this share of its largest value.
42
+ RAMP_END_FRACTION = 0.1
43
+
44
+ # Rows whose largest luminance deviation is below this carry no usable shading.
45
+ MINIMUM_RAMP_CONTRAST = 0.04
46
+
47
+ # Central share of a span used as the luminance plateau.
48
+ PLATEAU_FRACTION = 0.3
49
+
50
+ # How far (0..1 per channel) a pixel may differ from the border colour and still count as background.
51
+ DEFAULT_BACKGROUND_TOLERANCE = 0.08
52
+
53
+ # A luminance ramp needs at least this many subject columns in its row.
54
+ MINIMUM_RAMP_COLUMNS = 8
55
+
56
+ # Drawn circles: at least this many segments, and this many per pixel of radius.
57
+ CIRCLE_MINIMUM_SEGMENTS = 16
58
+ CIRCLE_SEGMENTS_PER_PIXEL = 8
59
+
60
+ # Numeric guards: smallest length or size treated as non-zero, the circle refinement's convergence step,
61
+ # the smallest luminance change treated as a ramp, and a denominator offset for horizontal edges.
62
+ NUMERIC_FLOOR = 1e-12
63
+ CIRCLE_CONVERGENCE = 1e-9
64
+ MINIMUM_RAMP_TOTAL = 1e-6
65
+ DIVISION_GUARD = 1e-30
66
+
67
+
68
+ def linear_to_srgb(values: np.ndarray) -> np.ndarray:
69
+ """
70
+ Applies the sRGB transfer curve: linear light to display-encoded values.
71
+
72
+ :param values: Linear values in 0..1 (any shape).
73
+ :returns: sRGB-encoded values in 0..1, same shape, float32.
74
+ """
75
+ clipped = np.clip(values, 0.0, 1.0).astype(np.float32)
76
+ return np.where(clipped <= 0.0031308, clipped * 12.92, 1.055 * np.power(clipped, 1.0 / 2.4) - 0.055)
77
+
78
+
79
+ def luminance(rgba: np.ndarray) -> np.ndarray:
80
+ """
81
+ Converts an RGB or RGBA image to luminance.
82
+
83
+ :param rgba: float array (height, width, 3 or 4).
84
+ :returns: float32 array (height, width).
85
+ """
86
+ return (rgba[:, :, :3] * LUMINANCE_WEIGHTS).sum(axis=2).astype(np.float32)
87
+
88
+
89
+ def erode(mask: np.ndarray, iterations: int = 1) -> np.ndarray:
90
+ """
91
+ Shrinks a boolean mask by one pixel per iteration (4-neighbourhood).
92
+
93
+ :param mask: Boolean (height, width).
94
+ :param iterations: How many pixels to remove from every edge.
95
+ :returns: The eroded mask.
96
+ """
97
+ result = mask.copy()
98
+ for _ in range(iterations):
99
+ shrunk = result.copy()
100
+ shrunk[1:, :] &= result[:-1, :]
101
+ shrunk[:-1, :] &= result[1:, :]
102
+ shrunk[:, 1:] &= result[:, :-1]
103
+ shrunk[:, :-1] &= result[:, 1:]
104
+ result = shrunk
105
+ return result
106
+
107
+
108
+ def dilate(mask: np.ndarray, iterations: int = 1) -> np.ndarray:
109
+ """
110
+ Grows a boolean mask by one pixel per iteration (4-neighbourhood).
111
+
112
+ :param mask: Boolean (height, width).
113
+ :param iterations: How many pixels to add to every edge.
114
+ :returns: The dilated mask.
115
+ """
116
+ result = mask.copy()
117
+ for _ in range(iterations):
118
+ grown = result.copy()
119
+ grown[1:, :] |= result[:-1, :]
120
+ grown[:-1, :] |= result[1:, :]
121
+ grown[:, 1:] |= result[:, :-1]
122
+ grown[:, :-1] |= result[:, 1:]
123
+ result = grown
124
+ return result
125
+
126
+
127
+ def _block_reduce(mask: np.ndarray, factor: int) -> np.ndarray:
128
+ """Downsamples a boolean mask by an integer factor; a cell is set when most of its pixels are."""
129
+ height, width = mask.shape
130
+ padded_height = -(-height // factor) * factor
131
+ padded_width = -(-width // factor) * factor
132
+ padded = np.zeros((padded_height, padded_width), dtype=np.float32)
133
+ padded[:height, :width] = mask
134
+ blocks = padded.reshape(padded_height // factor, factor, padded_width // factor, factor)
135
+ return blocks.mean(axis=(1, 3)) > 0.5
136
+
137
+
138
+ def connected_to_border(candidates: np.ndarray) -> np.ndarray:
139
+ """
140
+ Flood-fills from the image border through candidate pixels. Runs on a reduced grid for speed, then
141
+ widens the result by one reduced cell so it reaches every full-resolution edge pixel.
142
+
143
+ :param candidates: Boolean (height, width): pixels the fill may pass through.
144
+ :returns: Boolean (height, width): the candidates reachable from the border.
145
+ """
146
+ height, width = candidates.shape
147
+ factor = max(1, int(np.ceil(max(height, width) / FLOOD_GRID_LONG_SIDE)))
148
+ passable = _block_reduce(candidates, factor)
149
+ reached = np.zeros_like(passable)
150
+ reached[0, :], reached[-1, :] = passable[0, :], passable[-1, :]
151
+ reached[:, 0] |= passable[:, 0]
152
+ reached[:, -1] |= passable[:, -1]
153
+ while True:
154
+ grown = dilate(reached) & passable
155
+ if np.array_equal(grown, reached):
156
+ break
157
+ reached = grown
158
+ reached = dilate(reached)
159
+ full = np.repeat(np.repeat(reached, factor, axis=0), factor, axis=1)[:height, :width]
160
+ return candidates & full
161
+
162
+
163
+ def subject_mask(rgba: np.ndarray, background_tolerance: float = DEFAULT_BACKGROUND_TOLERANCE) -> np.ndarray:
164
+ """
165
+ Separates the subject from its background. A transparent image uses its alpha. Otherwise the background
166
+ colour is the median of the image border, and only background-coloured pixels connected to the border
167
+ count as background, so light details enclosed by the subject (logos, highlights) stay subject.
168
+
169
+ :param rgba: float array (height, width, 4), values 0..1.
170
+ :param background_tolerance: Largest per-channel difference (0..1) from the background colour that
171
+ still counts as background.
172
+ :returns: Boolean (height, width), True on the subject.
173
+ """
174
+ alpha = rgba[:, :, 3]
175
+ if alpha.min() < 0.5:
176
+ return alpha > 0.5
177
+ height, width = alpha.shape
178
+ border = max(2, int(min(width, height) * BORDER_SAMPLE_FRACTION))
179
+ strips = np.concatenate((rgba[:border, :, :3].reshape(-1, 3), rgba[-border:, :, :3].reshape(-1, 3),
180
+ rgba[:, :border, :3].reshape(-1, 3), rgba[:, -border:, :3].reshape(-1, 3)))
181
+ 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))
186
+
187
+
188
+ def apply_crop(mask: np.ndarray, crop) -> np.ndarray:
189
+ """
190
+ Clears everything outside a crop box, so labels, rulers and floor lines outside it are ignored.
191
+
192
+ :param mask: Boolean (height, width).
193
+ :param crop: [left, top, right, bottom] in pixels (right / bottom exclusive), or None for no crop.
194
+ :returns: A cropped copy of the mask, same shape.
195
+ """
196
+ if crop is None:
197
+ return mask.copy()
198
+ left, top, right, bottom = (int(round(value)) for value in crop)
199
+ cropped = np.zeros_like(mask)
200
+ cropped[max(0, top):bottom, max(0, left):right] = mask[max(0, top):bottom, max(0, left):right]
201
+ return cropped
202
+
203
+
204
+ def subject_bounds(mask: np.ndarray):
205
+ """
206
+ Bounding box of the subject in continuous pixel coordinates.
207
+
208
+ :param mask: Boolean (height, width).
209
+ :returns: (left, top, right, bottom) with right / bottom exclusive, or None for an empty mask.
210
+ """
211
+ columns = np.flatnonzero(mask.any(axis=0))
212
+ rows = np.flatnonzero(mask.any(axis=1))
213
+ if columns.size == 0:
214
+ return None
215
+ return float(columns[0]), float(rows[0]), float(columns[-1] + 1), float(rows[-1] + 1)
216
+
217
+
218
+ def extent_along_row(mask: np.ndarray, row: float):
219
+ """
220
+ The subject's horizontal extent on one image row.
221
+
222
+ :param mask: Boolean (height, width).
223
+ :param row: Continuous row coordinate; the pixel row containing it is read.
224
+ :returns: (first column, end column) continuous (end exclusive), or None when the row is empty or
225
+ outside the image.
226
+ """
227
+ index = int(np.floor(row))
228
+ if index < 0 or index >= mask.shape[0]:
229
+ return None
230
+ columns = np.flatnonzero(mask[index])
231
+ if columns.size == 0:
232
+ return None
233
+ return float(columns[0]), float(columns[-1] + 1)
234
+
235
+
236
+ def extent_along_column(mask: np.ndarray, column: float):
237
+ """
238
+ The subject's vertical extent on one image column.
239
+
240
+ :param mask: Boolean (height, width).
241
+ :param column: Continuous column coordinate; the pixel column containing it is read.
242
+ :returns: (first row, end row) continuous (end exclusive), or None when the column is empty or outside.
243
+ """
244
+ return extent_along_row(mask.T, column)
245
+
246
+
247
+ def grade_delta(reference_metres: float, model_metres: float) -> dict:
248
+ """
249
+ Grades a model measurement against the reference: MATCH within 3 % or 1 cm, CLOSE within 6 %,
250
+ WRONG beyond.
251
+
252
+ :param reference_metres: The reference value, in metres.
253
+ :param model_metres: The model value, in metres.
254
+ :returns: {"delta_m", "delta_percent", "grade"}; the delta is model minus reference.
255
+ """
256
+ delta = model_metres - reference_metres
257
+ percent = 100.0 * delta / reference_metres if abs(reference_metres) > NUMERIC_FLOOR else float("inf")
258
+ if abs(percent) <= MATCH_PERCENT or abs(delta) <= MATCH_ABSOLUTE_METRES:
259
+ grade = "MATCH"
260
+ elif abs(percent) <= CLOSE_PERCENT:
261
+ grade = "CLOSE"
262
+ else:
263
+ grade = "WRONG"
264
+ return {"delta_m": round(delta, 5), "delta_percent": round(percent, 2), "grade": grade}
265
+
266
+
267
+ def grade_radius(reference_metres: float, model_metres: float) -> dict:
268
+ """
269
+ Grades a corner radius: MATCH within 15 % of the reference radius, WRONG beyond.
270
+
271
+ :param reference_metres: Reference radius in metres.
272
+ :param model_metres: Model radius in metres.
273
+ :returns: {"delta_m", "delta_percent", "grade"}.
274
+ """
275
+ delta = model_metres - reference_metres
276
+ percent = 100.0 * delta / reference_metres if reference_metres > NUMERIC_FLOOR else float("inf")
277
+ grade = "MATCH" if abs(percent) <= RADIUS_TOLERANCE_PERCENT else "WRONG"
278
+ return {"delta_m": round(delta, 5), "delta_percent": round(percent, 2), "grade": grade}
279
+
280
+
281
+ def fit_line(points: np.ndarray):
282
+ """
283
+ Total-least-squares line through 2D points.
284
+
285
+ :param points: (N, 2) array, N >= 2.
286
+ :returns: (point on the line, unit direction), both (2,) arrays.
287
+ """
288
+ centroid = points.mean(axis=0)
289
+ _, _, axes = np.linalg.svd(points - centroid)
290
+ return centroid, axes[0]
291
+
292
+
293
+ def distance_to_line(points: np.ndarray, line_point: np.ndarray, line_direction: np.ndarray) -> np.ndarray:
294
+ """
295
+ Perpendicular distance of 2D points from a line.
296
+
297
+ :param points: (N, 2) array.
298
+ :param line_point: A point on the line.
299
+ :param line_direction: The line's unit direction.
300
+ :returns: (N,) distances.
301
+ """
302
+ offsets = points - line_point
303
+ return np.abs(offsets[:, 0] * line_direction[1] - offsets[:, 1] * line_direction[0])
304
+
305
+
306
+ def fit_circle(points: np.ndarray) -> dict:
307
+ """
308
+ Fits a circle to 2D points: an algebraic (Kasa) fit as the start, refined by Gauss-Newton on the
309
+ geometric distance. The algebraic fit alone under-estimates the radius of a partial arc.
310
+
311
+ :param points: (N, 2) array, N >= 3, not all on one line.
312
+ :returns: {"center": (x, y), "radius", "rms"} in the points' units.
313
+ :raises ValueError: when fewer than three points are given.
314
+ """
315
+ if len(points) < 3:
316
+ raise ValueError("a circle fit needs at least three points")
317
+ x, y = points[:, 0], points[:, 1]
318
+ design = np.column_stack((x, y, np.ones_like(x)))
319
+ solution, *_ = np.linalg.lstsq(design, -(x * x + y * y), rcond=None)
320
+ center = np.array([-solution[0] / 2.0, -solution[1] / 2.0])
321
+ radius = float(np.sqrt(max(center @ center - solution[2], NUMERIC_FLOOR)))
322
+ for _ in range(CIRCLE_REFINE_STEPS):
323
+ offsets = points - center
324
+ distances = np.maximum(np.linalg.norm(offsets, axis=1), NUMERIC_FLOOR)
325
+ residuals = distances - radius
326
+ jacobian = np.column_stack((-offsets[:, 0] / distances, -offsets[:, 1] / distances, -np.ones_like(x)))
327
+ step, *_ = np.linalg.lstsq(jacobian, -residuals, rcond=None)
328
+ center = center + step[:2]
329
+ radius = radius + float(step[2])
330
+ if np.abs(step).max() < CIRCLE_CONVERGENCE:
331
+ break
332
+ rms = float(np.sqrt(np.mean((np.linalg.norm(points - center, axis=1) - radius) ** 2)))
333
+ return {"center": (float(center[0]), float(center[1])), "radius": abs(radius), "rms": rms}
334
+
335
+
336
+ def _top_profile(mask: np.ndarray, columns: np.ndarray) -> np.ndarray:
337
+ """(column centre, top edge row) for every given column that holds subject pixels."""
338
+ points = []
339
+ for column in columns:
340
+ rows = np.flatnonzero(mask[:, column])
341
+ if rows.size:
342
+ points.append((column + 0.5, float(rows[0])))
343
+ return np.array(points, dtype=np.float64).reshape(-1, 2)
344
+
345
+
346
+ def _right_profile(mask: np.ndarray, rows: np.ndarray) -> np.ndarray:
347
+ """(right edge column, row centre) for every given row that holds subject pixels."""
348
+ points = []
349
+ for row in rows:
350
+ columns = np.flatnonzero(mask[row])
351
+ if columns.size:
352
+ points.append((float(columns[-1] + 1), row + 0.5))
353
+ return np.array(points, dtype=np.float64).reshape(-1, 2)
354
+
355
+
356
+ def _top_right_corner(mask: np.ndarray, region) -> dict:
357
+ """Corner fit for the top-right corner of a mask; see corner_radius for the contract."""
358
+ left, top, right, bottom = (int(round(value)) for value in region)
359
+ region_columns = np.arange(max(0, left), min(mask.shape[1], right))
360
+ region_rows = np.arange(max(0, top), min(mask.shape[0], bottom))
361
+ if region_columns.size < 4 or region_rows.size < 4:
362
+ return None
363
+ top_points = _top_profile(mask[:bottom], region_columns)
364
+ side_points = _right_profile(mask[:, :right], region_rows)
365
+ if len(top_points) < 3 or len(side_points) < 3:
366
+ return None
367
+ flat_columns = max(2, int(len(top_points) * FLAT_SAMPLE_FRACTION))
368
+ flat_rows = max(2, int(len(side_points) * FLAT_SAMPLE_FRACTION))
369
+ top_line = fit_line(top_points[:flat_columns])
370
+ side_line = fit_line(side_points[-flat_rows:])
371
+ flats = _flats_corner(top_line, side_line, top_points[:flat_columns], side_points[-flat_rows:])
372
+ profile = np.unique(np.concatenate((top_points, side_points)), axis=0)
373
+ away_from_flats = ((distance_to_line(profile, *top_line) > FLAT_TOLERANCE_PIXELS)
374
+ & (distance_to_line(profile, *side_line) > FLAT_TOLERANCE_PIXELS))
375
+ arc = profile[away_from_flats]
376
+ if len(arc) < MINIMUM_ARC_POINTS:
377
+ return {"radius_px": 0.0, "center": None, "rms_px": 0.0, "arc_points": int(len(arc)), **flats}
378
+ circle = fit_circle(arc)
379
+ return {"radius_px": circle["radius"], "center": circle["center"], "rms_px": circle["rms"],
380
+ "arc_points": int(len(arc)), **flats}
381
+
382
+
383
+ def _flats_corner(top_line: tuple, side_line: tuple, top_flat: np.ndarray, side_flat: np.ndarray) -> dict:
384
+ """
385
+ The sharp corner the two fitted flats meet at, and the angle between them inside the shape: what an
386
+ equal-depth radius is measured from.
387
+
388
+ :returns: {"corner": (column, row) or None when the flats are parallel, "interior_angle_degrees"}.
389
+ """
390
+ (top_point, top_direction), (side_point, side_direction) = top_line, side_line
391
+ system = np.column_stack((top_direction, -side_direction))
392
+ if abs(np.linalg.det(system)) < NUMERIC_FLOOR:
393
+ return {"corner": None, "interior_angle_degrees": None}
394
+ along_top = np.linalg.solve(system, side_point - top_point)[0]
395
+ corner = top_point + along_top * top_direction
396
+ toward_top, toward_side = top_flat.mean(axis=0) - corner, side_flat.mean(axis=0) - corner
397
+ cosine = toward_top @ toward_side / max(np.linalg.norm(toward_top) * np.linalg.norm(toward_side), NUMERIC_FLOOR)
398
+ return {"corner": (float(corner[0]), float(corner[1])),
399
+ "interior_angle_degrees": float(np.degrees(np.arccos(np.clip(cosine, -1.0, 1.0))))}
400
+
401
+
402
+ def corner_radius(mask: np.ndarray, quadrant: str, region=None) -> dict:
403
+ """
404
+ Measures the radius of one rounded corner of a silhouette: the outer profile beside the corner is
405
+ split into the two flats (fitted as lines, so a leaning side still works) and the arc between them,
406
+ and a circle is fitted to the arc.
407
+
408
+ :param mask: Boolean (height, width) silhouette, row 0 at the top.
409
+ :param quadrant: "top_right", "top_left", "bottom_right" or "bottom_left".
410
+ :param region: Optional [left, top, right, bottom] box (pixels) to search in; default is the matching
411
+ quarter of the subject's bounding box.
412
+ :returns: {"radius_px", "center" (column, row) or None, "rms_px", "arc_points", "corner" (column, row)
413
+ where the fitted flats meet, or None, "interior_angle_degrees" between the flats}. A radius of 0 means
414
+ the corner is sharper than the image resolves. None when the region holds no usable outline.
415
+ :raises ValueError: for an unknown quadrant.
416
+ """
417
+ flips = {"top_right": (False, False), "top_left": (False, True),
418
+ "bottom_right": (True, False), "bottom_left": (True, True)}
419
+ if quadrant not in flips:
420
+ raise ValueError(f"unknown corner quadrant '{quadrant}'; use one of {sorted(flips)}")
421
+ flip_rows, flip_columns = flips[quadrant]
422
+ height, width = mask.shape
423
+ bounds = subject_bounds(mask)
424
+ if bounds is None:
425
+ return None
426
+ if region is None:
427
+ left, top, right, bottom = bounds
428
+ middle_column, middle_row = (left + right) / 2.0, (top + bottom) / 2.0
429
+ region = [middle_column if not flip_columns else left, top if not flip_rows else middle_row,
430
+ right if not flip_columns else middle_column, middle_row if not flip_rows else bottom]
431
+ left, top, right, bottom = region
432
+ oriented = mask
433
+ if flip_rows:
434
+ oriented = oriented[::-1, :]
435
+ top, bottom = height - bottom, height - top
436
+ if flip_columns:
437
+ oriented = oriented[:, ::-1]
438
+ left, right = width - right, width - left
439
+ result = _top_right_corner(oriented, (left, top, right, bottom))
440
+ if result is None:
441
+ return result
442
+ for key in ("center", "corner"):
443
+ if result.get(key) is not None:
444
+ column, row = result[key]
445
+ result[key] = (width - column if flip_columns else column, height - row if flip_rows else row)
446
+ return result
447
+
448
+
449
+ def luminance_ramp(gray_row: np.ndarray, mask_row: np.ndarray) -> dict:
450
+ """
451
+ Reads how shading changes across a surface on one image row. A rounded roll shades as a gradual ramp
452
+ roughly as wide as its radius; a faceted or sharp edge changes in one or two pixels.
453
+
454
+ :param gray_row: Luminance values along the row.
455
+ :param mask_row: Boolean subject mask along the row.
456
+ :returns: {"left_ramp_px", "right_ramp_px", "left_step_fraction", "right_step_fraction"}. A step
457
+ fraction near 1 means the whole change happens in one pixel step (a crease); a small one means a
458
+ smooth ramp. None when the row has no subject or no usable shading contrast.
459
+ """
460
+ columns = np.flatnonzero(mask_row)
461
+ if columns.size < MINIMUM_RAMP_COLUMNS:
462
+ return None
463
+ # Skip one pixel at each silhouette edge: it is blended with the background by anti-aliasing.
464
+ span = gray_row[columns[0] + 1:columns[-1]]
465
+ plateau_half = max(1, int(len(span) * PLATEAU_FRACTION / 2))
466
+ middle = len(span) // 2
467
+ plateau = float(np.median(span[middle - plateau_half:middle + plateau_half + 1]))
468
+ deviation = np.abs(span - plateau)
469
+ if deviation.max() < MINIMUM_RAMP_CONTRAST:
470
+ return None
471
+ result = {}
472
+ for side, ordered in (("left", span[:middle]), ("right", span[middle:][::-1])):
473
+ side_deviation = np.abs(ordered - plateau)
474
+ largest = side_deviation.max()
475
+ if largest < MINIMUM_RAMP_CONTRAST:
476
+ result[f"{side}_ramp_px"], result[f"{side}_step_fraction"] = 0, None
477
+ continue
478
+ inside = np.flatnonzero(side_deviation < largest * RAMP_END_FRACTION)
479
+ ramp_end = int(inside[0]) if inside.size else len(ordered)
480
+ ramp = ordered[:ramp_end + 1]
481
+ steps = np.abs(np.diff(ramp))
482
+ total = abs(float(ramp[0]) - float(ramp[-1]))
483
+ result[f"{side}_ramp_px"] = ramp_end
484
+ result[f"{side}_step_fraction"] = round(float(steps.max()) / total, 3) if total > MINIMUM_RAMP_TOTAL else None
485
+ return result
486
+
487
+
488
+ def gaussian_blur(values: np.ndarray, sigma_pixels: float) -> np.ndarray:
489
+ """
490
+ Separable Gaussian blur of a 2D array, edges extended.
491
+
492
+ :param values: (height, width) float array.
493
+ :param sigma_pixels: Standard deviation in pixels; 0 or less returns a copy.
494
+ :returns: The blurred array.
495
+ """
496
+ if sigma_pixels <= 0:
497
+ return values.astype(np.float32).copy()
498
+ radius = int(np.ceil(3.0 * sigma_pixels))
499
+ offsets = np.arange(-radius, radius + 1, dtype=np.float32)
500
+ kernel = np.exp(-0.5 * (offsets / sigma_pixels) ** 2)
501
+ kernel /= kernel.sum()
502
+ padded = np.pad(values.astype(np.float32), radius, mode="edge")
503
+ rows_blurred = sum(weight * padded[:, index:index + values.shape[1]] for index, weight in enumerate(kernel))
504
+ return sum(weight * rows_blurred[index:index + values.shape[0], :] for index, weight in enumerate(kernel))
505
+
506
+
507
+ def fill_polygon(height: int, width: int, polygon: np.ndarray) -> np.ndarray:
508
+ """
509
+ Rasterises a closed polygon (even-odd rule, sampled at pixel centres).
510
+
511
+ :param height: Mask height in pixels.
512
+ :param width: Mask width in pixels.
513
+ :param polygon: (N, 2) array of (column, row) vertices in continuous pixel coordinates.
514
+ :returns: Boolean (height, width) mask.
515
+ """
516
+ rows, columns = np.mgrid[0:height, 0:width]
517
+ sample_columns, sample_rows = columns + 0.5, rows + 0.5
518
+ inside = np.zeros((height, width), dtype=bool)
519
+ previous = polygon[-1]
520
+ for current in polygon:
521
+ spans_row = (current[1] > sample_rows) != (previous[1] > sample_rows)
522
+ crossing = (previous[0] - current[0]) * (sample_rows - current[1]) / (previous[1] - current[1] + DIVISION_GUARD) + current[0]
523
+ inside ^= spans_row & (sample_columns < crossing)
524
+ previous = current
525
+ return inside
526
+
527
+
528
+ def draw_segment(image: np.ndarray, start, end, color, thickness: int = 1) -> None:
529
+ """
530
+ Draws a straight segment into an RGB(A) float image in place.
531
+
532
+ :param image: (height, width, 3 or 4) float array.
533
+ :param start: (column, row) start point.
534
+ :param end: (column, row) end point.
535
+ :param color: RGB tuple 0..1.
536
+ :param thickness: Line thickness in pixels.
537
+ """
538
+ length = max(abs(end[0] - start[0]), abs(end[1] - start[1]), 1.0)
539
+ steps = np.linspace(0.0, 1.0, int(length * 2) + 2)
540
+ columns = start[0] + (end[0] - start[0]) * steps
541
+ rows = start[1] + (end[1] - start[1]) * steps
542
+ _stamp(image, columns, rows, color, thickness)
543
+
544
+
545
+ def draw_circle(image: np.ndarray, center, radius: float, color, thickness: int = 1) -> None:
546
+ """
547
+ Draws a circle outline into an RGB(A) float image in place.
548
+
549
+ :param image: (height, width, 3 or 4) float array.
550
+ :param center: (column, row) centre.
551
+ :param radius: Radius in pixels.
552
+ :param color: RGB tuple 0..1.
553
+ :param thickness: Line thickness in pixels.
554
+ """
555
+ angles = np.linspace(0.0, 2.0 * np.pi, max(CIRCLE_MINIMUM_SEGMENTS, int(radius * CIRCLE_SEGMENTS_PER_PIXEL)))
556
+ _stamp(image, center[0] + radius * np.cos(angles), center[1] + radius * np.sin(angles), color, thickness)
557
+
558
+
559
+ def _stamp(image: np.ndarray, columns: np.ndarray, rows: np.ndarray, color, thickness: int) -> None:
560
+ """Paints square dots of the given thickness at continuous pixel positions, clipped to the image."""
561
+ height, width = image.shape[:2]
562
+ half = thickness // 2
563
+ for row_offset in range(-half, thickness - half):
564
+ for column_offset in range(-half, thickness - half):
565
+ pixel_rows = np.floor(rows).astype(int) + row_offset
566
+ pixel_columns = np.floor(columns).astype(int) + column_offset
567
+ keep = (pixel_rows >= 0) & (pixel_rows < height) & (pixel_columns >= 0) & (pixel_columns < width)
568
+ image[pixel_rows[keep], pixel_columns[keep], :3] = color