@babylonjs-toolkit/agent 1.2.16 → 1.2.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +3 -2
  2. package/package.json +1 -1
  3. package/skills/bt-blender/SKILL.md +448 -0
  4. package/skills/bt-blender/THIRD_PARTY_NOTICES.md +141 -0
  5. package/skills/bt-blender/references/art-style-and-genre.md +173 -0
  6. package/skills/bt-blender/references/characters-and-creatures.md +644 -0
  7. package/skills/bt-blender/references/environments.md +478 -0
  8. package/skills/bt-blender/references/game-engine-export.md +284 -0
  9. package/skills/bt-blender/references/geometry-nodes.md +447 -0
  10. package/skills/bt-blender/references/hard-surface.md +724 -0
  11. package/skills/bt-blender/references/procedural-generation.md +358 -0
  12. package/skills/bt-blender/references/rigging-and-animation.md +1080 -0
  13. package/skills/bt-blender/references/sculpting-and-retopology.md +544 -0
  14. package/skills/bt-blender/references/uv-and-pbr-materials.md +381 -0
  15. package/skills/bt-blender/references/vehicles.md +637 -0
  16. package/skills/bt-blender/scripts/blender/__pycache__/construction_kit.cpython-313.pyc +0 -0
  17. package/skills/bt-blender/scripts/blender/__pycache__/geometry_nodes_builders.cpython-313.pyc +0 -0
  18. package/skills/bt-blender/scripts/blender/__pycache__/image_measure.cpython-313.pyc +0 -0
  19. package/skills/bt-blender/scripts/blender/__pycache__/reference_traces.cpython-313.pyc +0 -0
  20. package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
  21. package/skills/bt-blender/scripts/blender/blueprint.py +293 -0
  22. package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
  23. package/skills/bt-blender/scripts/blender/construction_kit.py +1770 -0
  24. package/skills/bt-blender/scripts/blender/coverage_check.py +221 -0
  25. package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
  26. package/skills/bt-blender/scripts/blender/evidence_sheet.py +243 -0
  27. package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
  28. package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
  29. package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
  30. package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
  31. package/skills/bt-blender/scripts/blender/image_measure.py +917 -0
  32. package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
  33. package/skills/bt-blender/scripts/blender/measure_stations.py +496 -0
  34. package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
  35. package/skills/bt-blender/scripts/blender/overlay_sheet.py +238 -0
  36. package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
  37. package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
  38. package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
  39. package/skills/bt-blender/scripts/blender/reference_traces.py +344 -0
  40. package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
  41. package/skills/bt-blender/scripts/blender/review_render.py +358 -0
  42. package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
  43. package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
  44. package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
  45. package/skills/bt-blender/scripts/blender/trace.py +283 -0
  46. package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
  47. package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
  48. package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
  49. package/skills/bt-blender/scripts/blender/world_gate.py +231 -0
  50. package/skills/bt-blender/scripts/bt-blender.mjs +333 -0
  51. package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
  52. package/skills/bt-execute/SKILL.md +2 -1
  53. package/skills/bt-gauntlet/SKILL.md +30 -20
  54. package/skills/bt-gauntlet/references/critic-rubrics.md +106 -7
  55. package/skills/bt-gauntlet/references/loop-templates.md +23 -3
  56. package/skills/bt-gauntlet/references/spec-composition.md +20 -1
  57. package/skills/bt-gauntlet/references/target-images.md +27 -0
  58. package/skills/bt-gauntlet/references/unity-pipeline.md +41 -4
  59. package/skills/bt-gauntlet/references/workspace.md +90 -6
  60. package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
  61. package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
  62. package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
  63. package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
  64. package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
  65. package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
  66. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
  67. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
  68. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
  69. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
  70. package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
@@ -0,0 +1,1770 @@
1
+ """
2
+ bt-blender construction kit: build professional forms in headless Blender from measurements instead of
3
+ stacking primitives. Import it from a build script:
4
+
5
+ import sys; sys.path.insert(0, "<skilldir>/scripts/blender")
6
+ import construction_kit as kit
7
+
8
+ kit.clear_default_scene()
9
+ section = kit.rounded_section(0.42, 0.30, 0.06, 0.02, segments=5)
10
+ body = kit.loft("Body", [(y, section) for y in (-0.5, 0.0, 0.5)])
11
+
12
+ What is in it, by form language:
13
+ - rounded, flowing forms: rounded_section + loft (sections with per-station corner radii; quad caps),
14
+ profile_spin, curve_tube, design_line_cage (a quad cage on named design lines, sharpness per line) +
15
+ cage_audit (poles, non-quads, edge ratio), subdivision_cage (holding loops, creases, shrink correction),
16
+ sdf_inflate (moulded parts from one side-view mask);
17
+ - faceted / boxy forms: bevel_edges (multi-segment, weight-limited, hardened normals);
18
+ - finishing: shade_smooth (sharp only on design lines), weld (keeps split normals), mirror,
19
+ apply_modifiers (realises Geometry Nodes instances first, so none are dropped), smart_unwrap;
20
+ - shared part operations the domain modules build on: boolean_cut (every cutter in one volume-checked
21
+ cut, rim edges returned), radial_array (copies round an axis), lod_chain (decimated LODs that keep
22
+ LOD0's custom normals);
23
+ - measuring: world_vertices, section_points, section_extent, evaluated_volume, edges_between;
24
+ - blueprint and traces: load_blueprint (the reference views as image planes, from the `blueprint` tool),
25
+ load_traces (traced outlines and design curves, from the `trace` tool) and stamp_traces (marks the parts
26
+ built on them; a spec's "require_traces" gates on the stamp).
27
+
28
+ Everything works on data (bmesh, mesh attributes, modifiers) except smart_unwrap, which needs the UV
29
+ operator. Lengths are metres; Blender is Z-up and the model faces -Y (glTF / BabylonJS forward).
30
+
31
+ Technique credits (ideas re-expressed, no code copied): the loft / profile_spin / curve_tube toolbox and
32
+ apply_modifiers follow majidmanzarpour/blender-game-skills (build_template.py); the rounded-rectangle
33
+ section with keystone follows NASA OpenVSP's cross-section definitions. sdf_inflate ports the
34
+ superellipse inflate field of colinurbs/claude-modeling-skills -- see sdf_inflate for its notice.
35
+ """
36
+ import math
37
+ import os
38
+ import warnings
39
+
40
+ import bmesh
41
+ import bpy
42
+ import numpy as np
43
+ from mathutils import Matrix, Vector
44
+ from mathutils.kdtree import KDTree
45
+
46
+ import geometry_nodes_builders as gn
47
+ import reference_traces
48
+
49
+ # A corner radius of 0 becomes a fillet this share of the section size, so every section keeps the same
50
+ # point count for lofting. Mark that edge sharp if it must read crisp.
51
+ MINIMUM_RADIUS_FRACTION = 0.001
52
+
53
+ # Tangent points stop this share short of a neighbouring point, so no two section points coincide.
54
+ TANGENT_CLEARANCE = 0.001
55
+
56
+ # Positions closer than this (metres) count as on the plane / on the axis.
57
+ GEOMETRY_EPSILON = 1e-9
58
+
59
+ # Default iteration limit and convergence tolerance of the subdivision shrink correction.
60
+ SHRINK_ITERATIONS = 4
61
+ SHRINK_TOLERANCE_PERCENT = 0.5
62
+
63
+ # Relative scale step used to measure how the stations respond to each other during shrink correction.
64
+ SHRINK_RESPONSE_STEP = 0.01
65
+
66
+ # Holding loops: a two-segment bevel at profile 1.0 rolls the subdivided corner to a radius of
67
+ # HOLDING_RADIUS_PER_WIDTH x the loop width at every subdivision level, and keeps the outer size exact.
68
+ # (Measured on Blender 5.3.0; a one-segment loop gave 2.3x to 5.2x the width, depending on the width.)
69
+ HOLDING_SEGMENTS = 2
70
+ HOLDING_PROFILE = 1.0
71
+ HOLDING_RADIUS_PER_WIDTH = 0.57
72
+
73
+ # Clamp Overlap check: the loops are re-evaluated at this share of their width (never clamped), and a loop
74
+ # narrower than this share of the asked width counts as clamped. At most this many fold spots are reported.
75
+ HOLDING_PROBE_SHARE = 0.01
76
+ HOLDING_CLAMP_RATIO = 0.999
77
+ MAXIMUM_REPORTED_FOLDS = 5
78
+
79
+ # A bevel vertex that moves less than this (metres) between widths is not part of the bevel.
80
+ HOLDING_TRAVEL_EPSILON = 1e-9
81
+
82
+ # Booleans: coplanar faces within this angle are merged after the cut (degrees), and the material slot the
83
+ # cutters bring into the cut so its rim can be found.
84
+ BOOLEAN_CLEANUP_DEGREES = 1.0
85
+ CUTTER_MATERIAL_SLOT = 1
86
+
87
+ # Two face sets touch along an edge shared by one face of each.
88
+ EDGE_FACE_COUNT = 2
89
+
90
+ # LOD chains: Data Transfer loop mapping for LOD0's custom normals (nearest corner of the nearest face,
91
+ # matched by face normal), and the suffix Unity's importer builds an LOD Group from.
92
+ LOD_NORMAL_TRANSFER_MAPPING = "POLYINTERP_NEAREST"
93
+ LOD_SUFFIX = "_LOD"
94
+
95
+ # Largest number of voxels sdf_inflate evaluates; a finer voxel needs a smaller part or a bigger budget.
96
+ SDF_MAXIMUM_VOXELS = 12_000_000
97
+
98
+ # Default sdf_inflate resolution: the part's longest dimension divided by this.
99
+ SDF_DEFAULT_DIVISIONS = 120
100
+
101
+ # Empty voxels kept around the sdf_inflate part on every side, so the surface closes inside the grid.
102
+ SDF_PADDING_VOXELS = 2
103
+
104
+ # Cap styles of loft and curve_tube. A quad cap puts its grid corners where the ring turns most, measured
105
+ # across this share of the ring's vertex count on either side (so a rounded corner's middle beats its ends);
106
+ # turning sums are compared to this many decimals, so a tie goes to the most nearly square grid.
107
+ CAP_STYLES = ("quad", "fan")
108
+ CAP_CORNER_WINDOW_SHARE = 1.0 / 8.0
109
+ CAP_SCORE_DECIMALS = 6
110
+
111
+ # Design-line cages: a crease at or above CREASE_CRISP is a crisp line (also marked sharp); each fairing pass
112
+ # moves a line's interior points this share of the way towards their neighbours' mean; a regular cage vertex
113
+ # has four edges, and every cage face is a quad.
114
+ CREASE_CRISP = 1.0
115
+ FAIRING_STEP = 0.25
116
+ CAGE_REGULAR_VALENCE = 4
117
+ QUAD_CORNERS = 4
118
+
119
+ # Knot spacing exponent of a centripetal Catmull-Rom spline (0.5; 0 is uniform, 1 is chordal).
120
+ CENTRIPETAL_EXPONENT = 0.5
121
+
122
+ AXIS_INDEX = {"X": 0, "Y": 1, "Z": 2}
123
+
124
+ # Collection the `blueprint` tool puts the reference image planes, view cameras and reference box in.
125
+ BLUEPRINT_COLLECTION = "_Blueprint"
126
+
127
+
128
+ # --- scene -------------------------------------------------------------------------------------------------
129
+
130
+ def clear_default_scene() -> None:
131
+ """
132
+ Empties the scene. `--factory-startup` loads the default Cube, Camera and Light; a build that keeps
133
+ them ships a stray cube, and every "all meshes" measurement includes it.
134
+ """
135
+ bpy.ops.wm.read_factory_settings(use_empty=True)
136
+
137
+
138
+ def _link_new_object(name: str, mesh: bpy.types.Mesh) -> bpy.types.Object:
139
+ """Creates an object for a mesh and links it to the scene collection."""
140
+ obj = bpy.data.objects.new(name, mesh)
141
+ bpy.context.scene.collection.objects.link(obj)
142
+ return obj
143
+
144
+
145
+ def _object_from_bmesh(name: str, edit_mesh: bmesh.types.BMesh) -> bpy.types.Object:
146
+ """Writes a bmesh into a new mesh object (freeing the bmesh) and links it to the scene."""
147
+ mesh = bpy.data.meshes.new(name)
148
+ edit_mesh.to_mesh(mesh)
149
+ edit_mesh.free()
150
+ return _link_new_object(name, mesh)
151
+
152
+
153
+ # --- sections and lofts ---------------------------------------------------------------------------------------
154
+
155
+ def _fillet(corner: np.ndarray, toward_previous: np.ndarray, toward_next: np.ndarray, radius: float,
156
+ segments: int) -> list:
157
+ """
158
+ Points of a circular fillet replacing a corner, from the tangent point on the incoming edge to the
159
+ tangent point on the outgoing edge.
160
+
161
+ :param corner: The sharp corner (2,).
162
+ :param toward_previous: Unit direction from the corner to the previous point.
163
+ :param toward_next: Unit direction from the corner to the next point.
164
+ :param radius: Fillet radius (already clamped to fit).
165
+ :param segments: Arc segments; segments + 1 points are returned.
166
+ :returns: List of (x, z) tuples.
167
+ """
168
+ half_angle = math.acos(float(np.clip(toward_previous @ toward_next, -1.0, 1.0))) / 2.0
169
+ tangent_distance = radius / math.tan(half_angle)
170
+ start = corner + toward_previous * tangent_distance
171
+ end = corner + toward_next * tangent_distance
172
+ bisector = toward_previous + toward_next
173
+ bisector /= np.linalg.norm(bisector)
174
+ center = corner + bisector * (radius / math.sin(half_angle))
175
+ start_angle = math.atan2(start[1] - center[1], start[0] - center[0])
176
+ end_angle = math.atan2(end[1] - center[1], end[0] - center[0])
177
+ sweep = (end_angle - start_angle + math.pi) % (2.0 * math.pi) - math.pi
178
+ return [(float(center[0] + radius * math.cos(start_angle + sweep * step / segments)),
179
+ float(center[1] + radius * math.sin(start_angle + sweep * step / segments)))
180
+ for step in range(segments + 1)]
181
+
182
+
183
+ def _radius_limit(half_angle: float, tangent_room: float) -> float:
184
+ """Largest fillet radius whose tangent points fit within the given room along both edges."""
185
+ return tangent_room * math.tan(half_angle)
186
+
187
+
188
+ def rounded_section(width: float, height: float, corner_radius_top: float, corner_radius_bottom: float,
189
+ segments: int = 5, keystone: float = 1.0) -> list:
190
+ """
191
+ A closed rounded-trapezoid cross-section (OpenVSP "rounded rectangle" with keystone), for lofting
192
+ rounded hard-surface bodies. Radii are dimensional (metres), not fractions, so they can be set straight
193
+ from a corner-radius measurement. The section spans x = -width/2 .. width/2 at its widest and
194
+ z = 0 .. height; move it with translate_section.
195
+
196
+ Every section with the same `segments` has the same point count and the same start point (top
197
+ centre, then clockwise towards +x), so any such sections loft together.
198
+
199
+ :param width: Widest width in metres (the top width when keystone <= 1, else the bottom width).
200
+ :param height: Height in metres.
201
+ :param corner_radius_top: Radius where the top rolls into the sides, metres. Clamped to fit.
202
+ :param corner_radius_bottom: Radius of the lower corners, metres. Clamped to fit.
203
+ :param segments: Arc segments per corner (5 per 90 degrees keeps the silhouette error under a
204
+ pixel for most game views).
205
+ :param keystone: Bottom width / top width. Below 1 narrows the bottom, above 1 narrows the top.
206
+ :returns: Closed list of (x, z) points; the last point does not repeat the first.
207
+ :raises ValueError: for non-positive sizes, segments or keystone.
208
+ """
209
+ if width <= 0 or height <= 0 or segments < 1 or keystone <= 0:
210
+ raise ValueError("rounded_section needs width > 0, height > 0, segments >= 1 and keystone > 0")
211
+ top_half = width / 2.0 if keystone <= 1.0 else width / (2.0 * keystone)
212
+ bottom_half = width / 2.0 * keystone if keystone <= 1.0 else width / 2.0
213
+ top_corner = np.array([top_half, height])
214
+ bottom_corner = np.array([bottom_half, 0.0])
215
+ side = bottom_corner - top_corner
216
+ side_length = float(np.linalg.norm(side))
217
+ side_down = side / side_length
218
+ minimum_radius = MINIMUM_RADIUS_FRACTION * min(width, height)
219
+ room = 1.0 - TANGENT_CLEARANCE
220
+
221
+ top_half_angle = math.acos(float(np.clip(np.array([-1.0, 0.0]) @ side_down, -1.0, 1.0))) / 2.0
222
+ bottom_half_angle = math.acos(float(np.clip(-side_down @ np.array([-1.0, 0.0]), -1.0, 1.0))) / 2.0
223
+ top_radius = max(corner_radius_top, minimum_radius)
224
+ bottom_radius = max(corner_radius_bottom, minimum_radius)
225
+ # Each corner may use the whole flat beside it, and the side is shared in proportion to the demand.
226
+ top_tangent = top_radius / math.tan(top_half_angle)
227
+ bottom_tangent = bottom_radius / math.tan(bottom_half_angle)
228
+ side_share = min(1.0, room * side_length / (top_tangent + bottom_tangent))
229
+ top_radius = min(top_radius * side_share, _radius_limit(top_half_angle, room * top_half))
230
+ bottom_radius = min(bottom_radius * side_share, _radius_limit(bottom_half_angle, room * bottom_half))
231
+
232
+ top_arc = _fillet(top_corner, np.array([-1.0, 0.0]), side_down, top_radius, segments)
233
+ bottom_arc = _fillet(bottom_corner, -side_down, np.array([-1.0, 0.0]), bottom_radius, segments)
234
+ right_half = [(0.0, float(height))] + top_arc + bottom_arc + [(0.0, 0.0)]
235
+ left_half = [(-x, z) for x, z in reversed(top_arc + bottom_arc)]
236
+ return right_half + left_half
237
+
238
+
239
+ def translate_section(points: list, x: float = 0.0, z: float = 0.0) -> list:
240
+ """
241
+ Moves a section, e.g. to set a station's floor height.
242
+
243
+ :param points: (x, z) points.
244
+ :param x: Offset along X in metres.
245
+ :param z: Offset along Z in metres.
246
+ :returns: The moved points.
247
+ """
248
+ return [(point_x + x, point_z + z) for point_x, point_z in points]
249
+
250
+
251
+ def _ring_faces(edit_mesh: bmesh.types.BMesh, first_ring: list, second_ring: list) -> list:
252
+ """Quad strip between two closed rings of equal length."""
253
+ count = len(first_ring)
254
+ return [edit_mesh.faces.new((first_ring[i], first_ring[(i + 1) % count], second_ring[(i + 1) % count], second_ring[i]))
255
+ for i in range(count)]
256
+
257
+
258
+ def _turning_angles(points: np.ndarray, window: int) -> np.ndarray:
259
+ """How far a closed polyline turns at each point, measured between the points `window` steps either side."""
260
+ incoming = points - np.roll(points, window, axis=0)
261
+ outgoing = np.roll(points, -window, axis=0) - points
262
+ lengths = np.maximum(np.linalg.norm(incoming, axis=1) * np.linalg.norm(outgoing, axis=1), GEOMETRY_EPSILON)
263
+ return np.arccos(np.clip(np.einsum("ij,ij->i", incoming, outgoing) / lengths, -1.0, 1.0))
264
+
265
+
266
+ def _quad_cap_layout(points: np.ndarray) -> tuple:
267
+ """
268
+ Where a quad grid cap puts its four corners on a ring of even length: the start index and the two side
269
+ lengths (opposite sides are equal), chosen so the corners sit on the ring's sharpest turns, the most
270
+ nearly square grid winning a tie.
271
+ """
272
+ count = len(points)
273
+ turning = _turning_angles(points, max(1, round(count * CAP_CORNER_WINDOW_SHARE)))
274
+ half = count // 2
275
+ best_score, best_layout = None, None
276
+ for start in range(count):
277
+ for columns in range(1, half):
278
+ rows = half - columns
279
+ corners = [start, start + columns, start + half, start + half + columns]
280
+ score = (round(float(turning[[corner % count for corner in corners]].sum()), CAP_SCORE_DECIMALS),
281
+ -abs(columns - rows))
282
+ if best_score is None or score > best_score:
283
+ best_score, best_layout = score, (start, columns, rows)
284
+ return best_layout
285
+
286
+
287
+ def _quad_cap(edit_mesh: bmesh.types.BMesh, ring: list) -> None:
288
+ """
289
+ Closes a ring of even length with a grid of quads (a Coons patch between its four sides), so the cap
290
+ has no pole: the four grid corners on the rim get valence 3 and every other vertex valence 4.
291
+ """
292
+ count = len(ring)
293
+ start, columns, rows = _quad_cap_layout(np.array([vertex.co for vertex in ring]))
294
+ ordered = ring[start:] + ring[:start]
295
+ grid = [[None] * (rows + 1) for _ in range(columns + 1)]
296
+ for i in range(columns + 1):
297
+ grid[i][0] = ordered[i]
298
+ grid[i][rows] = ordered[2 * columns + rows - i]
299
+ for j in range(rows + 1):
300
+ grid[columns][j] = ordered[columns + j]
301
+ grid[0][j] = ordered[(count - j) % count]
302
+ corner_00, corner_10 = grid[0][0].co, grid[columns][0].co
303
+ corner_01, corner_11 = grid[0][rows].co, grid[columns][rows].co
304
+ for i in range(1, columns):
305
+ across = i / columns
306
+ for j in range(1, rows):
307
+ along = j / rows
308
+ position = ((1.0 - along) * grid[i][0].co + along * grid[i][rows].co
309
+ + (1.0 - across) * grid[0][j].co + across * grid[columns][j].co
310
+ - ((1.0 - across) * (1.0 - along) * corner_00 + across * (1.0 - along) * corner_10
311
+ + (1.0 - across) * along * corner_01 + across * along * corner_11))
312
+ grid[i][j] = edit_mesh.verts.new(position)
313
+ for i in range(columns):
314
+ for j in range(rows):
315
+ edit_mesh.faces.new((grid[i][j], grid[i + 1][j], grid[i + 1][j + 1], grid[i][j + 1]))
316
+
317
+
318
+ def _fan_cap(edit_mesh: bmesh.types.BMesh, ring: list) -> None:
319
+ """Closes a ring with a triangle fan around its centroid (one pole of valence len(ring))."""
320
+ center = edit_mesh.verts.new(sum((vertex.co for vertex in ring), Vector()) / len(ring))
321
+ for i in range(len(ring)):
322
+ edit_mesh.faces.new((ring[i], ring[(i + 1) % len(ring)], center))
323
+
324
+
325
+ def _cap(edit_mesh: bmesh.types.BMesh, ring: list, cap_style: str) -> None:
326
+ """
327
+ Closes a ring flat and marks its rim edges sharp: a quad grid for "quad" when the ring has an even
328
+ number of vertices, otherwise a triangle fan.
329
+ """
330
+ if cap_style == "quad" and len(ring) % 2 == 0:
331
+ _quad_cap(edit_mesh, ring)
332
+ else:
333
+ _fan_cap(edit_mesh, ring)
334
+ for i in range(len(ring)):
335
+ edit_mesh.edges.get((ring[i], ring[(i + 1) % len(ring)])).smooth = False
336
+
337
+
338
+ def _check_cap_style(cap_style: str) -> None:
339
+ """Raises ValueError for a cap style the kit does not know."""
340
+ if cap_style not in CAP_STYLES:
341
+ raise ValueError(f"cap_style must be one of {CAP_STYLES}; got {cap_style!r}")
342
+
343
+
344
+ def loft(name: str, stations: list, cap_ends: bool = True, cap_style: str = "quad") -> bpy.types.Object:
345
+ """
346
+ Lofts cross-sections placed at stations along Y into one closed, smooth-shaded quad body. Build the
347
+ sections from measurements (width from the top view, height from the side view, corner radii from the
348
+ front view) and put a station at every place the form changes. Consecutive sections are joined
349
+ straight (no interpolating curve), so the body never bulges past a measured station.
350
+
351
+ :param name: Object and mesh name.
352
+ :param stations: List of (y, section_points); section_points are (x, z) tuples, all sections with
353
+ the same count and the same start point (rounded_section guarantees both). Y must increase.
354
+ :param cap_ends: Close both ends with flat caps (their rims are marked sharp).
355
+ :param cap_style: "quad" (default): a grid of quads with its four corners on the section's sharpest
356
+ turns, so a loft used as a subdivision cage has no pole at its ends (sections with an odd point count
357
+ fall back to the fan). "fan": a triangle fan round the centroid, the cheapest cap for a loft that
358
+ ships unsubdivided; under subdivision its pole of valence n dents the surface, and holding loops on
359
+ its thin spokes clamp every loop on the part (measured on 5.3.0: 7.0 mm loops cut to 5.5 mm). Put
360
+ holding loops on a cap's rim, never inside it.
361
+ :returns: The new object, linked to the scene.
362
+ :raises ValueError: with fewer than two stations, unequal point counts, non-increasing Y or an unknown
363
+ cap style.
364
+ """
365
+ _check_cap_style(cap_style)
366
+ if len(stations) < 2:
367
+ raise ValueError("loft needs at least two stations")
368
+ counts = {len(points) for _, points in stations}
369
+ if len(counts) != 1:
370
+ raise ValueError(f"every section needs the same point count; got {sorted(counts)}")
371
+ positions = [y for y, _ in stations]
372
+ if any(later <= earlier for earlier, later in zip(positions, positions[1:])):
373
+ raise ValueError("station Y positions must strictly increase")
374
+ edit_mesh = bmesh.new()
375
+ rings = [[edit_mesh.verts.new((x, y, z)) for x, z in points] for y, points in stations]
376
+ for first_ring, second_ring in zip(rings, rings[1:]):
377
+ _ring_faces(edit_mesh, first_ring, second_ring)
378
+ if cap_ends:
379
+ _cap(edit_mesh, rings[0], cap_style)
380
+ _cap(edit_mesh, rings[-1], cap_style)
381
+ for face in edit_mesh.faces:
382
+ face.smooth = True
383
+ bmesh.ops.recalc_face_normals(edit_mesh, faces=edit_mesh.faces[:])
384
+ return _object_from_bmesh(name, edit_mesh)
385
+
386
+
387
+ def _axis_point(radius: float, height: float, angle: float, axis: str) -> tuple:
388
+ """A point of a lathe ring: radius and angle around the axis, height along it."""
389
+ across, along = radius * math.cos(angle), radius * math.sin(angle)
390
+ if axis == "Z":
391
+ return across, along, height
392
+ if axis == "Y":
393
+ return across, height, along
394
+ return height, across, along
395
+
396
+
397
+ def profile_spin(name: str, profile_points: list, steps: int = 32, axis: str = "Z") -> bpy.types.Object:
398
+ """
399
+ Lathes a profile around an axis: wheels, rims, tyres, knobs, bottles, nozzles, lamp bodies.
400
+ Points on the axis (radius 0) become single pole vertices, so a closed profile gives a closed solid
401
+ with no collapsed faces. Such a pole has valence `steps` and is ringed by triangles: harmless on a lathe
402
+ that ships as built, but never put one under subdivision_cage (it wrinkles the surface). A turned part
403
+ that will be subdivided is a loft of circular sections along the axis, whose ends loft caps with quads.
404
+
405
+ :param name: Object and mesh name.
406
+ :param profile_points: List of (radius, height) in metres, in order along the profile.
407
+ :param steps: Segments around the axis (use multiples of 4 or 8; more for large on-screen circles).
408
+ :param axis: "X", "Y" or "Z".
409
+ :returns: The new smooth-shaded object.
410
+ :raises ValueError: for an unknown axis, fewer than two points or fewer than three steps.
411
+ """
412
+ if axis not in AXIS_INDEX:
413
+ raise ValueError("axis must be 'X', 'Y' or 'Z'")
414
+ if len(profile_points) < 2 or steps < 3:
415
+ raise ValueError("profile_spin needs at least two profile points and three steps")
416
+ edit_mesh = bmesh.new()
417
+ rings = []
418
+ for radius, height in profile_points:
419
+ if radius <= GEOMETRY_EPSILON:
420
+ rings.append(edit_mesh.verts.new(_axis_point(0.0, height, 0.0, axis)))
421
+ else:
422
+ rings.append([edit_mesh.verts.new(_axis_point(radius, height, 2.0 * math.pi * i / steps, axis))
423
+ for i in range(steps)])
424
+ for first, second in zip(rings, rings[1:]):
425
+ first_is_pole, second_is_pole = not isinstance(first, list), not isinstance(second, list)
426
+ if first_is_pole and second_is_pole:
427
+ continue
428
+ if first_is_pole:
429
+ for i in range(steps):
430
+ edit_mesh.faces.new((first, second[(i + 1) % steps], second[i]))
431
+ elif second_is_pole:
432
+ for i in range(steps):
433
+ edit_mesh.faces.new((first[i], first[(i + 1) % steps], second))
434
+ else:
435
+ _ring_faces(edit_mesh, first, second)
436
+ for face in edit_mesh.faces:
437
+ face.smooth = True
438
+ bmesh.ops.recalc_face_normals(edit_mesh, faces=edit_mesh.faces[:])
439
+ return _object_from_bmesh(name, edit_mesh)
440
+
441
+
442
+ def _lerp_at(parameter: float, start_knot: float, end_knot: float, start_point: np.ndarray,
443
+ end_point: np.ndarray) -> np.ndarray:
444
+ """Linear blend of two points by where `parameter` sits between their knots."""
445
+ span = end_knot - start_knot
446
+ return (end_knot - parameter) / span * start_point + (parameter - start_knot) / span * end_point
447
+
448
+
449
+ def _centripetal_catmull_rom(points: np.ndarray, samples_per_segment: int) -> np.ndarray:
450
+ """
451
+ Samples a centripetal Catmull-Rom spline through every point (it passes through them exactly and does
452
+ not overshoot or loop on uneven spacing, unlike the uniform form or auto Bezier handles). Each span is
453
+ evaluated with the Barry-Goldman pyramid of linear blends.
454
+ """
455
+ padded = np.vstack((2.0 * points[0] - points[1], points, 2.0 * points[-1] - points[-2]))
456
+ samples = []
457
+ for index in range(1, len(padded) - 2):
458
+ control = padded[index - 1:index + 3]
459
+ knots = [0.0]
460
+ for first, second in zip(control, control[1:]):
461
+ knots.append(knots[-1] + max(np.linalg.norm(second - first) ** CENTRIPETAL_EXPONENT, GEOMETRY_EPSILON))
462
+ for step in range(samples_per_segment):
463
+ parameter = knots[1] + (knots[2] - knots[1]) * step / samples_per_segment
464
+ level_one = [_lerp_at(parameter, knots[i], knots[i + 1], control[i], control[i + 1]) for i in range(3)]
465
+ level_two = [_lerp_at(parameter, knots[i], knots[i + 2], level_one[i], level_one[i + 1]) for i in range(2)]
466
+ samples.append(_lerp_at(parameter, knots[1], knots[2], level_two[0], level_two[1]))
467
+ samples.append(points[-1])
468
+ return np.array(samples)
469
+
470
+
471
+ def _transport_frames(path: np.ndarray) -> list:
472
+ """Parallel-transport (normal, binormal) frames along a polyline, so tube rings do not twist."""
473
+ tangents = np.gradient(path, axis=0)
474
+ tangents /= np.maximum(np.linalg.norm(tangents, axis=1, keepdims=True), GEOMETRY_EPSILON)
475
+ least_aligned = np.eye(3)[int(np.argmin(np.abs(tangents[0])))]
476
+ normal = np.cross(tangents[0], least_aligned)
477
+ normal /= np.linalg.norm(normal)
478
+ frames = []
479
+ for index, tangent in enumerate(tangents):
480
+ if index:
481
+ rotation = Vector(tangents[index - 1]).rotation_difference(Vector(tangent))
482
+ normal = np.array(rotation @ Vector(normal))
483
+ normal -= tangent * (normal @ tangent)
484
+ normal /= np.linalg.norm(normal)
485
+ frames.append((normal, np.cross(tangent, normal)))
486
+ return frames
487
+
488
+
489
+ def curve_tube(name: str, points: list, radius, resolution: int = 8, path_subdivisions: int = 4,
490
+ cap_ends: bool = True, cap_style: str = "quad") -> bpy.types.Object:
491
+ """
492
+ A smooth tube through traced centre-line points: struts, rails, pipes, cables, handles, roll hoops.
493
+ The path is a centripetal Catmull-Rom spline through every point (traced points stay exact), and the
494
+ rings are parallel-transported so the tube does not twist.
495
+
496
+ :param name: Object and mesh name.
497
+ :param points: At least two (x, y, z) centre-line points in metres.
498
+ :param radius: Tube radius in metres, or one radius per point (a taper).
499
+ :param resolution: Vertices around the tube.
500
+ :param path_subdivisions: Path samples per span between two points (1 = straight spans).
501
+ :param cap_ends: Close both ends with flat caps (rims marked sharp).
502
+ :param cap_style: "quad" (default; an even resolution gets a quad grid cap, an odd one a fan) or "fan"
503
+ (see loft).
504
+ :returns: The new smooth-shaded mesh object.
505
+ :raises ValueError: with fewer than two points, a radius list of the wrong length, resolution < 3 or an
506
+ unknown cap style.
507
+ """
508
+ _check_cap_style(cap_style)
509
+ path_points = np.array(points, dtype=np.float64)
510
+ if len(path_points) < 2 or resolution < 3:
511
+ raise ValueError("curve_tube needs at least two points and a resolution of at least 3")
512
+ radii = np.full(len(path_points), float(radius)) if np.isscalar(radius) else np.array(radius, dtype=np.float64)
513
+ if len(radii) != len(path_points):
514
+ raise ValueError("give one radius, or one radius per point")
515
+ path = _centripetal_catmull_rom(path_points, max(1, path_subdivisions))
516
+ sample_radii = np.interp(np.linspace(0.0, len(path_points) - 1, len(path)), np.arange(len(path_points)), radii)
517
+ edit_mesh = bmesh.new()
518
+ rings = []
519
+ for center, ring_radius, (normal, binormal) in zip(path, sample_radii, _transport_frames(path)):
520
+ rings.append([edit_mesh.verts.new(center + ring_radius * (math.cos(2.0 * math.pi * i / resolution) * normal
521
+ + math.sin(2.0 * math.pi * i / resolution) * binormal))
522
+ for i in range(resolution)])
523
+ for first_ring, second_ring in zip(rings, rings[1:]):
524
+ _ring_faces(edit_mesh, first_ring, second_ring)
525
+ if cap_ends:
526
+ _cap(edit_mesh, rings[0], cap_style)
527
+ _cap(edit_mesh, rings[-1], cap_style)
528
+ for face in edit_mesh.faces:
529
+ face.smooth = True
530
+ bmesh.ops.recalc_face_normals(edit_mesh, faces=edit_mesh.faces[:])
531
+ return _object_from_bmesh(name, edit_mesh)
532
+
533
+
534
+ # --- design-line cages ------------------------------------------------------------------------------------------
535
+
536
+ def _fair_line(points: np.ndarray, passes: int) -> np.ndarray:
537
+ """Fairs a polyline along its length: each pass moves every interior point FAIRING_STEP of the way
538
+ towards the mean of its neighbours; the end points stay where they were traced."""
539
+ faired = points.copy()
540
+ for _ in range(passes):
541
+ faired[1:-1] += FAIRING_STEP * (faired[:-2] - 2.0 * faired[1:-1] + faired[2:])
542
+ return faired
543
+
544
+
545
+ def design_line_cage(name: str, lines: dict, row_names=None, creases=None, holding=None,
546
+ fair_passes: int = 0) -> tuple:
547
+ """
548
+ A sparse quad cage laid on named design lines, the professional start for a rounded panel: the lines
549
+ the reference shows (crisp edge, fold, highlight crest, seam, silhouette) are traced as 3D polylines
550
+ first, and the cage is the grid of quads between them, so every cage edge runs along a design line and
551
+ every line is an edge chain. Each line gets its own sharpness: a crease (1.0 crisp, 0.6-0.8 a fold) or
552
+ a holding-loop weight. Feed the result to subdivision_cage.
553
+
554
+ :param name: Object and mesh name.
555
+ :param lines: {line name: points}, in order across the panel; every line is (rows, 3) points sampled at
556
+ the same stations, so point r of each line lies on station r. Faces wind so the normal is (next line
557
+ - line) x (next station - station): order the lines so it points out of the part.
558
+ :param row_names: Names of the stations, in order; default "row0", "row1", ...
559
+ :param creases: {line or station name: crease 0..1}. 1.0 also marks the chain sharp (sharp_edge
560
+ survives subdivision, so the crisp lines are still known after apply_modifiers).
561
+ :param holding: {line or station name: bevel weight 0..1}. subdivision_cage sizes its loops from the
562
+ largest radius, and a weight w gives a chain loops w times as wide.
563
+ :param fair_passes: Fairing passes along each line before the cage is built (the curve smoothing CAD
564
+ modellers do before surfacing); lines creased 1.0 keep their traced points.
565
+ :returns: (object, {"lines": {name: [edge indices]}, "rows": {name: [edge indices]}, "audit":
566
+ cage_audit(object)}). The faces are smooth.
567
+ :raises ValueError: for fewer than two lines or stations, lines of unequal length, a station name
568
+ list of the wrong length, a name used twice, or a sharpness given for an unknown name.
569
+ """
570
+ names = list(lines)
571
+ traced = [np.asarray(lines[line], dtype=np.float64) for line in names]
572
+ station_count = len(traced[0]) if traced else 0
573
+ if len(names) < 2 or station_count < 2 or any(points.shape != (station_count, 3) for points in traced):
574
+ raise ValueError("design_line_cage needs at least two lines of the same (stations >= 2, 3) shape")
575
+ stations = list(row_names) if row_names is not None else [f"row{index}" for index in range(station_count)]
576
+ if len(stations) != station_count:
577
+ raise ValueError(f"give one row name per station ({station_count}); got {len(stations)}")
578
+ if len(set(names) | set(stations)) != len(names) + len(stations):
579
+ raise ValueError("every line and station name must be unique")
580
+ creases, holding = dict(creases or {}), dict(holding or {})
581
+ unknown = (set(creases) | set(holding)) - set(names) - set(stations)
582
+ if unknown:
583
+ raise ValueError(f"no line or station named {sorted(unknown)}")
584
+ crisp = {chain for chain, value in creases.items() if value >= CREASE_CRISP}
585
+ if fair_passes:
586
+ traced = [points if line in crisp else _fair_line(points, fair_passes) for line, points in zip(names, traced)]
587
+
588
+ edit_mesh = bmesh.new()
589
+ grid = [[edit_mesh.verts.new(point) for point in points] for points in traced]
590
+ for line in range(len(names) - 1):
591
+ for station in range(station_count - 1):
592
+ face = edit_mesh.faces.new((grid[line][station], grid[line + 1][station],
593
+ grid[line + 1][station + 1], grid[line][station + 1]))
594
+ face.smooth = True
595
+ chains = {line_name: [edit_mesh.edges.get((grid[line][station], grid[line][station + 1]))
596
+ for station in range(station_count - 1)] for line, line_name in enumerate(names)}
597
+ chains.update({station_name: [edit_mesh.edges.get((grid[line][station], grid[line + 1][station]))
598
+ for line in range(len(names) - 1)]
599
+ for station, station_name in enumerate(stations)})
600
+ for chain in crisp:
601
+ for edge in chains[chain]:
602
+ edge.smooth = False
603
+ edit_mesh.edges.index_update()
604
+ indices = {chain: [edge.index for edge in edges] for chain, edges in chains.items()}
605
+ obj = _object_from_bmesh(name, edit_mesh)
606
+ if creases:
607
+ set_edge_values(obj, "crease_edge", {index: value for chain, value in creases.items() for index in indices[chain]})
608
+ if holding:
609
+ set_edge_values(obj, "bevel_weight_edge", {index: value for chain, value in holding.items() for index in indices[chain]})
610
+ return obj, {"lines": {line: indices[line] for line in names},
611
+ "rows": {station: indices[station] for station in stations}, "audit": cage_audit(obj)}
612
+
613
+
614
+ def cage_audit(obj: bpy.types.Object) -> dict:
615
+ """
616
+ The topology checks a subdivision cage must pass before it is subdivided. Poles (interior vertices
617
+ with other than four edges) are listed with their world positions: each must sit on a flat area or
618
+ behind an opening, never on a roll a highlight crosses, and a panel carries a few at most. The edge
619
+ ratio compares the two edges that carry a loop through a vertex; keep it under about 1.5 on rolled zones,
620
+ or the highlight bunches. Boundary vertices are skipped (a mirror seam is a boundary until mirrored).
621
+
622
+ :param obj: The cage (mesh object).
623
+ :returns: {"faces", "non_quads", "poles": [{"vertex", "valence", "position"}], "max_edge_ratio",
624
+ "max_edge_ratio_at": world position or None}.
625
+ """
626
+ matrix = obj.matrix_world
627
+ edit_mesh = bmesh.new()
628
+ edit_mesh.from_mesh(obj.data)
629
+ poles, worst_ratio, worst_at = [], 1.0, None
630
+ try:
631
+ for vertex in edit_mesh.verts:
632
+ if vertex.is_boundary or not vertex.link_faces:
633
+ continue
634
+ if len(vertex.link_edges) != CAGE_REGULAR_VALENCE:
635
+ poles.append({"vertex": vertex.index, "valence": len(vertex.link_edges),
636
+ "position": [round(value, 4) for value in matrix @ vertex.co]})
637
+ continue
638
+ for edge in vertex.link_edges:
639
+ sharing = set(edge.link_faces)
640
+ opposite = [other for other in vertex.link_edges
641
+ if other is not edge and not sharing.intersection(other.link_faces)]
642
+ if len(opposite) != 1:
643
+ continue
644
+ shorter, longer = sorted((edge.calc_length(), opposite[0].calc_length()))
645
+ ratio = longer / max(shorter, GEOMETRY_EPSILON)
646
+ if ratio > worst_ratio:
647
+ worst_ratio, worst_at = ratio, [round(value, 4) for value in matrix @ vertex.co]
648
+ non_quads = sum(1 for face in edit_mesh.faces if len(face.verts) != QUAD_CORNERS)
649
+ face_count = len(edit_mesh.faces)
650
+ finally:
651
+ edit_mesh.free()
652
+ return {"faces": face_count, "non_quads": non_quads, "poles": poles,
653
+ "max_edge_ratio": round(worst_ratio, 3), "max_edge_ratio_at": worst_at}
654
+
655
+
656
+ # --- edge attributes, subdivision, bevel, shading -----------------------------------------------------------
657
+
658
+ def set_edge_values(obj: bpy.types.Object, attribute: str, values: dict) -> None:
659
+ """
660
+ Writes per-edge float values (bevel_weight_edge, crease_edge) on a mesh, creating the attribute.
661
+
662
+ :param obj: Mesh object.
663
+ :param attribute: Attribute name, e.g. "bevel_weight_edge" or "crease_edge".
664
+ :param values: {edge index: value 0..1}.
665
+ :raises IndexError: for an edge index outside the mesh.
666
+ """
667
+ mesh = obj.data
668
+ layer = mesh.attributes.get(attribute) or mesh.attributes.new(attribute, "FLOAT", "EDGE")
669
+ edge_count = len(mesh.edges)
670
+ for index, value in values.items():
671
+ if not 0 <= index < edge_count:
672
+ raise IndexError(f"edge {index} is outside {obj.name} ({edge_count} edges)")
673
+ layer.data[index].value = float(value)
674
+
675
+
676
+ def _edge_value_map(edges_or_values) -> dict:
677
+ """Accepts a list of edge indices (value 1.0) or a {index: value} dict."""
678
+ if isinstance(edges_or_values, dict):
679
+ return dict(edges_or_values)
680
+ return {int(index): 1.0 for index in edges_or_values}
681
+
682
+
683
+ def _positive_edge_count(obj: bpy.types.Object, attribute: str) -> int:
684
+ """How many edges carry a value above 0 in a float edge attribute (0 when the attribute is missing)."""
685
+ layer = obj.data.attributes.get(attribute)
686
+ if layer is None:
687
+ return 0
688
+ values = np.empty(len(layer.data), dtype=np.float32)
689
+ layer.data.foreach_get("value", values)
690
+ return int(np.count_nonzero(values > 0.0))
691
+
692
+
693
+ def _evaluated_world_mesh(obj: bpy.types.Object) -> tuple:
694
+ """(world vertices (N, 3), edges (E, 2)) of an object with its modifiers applied (empty without a mesh)."""
695
+ depsgraph = bpy.context.evaluated_depsgraph_get()
696
+ evaluated = obj.evaluated_get(depsgraph)
697
+ mesh = evaluated.to_mesh()
698
+ if mesh is None:
699
+ # An object whose evaluated geometry holds no mesh (a curve whose nodes only make instances).
700
+ evaluated.to_mesh_clear()
701
+ return np.zeros((0, 3)), np.zeros((0, 2), dtype=np.int64)
702
+ try:
703
+ coordinates = np.empty(len(mesh.vertices) * 3, dtype=np.float64)
704
+ mesh.vertices.foreach_get("co", coordinates)
705
+ edges = np.empty(len(mesh.edges) * 2, dtype=np.int64)
706
+ mesh.edges.foreach_get("vertices", edges)
707
+ matrix = np.array(evaluated.matrix_world)
708
+ finally:
709
+ evaluated.to_mesh_clear()
710
+ vertices = coordinates.reshape(-1, 3) @ matrix[:3, :3].T + matrix[:3, 3]
711
+ return vertices, edges.reshape(-1, 2)
712
+
713
+
714
+ def world_vertices(obj: bpy.types.Object, evaluated: bool = True) -> np.ndarray:
715
+ """
716
+ World-space vertex positions. Measure with these, never with bound_box: an object's bound_box is its
717
+ local box, so on a rotated object its world corners overstate the size (a 45-degree sphere of 1 m
718
+ reads 1.41 m).
719
+
720
+ :param obj: Any object Blender can turn into a mesh.
721
+ :param evaluated: Include modifiers (True) or read the base mesh only.
722
+ :returns: (N, 3) float64 array in metres.
723
+ """
724
+ if evaluated:
725
+ return _evaluated_world_mesh(obj)[0]
726
+ coordinates = np.empty(len(obj.data.vertices) * 3, dtype=np.float64)
727
+ obj.data.vertices.foreach_get("co", coordinates)
728
+ matrix = np.array(obj.matrix_world)
729
+ return coordinates.reshape(-1, 3) @ matrix[:3, :3].T + matrix[:3, 3]
730
+
731
+
732
+ def section_points(objects, position: float, axis: str = "Y") -> np.ndarray:
733
+ """
734
+ Where the evaluated mesh edges cross a plane: the cross-section outline (unordered) at a station.
735
+
736
+ :param objects: An object or a list of objects.
737
+ :param position: Plane position along the axis, metres.
738
+ :param axis: "X", "Y" or "Z": the plane's normal.
739
+ :returns: (M, 2) array of the two other world coordinates, in axis order (for Y: x and z).
740
+ """
741
+ axis_index = AXIS_INDEX[axis]
742
+ other_axes = [index for index in range(3) if index != axis_index]
743
+ collected = []
744
+ for obj in objects if isinstance(objects, (list, tuple)) else [objects]:
745
+ vertices, edges = _evaluated_world_mesh(obj)
746
+ offsets = vertices[:, axis_index] - position
747
+ start, end = offsets[edges[:, 0]], offsets[edges[:, 1]]
748
+ crossing = (start * end) < 0.0
749
+ fraction = start[crossing] / (start[crossing] - end[crossing])
750
+ first, second = vertices[edges[crossing, 0]], vertices[edges[crossing, 1]]
751
+ collected.append((first + (second - first) * fraction[:, None])[:, other_axes])
752
+ collected.append(vertices[np.abs(offsets) <= GEOMETRY_EPSILON][:, other_axes])
753
+ return np.concatenate(collected) if collected else np.zeros((0, 2))
754
+
755
+
756
+ def section_extent(objects, position: float, axis: str = "Y", measure_axis: str = "X"):
757
+ """
758
+ The extent of a cross-section along one axis: the exact silhouette width or height a straight view
759
+ shows at that station.
760
+
761
+ :param objects: An object or a list of objects.
762
+ :param position: Station position along `axis`, metres.
763
+ :param axis: The station axis (plane normal).
764
+ :param measure_axis: The axis to measure along (must differ from `axis`).
765
+ :returns: (minimum, maximum) in metres, or None when the plane misses the mesh.
766
+ :raises ValueError: when both axes are the same.
767
+ """
768
+ if measure_axis == axis:
769
+ raise ValueError("measure_axis must differ from the station axis")
770
+ points = section_points(objects, position, axis)
771
+ if len(points) == 0:
772
+ return None
773
+ other_axes = [name for name in ("X", "Y", "Z") if name != axis]
774
+ column = points[:, other_axes.index(measure_axis)]
775
+ return float(column.min()), float(column.max())
776
+
777
+
778
+ def _station_measurements(obj: bpy.types.Object, targets: list, axis: str) -> list:
779
+ """Measures the evaluated mesh at each shrink target: extents and centres across the two other axes."""
780
+ measurements = []
781
+ for target in targets:
782
+ points = section_points(obj, target["position"], axis)
783
+ if len(points) == 0:
784
+ raise ValueError(f"the evaluated mesh does not reach station {target['position']} along {axis}")
785
+ low, high = points.min(axis=0), points.max(axis=0)
786
+ measurements.append({"size": high - low, "center": (high + low) / 2.0})
787
+ return measurements
788
+
789
+
790
+ def _target_sizes(target: dict, axis: str) -> list:
791
+ """Target extents across the two non-station axes ("width" is along X or Y, "height" along Z)."""
792
+ if axis == "Z":
793
+ return [target.get("width"), target.get("depth")]
794
+ return [target.get("width"), target.get("height")]
795
+
796
+
797
+ def _shrink_errors(targets: list, measurements: list, axis: str) -> list:
798
+ """Per-station percent errors of the measured extents against the targets (None where no target)."""
799
+ errors = []
800
+ for target, measured in zip(targets, measurements):
801
+ sizes = _target_sizes(target, axis)
802
+ errors.append([None if wanted is None else 100.0 * (measured["size"][slot] - wanted) / wanted
803
+ for slot, wanted in enumerate(sizes)])
804
+ return errors
805
+
806
+
807
+ def _cage_world(obj: bpy.types.Object) -> np.ndarray:
808
+ """The cage's base-mesh vertices in world space, (N, 3)."""
809
+ local = np.empty(len(obj.data.vertices) * 3)
810
+ obj.data.vertices.foreach_get("co", local)
811
+ matrix = np.array(obj.matrix_world)
812
+ return local.reshape(-1, 3) @ matrix[:3, :3].T + matrix[:3, 3]
813
+
814
+
815
+ def _set_cage_world(obj: bpy.types.Object, world: np.ndarray) -> None:
816
+ """Writes world-space positions back to the cage's base mesh and re-evaluates it."""
817
+ inverse = np.linalg.inv(np.array(obj.matrix_world))
818
+ obj.data.vertices.foreach_set("co", (world @ inverse[:3, :3].T + inverse[:3, 3]).ravel())
819
+ obj.data.update()
820
+ bpy.context.view_layer.update()
821
+
822
+
823
+ def _scaled_cage(world: np.ndarray, positions: np.ndarray, factors: np.ndarray, centers: np.ndarray,
824
+ axis: str) -> np.ndarray:
825
+ """
826
+ Scales cage vertices about their station centres, each factor interpolated between the stations along
827
+ the station axis (held constant beyond the end stations).
828
+
829
+ :param world: Cage vertices (N, 3), world space.
830
+ :param positions: Station positions, ascending.
831
+ :param factors: (2, stations) scale per non-station axis and station.
832
+ :param centers: (2, stations) section centre per non-station axis and station.
833
+ :param axis: Station axis.
834
+ :returns: The scaled vertices.
835
+ """
836
+ axis_index = AXIS_INDEX[axis]
837
+ scaled = world.copy()
838
+ for slot, world_axis in enumerate(index for index in range(3) if index != axis_index):
839
+ factor = np.interp(world[:, axis_index], positions, factors[slot])
840
+ center = np.interp(world[:, axis_index], positions, centers[slot])
841
+ scaled[:, world_axis] = center + (world[:, world_axis] - center) * factor
842
+ return scaled
843
+
844
+
845
+ def _station_sizes(obj: bpy.types.Object, targets: list, axis: str) -> tuple:
846
+ """(sizes (2, stations), centres (2, stations)) of the evaluated mesh at the targets."""
847
+ measurements = _station_measurements(obj, targets, axis)
848
+ return (np.array([measured["size"] for measured in measurements]).T,
849
+ np.array([measured["center"] for measured in measurements]).T)
850
+
851
+
852
+ def _station_response(obj: bpy.types.Object, targets: list, axis: str, world: np.ndarray,
853
+ positions: np.ndarray, sizes: np.ndarray, centers: np.ndarray) -> np.ndarray:
854
+ """
855
+ How every station's evaluated size moves when one station's cage scale changes (a finite-difference
856
+ Jacobian). Subdivision is linear in the cage, so neighbouring stations are coupled but predictable.
857
+
858
+ :returns: (2, stations, stations) array: d size[slot][row] / d factor[slot][column].
859
+ """
860
+ count = len(targets)
861
+ response = np.zeros((2, count, count))
862
+ for column in range(count):
863
+ factors = np.ones((2, count))
864
+ factors[:, column] += SHRINK_RESPONSE_STEP
865
+ _set_cage_world(obj, _scaled_cage(world, positions, factors, centers, axis))
866
+ perturbed, _ = _station_sizes(obj, targets, axis)
867
+ response[:, :, column] = (perturbed - sizes) / SHRINK_RESPONSE_STEP
868
+ _set_cage_world(obj, world)
869
+ return response
870
+
871
+
872
+ def _newton_factors(targets: list, axis: str, sizes: np.ndarray, response: np.ndarray) -> np.ndarray:
873
+ """Scale factors that bring every targeted size to its target at once (least squares per axis)."""
874
+ count = len(targets)
875
+ factors = np.ones((2, count))
876
+ for slot in range(2):
877
+ wanted = [_target_sizes(target, axis)[slot] for target in targets]
878
+ rows = [index for index, value in enumerate(wanted) if value is not None]
879
+ if not rows:
880
+ continue
881
+ shortfall = np.array([wanted[index] for index in rows]) - sizes[slot, rows]
882
+ step = np.linalg.lstsq(response[slot][np.ix_(rows, rows)], shortfall, rcond=None)[0]
883
+ factors[slot, rows] += step
884
+ return factors
885
+
886
+
887
+ def _largest_error(errors: list) -> float:
888
+ """The largest absolute percent error over every targeted extent."""
889
+ return max((abs(value) for station in errors for value in station if value is not None), default=0.0)
890
+
891
+
892
+ def _correct_shrinkage(obj: bpy.types.Object, targets: list, axis: str, max_iterations: int,
893
+ tolerance_percent: float) -> dict:
894
+ """
895
+ Scales the cage, station by station, until the subdivided result meets the station targets. Each round
896
+ measures how every station responds to every station's scale and solves for all factors together
897
+ (a Newton step), so a waist between two wider stations does not oscillate.
898
+ """
899
+ targets = sorted(targets, key=lambda target: target["position"])
900
+ positions = np.array([target["position"] for target in targets], dtype=np.float64)
901
+ bpy.context.view_layer.update()
902
+ measurements = _station_measurements(obj, targets, axis)
903
+ errors = _shrink_errors(targets, measurements, axis)
904
+ initial_error = _largest_error(errors)
905
+ iterations = 0
906
+ while _largest_error(errors) > tolerance_percent and iterations < max_iterations:
907
+ world = _cage_world(obj)
908
+ sizes, centers = _station_sizes(obj, targets, axis)
909
+ response = _station_response(obj, targets, axis, world, positions, sizes, centers)
910
+ _set_cage_world(obj, _scaled_cage(world, positions, _newton_factors(targets, axis, sizes, response),
911
+ centers, axis))
912
+ iterations += 1
913
+ measurements = _station_measurements(obj, targets, axis)
914
+ errors = _shrink_errors(targets, measurements, axis)
915
+ final_error = _largest_error(errors)
916
+ stations = [{"position": target["position"],
917
+ "measured": [round(float(value), 5) for value in measured["size"]],
918
+ "error_percent": [None if value is None else round(float(value), 3) for value in station_errors]}
919
+ for target, measured, station_errors in zip(targets, measurements, errors)]
920
+ return {"iterations": iterations, "converged": bool(final_error <= tolerance_percent),
921
+ "initial_max_error_percent": round(float(initial_error), 3),
922
+ "final_max_error_percent": round(float(final_error), 3),
923
+ "stations": stations}
924
+
925
+
926
+ def _evaluated_faces(obj: bpy.types.Object) -> tuple:
927
+ """(world vertices (N, 3), face normals (F, 3), face centres (F, 3)) of the evaluated mesh."""
928
+ depsgraph = bpy.context.evaluated_depsgraph_get()
929
+ evaluated = obj.evaluated_get(depsgraph)
930
+ mesh = evaluated.to_mesh()
931
+ try:
932
+ coordinates = np.empty(len(mesh.vertices) * 3, dtype=np.float64)
933
+ mesh.vertices.foreach_get("co", coordinates)
934
+ normals = np.empty(len(mesh.polygons) * 3, dtype=np.float64)
935
+ mesh.polygons.foreach_get("normal", normals)
936
+ centers = np.empty(len(mesh.polygons) * 3, dtype=np.float64)
937
+ mesh.polygons.foreach_get("center", centers)
938
+ matrix = np.array(evaluated.matrix_world)
939
+ finally:
940
+ evaluated.to_mesh_clear()
941
+ rotation, translation = matrix[:3, :3], matrix[:3, 3]
942
+ return (coordinates.reshape(-1, 3) @ rotation.T + translation, normals.reshape(-1, 3) @ rotation.T,
943
+ centers.reshape(-1, 3) @ rotation.T + translation)
944
+
945
+
946
+ def _holding_check(obj: bpy.types.Object, holding: bpy.types.BevelModifier, subdivision: bpy.types.SubsurfModifier,
947
+ width: float) -> dict:
948
+ """
949
+ Measures the holding loops the Bevel modifier really makes. Clamp Overlap is global: one feature too
950
+ narrow for its loops shrinks the loop width, and so the radius, on every edge of the part. The stack is
951
+ evaluated without subdivision at a tiny probe width (never clamped), at the full width unclamped and at
952
+ the full width as set. Bevel vertices move linearly with the width, so the clamped travel over the free
953
+ travel gives the effective width; faces that turn over between the probe and the unclamped full width
954
+ are the narrow spots.
955
+
956
+ :param obj: The cage.
957
+ :param holding: Its holding-loop Bevel modifier.
958
+ :param subdivision: Its Subdivision modifier (switched off for the measurement, then restored).
959
+ :param width: The loop width asked for, metres.
960
+ :returns: {"loop_width", "effective_loop_width", "effective_corner_radius", "clamped", "folds",
961
+ "fold_centers"}; the effective values are None when the topology changed between evaluations.
962
+ """
963
+ clamp_setting = holding.use_clamp_overlap
964
+ subdivision.show_viewport = False
965
+ try:
966
+ set_vertices, _, _ = _evaluated_faces(obj)
967
+ holding.use_clamp_overlap = False
968
+ free_vertices, free_normals, _ = _evaluated_faces(obj)
969
+ probe_width = width * HOLDING_PROBE_SHARE
970
+ holding.width = probe_width
971
+ probe_vertices, probe_normals, probe_centers = _evaluated_faces(obj)
972
+ finally:
973
+ holding.width = width
974
+ holding.use_clamp_overlap = clamp_setting
975
+ subdivision.show_viewport = True
976
+ bpy.context.view_layer.update()
977
+ report = {"loop_width": round(width, 6), "effective_loop_width": None, "effective_corner_radius": None,
978
+ "clamped": None, "folds": 0, "fold_centers": []}
979
+ if not (len(set_vertices) == len(free_vertices) == len(probe_vertices)) or len(probe_normals) != len(free_normals):
980
+ return report
981
+ folded = np.flatnonzero(np.einsum("ij,ij->i", probe_normals, free_normals) < 0.0)
982
+ report["folds"] = int(len(folded))
983
+ report["fold_centers"] = [[round(float(value), 4) for value in center]
984
+ for center in probe_centers[folded[:MAXIMUM_REPORTED_FOLDS]]]
985
+ free_travel = free_vertices - probe_vertices
986
+ set_travel = set_vertices - probe_vertices
987
+ lengths = np.einsum("ij,ij->i", free_travel, free_travel)
988
+ moving = lengths > HOLDING_TRAVEL_EPSILON ** 2
989
+ if not moving.any():
990
+ return report
991
+ ratios = np.einsum("ij,ij->i", set_travel[moving], free_travel[moving]) / lengths[moving]
992
+ effective = probe_width + (width - probe_width) * float(np.clip(ratios.min(), 0.0, 1.0))
993
+ report.update({"effective_loop_width": round(effective, 6),
994
+ "effective_corner_radius": round(effective * HOLDING_RADIUS_PER_WIDTH, 6),
995
+ "clamped": bool(effective < width * HOLDING_CLAMP_RATIO)})
996
+ return report
997
+
998
+
999
+ def _warn_holding(obj: bpy.types.Object, check: dict) -> None:
1000
+ """Warns when Clamp Overlap shrank the loops, or when unclamped loops fold over."""
1001
+ if check["clamped"]:
1002
+ warnings.warn(f"subdivision_cage({obj.name}): Clamp Overlap cut every holding loop from "
1003
+ f"{check['loop_width']} m to {check['effective_loop_width']} m (corner radius "
1004
+ f"{check['effective_corner_radius']} m); a feature narrower than twice the loop width sits "
1005
+ f"near {check['fold_centers']}. Widen it, or give its edges a lower bevel weight.",
1006
+ RuntimeWarning, stacklevel=3)
1007
+ elif check["folds"]:
1008
+ warnings.warn(f"subdivision_cage({obj.name}): with Clamp Overlap off, {check['folds']} faces fold over "
1009
+ f"near {check['fold_centers']}: the loops are wider than the feature they sit on.",
1010
+ RuntimeWarning, stacklevel=3)
1011
+
1012
+
1013
+ def subdivision_cage(obj: bpy.types.Object, levels: int = 1, holding_loop_width=None, crease_edges=None,
1014
+ shrink_targets=None, holding_edges=None, station_axis: str = "Y",
1015
+ max_iterations: int = SHRINK_ITERATIONS,
1016
+ tolerance_percent: float = SHRINK_TOLERANCE_PERCENT, holding_corner_radius=None,
1017
+ clamp_overlap: bool = True) -> dict:
1018
+ """
1019
+ Turns a light quad cage into a smooth subdivision surface for blends and junctions (pods, cheeks,
1020
+ intakes): optional holding loops (a weight-limited Bevel modifier before the subdivision, two segments
1021
+ at profile 1.0, so the subdivided corner radius is HOLDING_RADIUS_PER_WIDTH x the loop width at any
1022
+ level and the outer size does not move), optional creases, then Catmull-Clark on the
1023
+ limit surface. Subdivision shrinks convex cages; with shrink_targets the cage is scaled at the
1024
+ stations until the subdivided surface meets the measured sizes. Each round solves every station
1025
+ together (neighbouring stations pull on each other through the subdivision), so one round normally
1026
+ converges and max_iterations is a safety limit.
1027
+
1028
+ Clamp Overlap is global in the Bevel modifier: one feature narrower than twice the loop width shrinks
1029
+ every loop on the part (measured on 5.3.0: radii 0.0040 -> 0.0034 m from one 12 mm wall). The loops are
1030
+ measured after they are added, and a RuntimeWarning names the effective width and where the narrow
1031
+ spot is; "holding_check" in the result carries the same numbers.
1032
+
1033
+ Modifiers stay live; call apply_modifiers when the shape is final.
1034
+
1035
+ :param obj: The cage (mesh object).
1036
+ :param levels: Subdivision levels (1 is the usual game compromise).
1037
+ :param holding_loop_width: Distance of holding loops from their edges, metres; None for no loops.
1038
+ The corner radius comes out at 0.57 x this width; prefer holding_corner_radius.
1039
+ :param crease_edges: Edge indices (crease 1.0) or {index: crease 0..1}; soft folds read better at 0.6-0.8.
1040
+ Creases already on the cage (a `crease_edge` attribute written by set_edge_values, design_line_cage
1041
+ or a bmesh layer) are kept, and the subdivision honours every crease above 0 whether or not this is
1042
+ given.
1043
+ :param shrink_targets: List of {"position": station coordinate, "width": metres, "height": metres}
1044
+ (either size may be omitted). For a Y station axis width is along X and height along Z; for an X
1045
+ axis width is along Y; for a Z axis give "width" (X) and "depth" (Y).
1046
+ :param holding_edges: Edges that get holding loops (bevel weight 1.0); None keeps existing weights.
1047
+ :param station_axis: Axis the stations are placed along.
1048
+ :param max_iterations: Correction rounds at most.
1049
+ :param tolerance_percent: Converged when every targeted extent is within this percent.
1050
+ :param holding_corner_radius: Target corner radius in metres (the measured reference radius); the
1051
+ loop width is set to radius / HOLDING_RADIUS_PER_WIDTH. Give this or holding_loop_width.
1052
+ :param clamp_overlap: Keep the Bevel modifier's Clamp Overlap (the safe default). Turn it off only once
1053
+ "holding_check" reports no folds, so a narrow feature can no longer shrink the other radii.
1054
+ :returns: {"modifiers": [names], "holding_loop_width": metres or None, "creased_edges": count of cage
1055
+ edges with a crease above 0, "shrink": report or None, "holding_check": {"loop_width",
1056
+ "effective_loop_width", "effective_corner_radius", "clamped", "folds", "fold_centers"} or None}.
1057
+ :raises ValueError: when holding loops are asked for but no edge is weighted, or both sizes are given.
1058
+ """
1059
+ if holding_corner_radius is not None:
1060
+ if holding_loop_width is not None:
1061
+ raise ValueError("give holding_loop_width or holding_corner_radius, not both")
1062
+ holding_loop_width = holding_corner_radius / HOLDING_RADIUS_PER_WIDTH
1063
+ if holding_edges is not None:
1064
+ set_edge_values(obj, "bevel_weight_edge", _edge_value_map(holding_edges))
1065
+ if crease_edges:
1066
+ set_edge_values(obj, "crease_edge", _edge_value_map(crease_edges))
1067
+ creased_edges = _positive_edge_count(obj, "crease_edge")
1068
+ modifier_names = []
1069
+ if holding_loop_width:
1070
+ if not _positive_edge_count(obj, "bevel_weight_edge"):
1071
+ raise ValueError("holding loops need weighted edges: pass holding_edges or set bevel_weight_edge")
1072
+ holding = obj.modifiers.new("HoldingLoops", "BEVEL")
1073
+ holding.limit_method = "WEIGHT"
1074
+ holding.width = holding_loop_width
1075
+ holding.segments = HOLDING_SEGMENTS
1076
+ holding.profile = HOLDING_PROFILE
1077
+ holding.use_clamp_overlap = clamp_overlap
1078
+ modifier_names.append(holding.name)
1079
+ subdivision = obj.modifiers.new("Subdivision", "SUBSURF")
1080
+ subdivision.levels = levels
1081
+ subdivision.render_levels = levels
1082
+ subdivision.use_limit_surface = True
1083
+ subdivision.quality = 3
1084
+ subdivision.use_creases = creased_edges > 0
1085
+ subdivision.boundary_smooth = "PRESERVE_CORNERS"
1086
+ modifier_names.append(subdivision.name)
1087
+ for face in obj.data.polygons:
1088
+ face.use_smooth = True
1089
+ holding_check = None
1090
+ if holding_loop_width:
1091
+ holding_check = _holding_check(obj, obj.modifiers[modifier_names[0]], subdivision, holding_loop_width)
1092
+ _warn_holding(obj, holding_check)
1093
+ shrink = None
1094
+ if shrink_targets:
1095
+ shrink = _correct_shrinkage(obj, shrink_targets, station_axis, max_iterations, tolerance_percent)
1096
+ return {"modifiers": modifier_names, "holding_loop_width": holding_loop_width or None,
1097
+ "creased_edges": creased_edges, "shrink": shrink, "holding_check": holding_check}
1098
+
1099
+
1100
+ def bevel_edges(obj: bpy.types.Object, edge_indices_or_weight, width: float, segments: int,
1101
+ profile: float = 0.5, harden_normals: bool = True) -> bpy.types.BevelModifier:
1102
+ """
1103
+ A weight-limited, multi-segment Bevel modifier for boxy parts. Bevel only design edges, sized from
1104
+ the measured corner radius (width = radius, 3-4 segments for soft rounds, 1-2 for machined chamfers).
1105
+ Harden Normals keeps the neighbouring flats flat while the bevel shades smoothly into them.
1106
+
1107
+ :param obj: Mesh object.
1108
+ :param edge_indices_or_weight: Edge indices to bevel (they get bevel weight 1.0), or a threshold
1109
+ 0..1: edges whose existing bevel_weight_edge is at least this are bevelled at full width and lower
1110
+ weights are cleared.
1111
+ :param width: Bevel width in metres.
1112
+ :param segments: Segments across the bevel.
1113
+ :param profile: 0.5 is circular; higher bulges out, lower pinches in.
1114
+ :param harden_normals: Keep neighbouring flat faces flat-shaded (needs smooth faces).
1115
+ :returns: The Bevel modifier.
1116
+ :raises ValueError: when no edge ends up selected for bevelling.
1117
+ """
1118
+ if isinstance(edge_indices_or_weight, (int, float)) and not isinstance(edge_indices_or_weight, bool):
1119
+ weights = obj.data.attributes.get("bevel_weight_edge")
1120
+ existing = {} if weights is None else {index: item.value for index, item in enumerate(weights.data)}
1121
+ threshold = float(edge_indices_or_weight)
1122
+ set_edge_values(obj, "bevel_weight_edge",
1123
+ {index: 1.0 if value >= threshold else 0.0 for index, value in existing.items()})
1124
+ else:
1125
+ set_edge_values(obj, "bevel_weight_edge", _edge_value_map(edge_indices_or_weight))
1126
+ weights = obj.data.attributes["bevel_weight_edge"]
1127
+ if not any(item.value > 0.0 for item in weights.data):
1128
+ raise ValueError("no edges selected for bevelling")
1129
+ for face in obj.data.polygons:
1130
+ face.use_smooth = True
1131
+ bevel = obj.modifiers.new("Bevel", "BEVEL")
1132
+ bevel.limit_method = "WEIGHT"
1133
+ bevel.width = width
1134
+ bevel.segments = segments
1135
+ bevel.profile = profile
1136
+ bevel.harden_normals = harden_normals
1137
+ bevel.use_clamp_overlap = True
1138
+ bevel.miter_outer = "MITER_ARC"
1139
+ return bevel
1140
+
1141
+
1142
+ def _clear_custom_normals(obj: bpy.types.Object) -> None:
1143
+ """Removes custom split normals (stored as the `custom_normal` corner attribute in Blender 5.x)."""
1144
+ mesh = obj.data
1145
+ if not mesh.has_custom_normals:
1146
+ return
1147
+ if "custom_normal" in mesh.attributes:
1148
+ mesh.attributes.remove(mesh.attributes["custom_normal"])
1149
+ return
1150
+ with bpy.context.temp_override(object=obj, active_object=obj, selected_objects=[obj],
1151
+ selected_editable_objects=[obj]):
1152
+ bpy.ops.mesh.customdata_custom_splitnormals_clear()
1153
+
1154
+
1155
+ def shade_smooth(obj: bpy.types.Object, design_line_edges=None, sharp_angle_degrees=None) -> dict:
1156
+ """
1157
+ Smooth shading for rounded forms: every face smooth, every edge smooth except the design lines.
1158
+ Clears custom normals first, so stale ones cannot fight the new shading. Never put Face-Area
1159
+ weighted normals on a curved surface: they flatten every facet.
1160
+
1161
+ :param obj: Mesh object.
1162
+ :param design_line_edges: Edge indices to mark sharp (crisp design lines), or None.
1163
+ :param sharp_angle_degrees: Also mark edges sharper than this dihedral angle - only for genuinely
1164
+ faceted forms. None keeps rounded forms free of angle splits.
1165
+ :returns: {"smooth_faces", "sharp_edges"}. Zero sharp edges on a part with design cuts means the
1166
+ marking missed them.
1167
+ """
1168
+ mesh = obj.data
1169
+ _clear_custom_normals(obj)
1170
+ design_lines = set(design_line_edges or ())
1171
+ edit_mesh = bmesh.new()
1172
+ edit_mesh.from_mesh(mesh)
1173
+ for face in edit_mesh.faces:
1174
+ face.smooth = True
1175
+ sharp_count = 0
1176
+ angle_limit = None if sharp_angle_degrees is None else math.radians(sharp_angle_degrees)
1177
+ for edge in edit_mesh.edges:
1178
+ is_sharp = edge.index in design_lines
1179
+ if angle_limit is not None and len(edge.link_faces) == 2:
1180
+ is_sharp = is_sharp or edge.calc_face_angle(0.0) > angle_limit
1181
+ edge.smooth = not is_sharp
1182
+ sharp_count += is_sharp
1183
+ edit_mesh.to_mesh(mesh)
1184
+ edit_mesh.free()
1185
+ return {"smooth_faces": len(mesh.polygons), "sharp_edges": sharp_count}
1186
+
1187
+
1188
+ def _corner_keys(mesh: bpy.types.Mesh) -> tuple:
1189
+ """A position per face corner, nudged towards its face centre, so every corner has its own key."""
1190
+ keys, corner_indices = [], []
1191
+ for polygon in mesh.polygons:
1192
+ center = polygon.center
1193
+ for loop_index in polygon.loop_indices:
1194
+ position = mesh.vertices[mesh.loops[loop_index].vertex_index].co
1195
+ keys.append(position.lerp(center, 0.25))
1196
+ corner_indices.append(loop_index)
1197
+ return keys, corner_indices
1198
+
1199
+
1200
+ def weld(obj: bpy.types.Object, distance: float, keep_normals: bool = True) -> dict:
1201
+ """
1202
+ Merges vertices closer than `distance` (Merge by Distance) without losing the shading. Hard shading
1203
+ that came from split edges turns smooth when the split vertices merge (a split cube welds into a
1204
+ blob); with keep_normals every face corner gets its previous normal back as a custom normal.
1205
+
1206
+ :param obj: Mesh object (apply its transforms first if the distance is meant in world units).
1207
+ :param distance: Merge distance in the mesh's local units.
1208
+ :param keep_normals: Restore the pre-weld corner normals.
1209
+ :returns: {"removed_vertices", "kept_normals"}.
1210
+ """
1211
+ mesh = obj.data
1212
+ before = len(mesh.vertices)
1213
+ tree, normals = None, []
1214
+ if keep_normals and mesh.polygons:
1215
+ keys, corner_indices = _corner_keys(mesh)
1216
+ normals = [mesh.corner_normals[index].vector.copy() for index in corner_indices]
1217
+ tree = KDTree(len(keys))
1218
+ for key_index, key in enumerate(keys):
1219
+ tree.insert(key, key_index)
1220
+ tree.balance()
1221
+ edit_mesh = bmesh.new()
1222
+ edit_mesh.from_mesh(mesh)
1223
+ bmesh.ops.remove_doubles(edit_mesh, verts=edit_mesh.verts[:], dist=distance)
1224
+ edit_mesh.to_mesh(mesh)
1225
+ edit_mesh.free()
1226
+ if tree is not None:
1227
+ restored = [None] * len(mesh.loops)
1228
+ keys, corner_indices = _corner_keys(mesh)
1229
+ for key, loop_index in zip(keys, corner_indices):
1230
+ restored[loop_index] = tuple(normals[tree.find(key)[1]])
1231
+ mesh.normals_split_custom_set(restored)
1232
+ return {"removed_vertices": before - len(mesh.vertices), "kept_normals": tree is not None}
1233
+
1234
+
1235
+ # --- modifiers and UVs ---------------------------------------------------------------------------------------
1236
+
1237
+ def mirror(obj: bpy.types.Object, axis: str = "X", merge_distance: float = 0.0001) -> bpy.types.MirrorModifier:
1238
+ """
1239
+ Mirrors a half-built part across its local axis, welding and clipping at the centre line. Check the
1240
+ reference is actually symmetric before relying on it.
1241
+
1242
+ :param obj: Mesh object (model one half, on the positive side of the axis).
1243
+ :param axis: "X", "Y" or "Z".
1244
+ :param merge_distance: Centre-line weld distance in metres.
1245
+ :returns: The Mirror modifier.
1246
+ """
1247
+ modifier = obj.modifiers.new("Mirror", "MIRROR")
1248
+ modifier.use_axis = [name == axis for name in ("X", "Y", "Z")]
1249
+ modifier.use_clip = True
1250
+ modifier.use_mirror_merge = True
1251
+ modifier.merge_threshold = merge_distance
1252
+ return modifier
1253
+
1254
+
1255
+ def apply_modifiers(obj: bpy.types.Object) -> bpy.types.Object:
1256
+ """
1257
+ Bakes the modifier stack into the mesh without operators. Keeps every data layer (vertex groups,
1258
+ UVs, attributes) and the mesh's name, so a re-run does not create `.001` names. A stack whose output
1259
+ holds Geometry Nodes instances is realised first: `new_from_object` (like `modifier_apply`) keeps only
1260
+ the mesh component and silently drops every instance (measured on 5.3.0).
1261
+
1262
+ :param obj: Mesh object.
1263
+ :returns: The same object.
1264
+ """
1265
+ if gn.instance_count(obj):
1266
+ gn.realize_to_mesh(obj)
1267
+ return obj
1268
+ depsgraph = bpy.context.evaluated_depsgraph_get()
1269
+ evaluated = obj.evaluated_get(depsgraph)
1270
+ baked = bpy.data.meshes.new_from_object(evaluated, preserve_all_data_layers=True, depsgraph=depsgraph)
1271
+ old_mesh = obj.data
1272
+ mesh_name = old_mesh.name
1273
+ obj.modifiers.clear()
1274
+ obj.data = baked
1275
+ if old_mesh.users == 0:
1276
+ bpy.data.meshes.remove(old_mesh)
1277
+ baked.name = mesh_name
1278
+ return obj
1279
+
1280
+
1281
+ # --- shared part operations: booleans, radial arrays, LODs --------------------------------------------------
1282
+
1283
+ def evaluated_volume(obj: bpy.types.Object) -> float:
1284
+ """Signed volume of the object's evaluated (modifiers applied) mesh, cubic metres."""
1285
+ edit_mesh = bmesh.new()
1286
+ edit_mesh.from_object(obj, bpy.context.evaluated_depsgraph_get())
1287
+ volume = edit_mesh.calc_volume(signed=True)
1288
+ edit_mesh.free()
1289
+ return volume
1290
+
1291
+
1292
+ def edges_between(edit_mesh: bmesh.types.BMesh, first_faces: set, second_faces: set) -> list:
1293
+ """
1294
+ Edges shared by one face of each set: the line where two regions meet (a cut rim, a floor corner).
1295
+
1296
+ :param edit_mesh: The bmesh the faces belong to.
1297
+ :param first_faces: A set of BMFace.
1298
+ :param second_faces: Another set of BMFace.
1299
+ :returns: The BMEdge list.
1300
+ """
1301
+ return [edge for edge in edit_mesh.edges if len(edge.link_faces) == EDGE_FACE_COUNT
1302
+ and any(face in first_faces for face in edge.link_faces)
1303
+ and any(face in second_faces for face in edge.link_faces)]
1304
+
1305
+
1306
+ def _recalculate_normals(obj: bpy.types.Object) -> None:
1307
+ """Points every face of a closed mesh outward (a flipped cutter face empties a MANIFOLD boolean)."""
1308
+ edit_mesh = bmesh.new()
1309
+ edit_mesh.from_mesh(obj.data)
1310
+ bmesh.ops.recalc_face_normals(edit_mesh, faces=edit_mesh.faces[:])
1311
+ edit_mesh.to_mesh(obj.data)
1312
+ edit_mesh.free()
1313
+
1314
+
1315
+ def _tag_cutters(cutters: list, cutter_material: bpy.types.Material) -> bpy.types.Collection:
1316
+ """Puts the cutters in one hidden collection with their own material, normals recalculated."""
1317
+ collection = bpy.data.collections.new("_Cutters")
1318
+ bpy.context.scene.collection.children.link(collection)
1319
+ for cutter in cutters:
1320
+ _recalculate_normals(cutter)
1321
+ cutter.data.materials.clear()
1322
+ cutter.data.materials.append(cutter_material)
1323
+ for parent in list(cutter.users_collection):
1324
+ parent.objects.unlink(cutter)
1325
+ collection.objects.link(cutter)
1326
+ cutter.hide_render = True
1327
+ cutter.display_type = "WIRE"
1328
+ return collection
1329
+
1330
+
1331
+ def boolean_cut(obj: bpy.types.Object, cutters: list, solver: str = "EXACT") -> dict:
1332
+ """
1333
+ Cuts every cutter out of a part in ONE boolean (a chain of booleans leaves slivers between cuts),
1334
+ applies it, checks the volume went down, merges coplanar slivers, and returns the rim edges so they
1335
+ can be bevelled. The rim is found by material: the cutters carry a second material into the cut, the
1336
+ edges between target faces and cutter faces are the rim, and the cutter faces are then given the
1337
+ target's material back. Cutters must be closed and overlap the part on every axis they cut through.
1338
+
1339
+ :param obj: Target mesh object (one material slot or none).
1340
+ :param cutters: Closed mesh objects; they are moved into a hidden `_Cutters` collection.
1341
+ :param solver: "EXACT" (robust, the default), "MANIFOLD" (fast, closed meshes only) or "FLOAT".
1342
+ :returns: {"rim_edges": edge indices, "volume_before", "volume_after"}.
1343
+ :raises RuntimeError: when the boolean did not remove volume (a flipped or non-overlapping cutter).
1344
+ """
1345
+ if not obj.data.materials:
1346
+ obj.data.materials.append(bpy.data.materials.new(f"{obj.name}_Material"))
1347
+ cutter_material = bpy.data.materials.new("_CutterFaces")
1348
+ collection = _tag_cutters(cutters, cutter_material)
1349
+ before = evaluated_volume(obj)
1350
+ modifier = obj.modifiers.new("Cut", "BOOLEAN")
1351
+ modifier.operation, modifier.operand_type, modifier.collection = "DIFFERENCE", "COLLECTION", collection
1352
+ modifier.solver, modifier.material_mode = solver, "TRANSFER"
1353
+ after = evaluated_volume(obj)
1354
+ if not 0.0 < after < before:
1355
+ raise RuntimeError(f"boolean did not cut: volume {before:.6f} -> {after:.6f}")
1356
+ apply_modifiers(obj)
1357
+ edit_mesh = bmesh.new()
1358
+ edit_mesh.from_mesh(obj.data)
1359
+ bmesh.ops.dissolve_limit(edit_mesh, angle_limit=math.radians(BOOLEAN_CLEANUP_DEGREES),
1360
+ verts=edit_mesh.verts[:], edges=edit_mesh.edges[:])
1361
+ cut_faces = {face for face in edit_mesh.faces if face.material_index == CUTTER_MATERIAL_SLOT}
1362
+ rim = edges_between(edit_mesh, cut_faces, set(edit_mesh.faces) - cut_faces)
1363
+ for face in cut_faces:
1364
+ face.material_index = 0
1365
+ edit_mesh.edges.index_update()
1366
+ rim_indices = sorted(edge.index for edge in rim)
1367
+ edit_mesh.to_mesh(obj.data)
1368
+ edit_mesh.free()
1369
+ obj.data.update()
1370
+ obj.data.materials.pop(index=CUTTER_MATERIAL_SLOT)
1371
+ return {"rim_edges": rim_indices, "volume_before": round(before, 9), "volume_after": round(after, 9)}
1372
+
1373
+
1374
+ def radial_array(obj: bpy.types.Object, count: int, axis: str = "X") -> None:
1375
+ """
1376
+ Repeats a part `count` times around its object's origin (tread blocks, spokes, bolts, fan blades):
1377
+ an Array modifier whose offset object is an empty turned by 360 / count, then applied. Build the one
1378
+ part at its place on the circle, with the object origin on the rotation axis.
1379
+
1380
+ :param obj: Mesh object, origin on the axis.
1381
+ :param count: Copies around the full circle.
1382
+ :param axis: "X", "Y" or "Z" (local).
1383
+ """
1384
+ # matrix_world is stale after a script sets .location until the view layer updates; the pivot is placed
1385
+ # from it, so read it fresh.
1386
+ bpy.context.view_layer.update()
1387
+ pivot = bpy.data.objects.new(f"_{obj.name}_ArrayPivot", None)
1388
+ bpy.context.scene.collection.objects.link(pivot)
1389
+ pivot.matrix_world = obj.matrix_world @ Matrix.Rotation(2.0 * math.pi / count, 4, axis)
1390
+ array = obj.modifiers.new("RadialArray", "ARRAY")
1391
+ array.count = count
1392
+ array.use_relative_offset = False
1393
+ array.use_object_offset = True
1394
+ array.offset_object = pivot
1395
+ apply_modifiers(obj)
1396
+ bpy.data.objects.remove(pivot)
1397
+
1398
+
1399
+ def lod_base_name(name: str) -> str:
1400
+ """The name without a trailing _LOD<n> (the name an LOD set is addressed by)."""
1401
+ head, separator, tail = name.rpartition(LOD_SUFFIX)
1402
+ return head if separator and tail.isdigit() else name
1403
+
1404
+
1405
+ def _triangle_count(obj: bpy.types.Object) -> int:
1406
+ """Triangles the mesh draws as."""
1407
+ return sum(len(polygon.vertices) - 2 for polygon in obj.data.polygons)
1408
+
1409
+
1410
+ def copy_object(obj: bpy.types.Object, name: str) -> bpy.types.Object:
1411
+ """A full copy (own mesh data) linked to the object's collections."""
1412
+ copy = obj.copy()
1413
+ copy.data = obj.data.copy()
1414
+ copy.name = name
1415
+ copy.data.name = name
1416
+ for collection in obj.users_collection:
1417
+ collection.objects.link(copy)
1418
+ return copy
1419
+
1420
+
1421
+ def _parent_levels(levels: list, base: str) -> bpy.types.Object:
1422
+ """Parents the levels to an Empty named `base` placed at LOD0's origin, keeping their world transforms."""
1423
+ bpy.context.view_layer.update()
1424
+ old = bpy.data.objects.get(base)
1425
+ if old is not None and old.type == "EMPTY":
1426
+ bpy.data.objects.remove(old)
1427
+ root = bpy.data.objects.new(base, None)
1428
+ for collection in levels[0].users_collection:
1429
+ collection.objects.link(root)
1430
+ root.matrix_world = levels[0].matrix_world.copy()
1431
+ for level in levels:
1432
+ world = level.matrix_world.copy()
1433
+ level.parent = root
1434
+ level.matrix_world = world
1435
+ return root
1436
+
1437
+
1438
+ def lod_chain(obj: bpy.types.Object, ratios=(0.5, 0.25), transfer_normals: bool = True,
1439
+ parent: bool = True, name_source: bool = True) -> list:
1440
+ """
1441
+ Builds LOD1.. from LOD0 by collapse decimation and names the set <Name>_LOD0, <Name>_LOD1, ... . Each level
1442
+ receives LOD0's shading by a Data Transfer of custom normals (corner normals, nearest face corner), so the
1443
+ silhouette simplifies while the lighting stays put; without it, a level re-smooths its own faces and pops
1444
+ when it switches. Every level gets the same materials (the same draw-call cost each). The Decimate ratio
1445
+ counts triangles, so each level's ratio is taken against LOD0's triangle count.
1446
+
1447
+ :param obj: The full-detail mesh (modifiers are applied first).
1448
+ :param ratios: Triangle ratio of each lower level against LOD0 (Unity's own guidance: each level about half
1449
+ the previous one).
1450
+ :param transfer_normals: Copy LOD0's corner normals onto every level.
1451
+ :param parent: Parent the levels to an Empty named <Name> at LOD0's origin (Unity puts the LOD Group on the
1452
+ FBX root; in glTF the Empty becomes the node a loader addresses the set by).
1453
+ :param name_source: Rename the source <Name>_LOD0 (False keeps its name; the levels are still <Name>_LOD1..).
1454
+ :returns: [LOD0, LOD1, ...].
1455
+ """
1456
+ apply_modifiers(obj)
1457
+ base = lod_base_name(obj.name)
1458
+ if name_source:
1459
+ obj.name = f"{base}{LOD_SUFFIX}0"
1460
+ obj.data.name = obj.name
1461
+ levels = [obj]
1462
+ source_triangles = _triangle_count(obj)
1463
+ for level, ratio in enumerate(ratios, start=1):
1464
+ lod = copy_object(obj, f"{base}{LOD_SUFFIX}{level}")
1465
+ decimate = lod.modifiers.new("Decimate", "DECIMATE")
1466
+ decimate.decimate_type = "COLLAPSE"
1467
+ decimate.ratio = ratio * source_triangles / max(_triangle_count(lod), 1)
1468
+ decimate.use_collapse_triangulate = True
1469
+ if transfer_normals:
1470
+ transfer = lod.modifiers.new("LOD0 normals", "DATA_TRANSFER")
1471
+ transfer.object = obj
1472
+ transfer.use_loop_data = True
1473
+ transfer.data_types_loops = {"CUSTOM_NORMAL"}
1474
+ transfer.loop_mapping = LOD_NORMAL_TRANSFER_MAPPING
1475
+ apply_modifiers(lod)
1476
+ levels.append(lod)
1477
+ if parent:
1478
+ _parent_levels(levels, base)
1479
+ return levels
1480
+
1481
+
1482
+ def smart_unwrap(obj: bpy.types.Object, angle_limit_degrees: float = 66.0, island_margin: float = 0.02) -> None:
1483
+ """
1484
+ Gives a mesh a quick Smart UV Project layout (enough for QA and checker renders; use bt-unwrap for a
1485
+ production layout and texture).
1486
+
1487
+ :param obj: Mesh object.
1488
+ :param angle_limit_degrees: Faces bending more than this start a new island.
1489
+ :param island_margin: Gap between islands, in UV units.
1490
+ :raises RuntimeError: when the operator does not finish.
1491
+ """
1492
+ view_layer = bpy.context.view_layer
1493
+ for candidate in view_layer.objects:
1494
+ candidate.select_set(candidate == obj)
1495
+ view_layer.objects.active = obj
1496
+ with bpy.context.temp_override(object=obj, active_object=obj, selected_objects=[obj],
1497
+ selected_editable_objects=[obj]):
1498
+ bpy.ops.object.mode_set(mode="EDIT")
1499
+ bpy.ops.mesh.select_all(action="SELECT")
1500
+ outcome = bpy.ops.uv.smart_project(angle_limit=math.radians(angle_limit_degrees), island_margin=island_margin)
1501
+ bpy.ops.object.mode_set(mode="OBJECT")
1502
+ if "FINISHED" not in outcome:
1503
+ raise RuntimeError(f"smart UV project did not finish: {outcome}")
1504
+
1505
+
1506
+ # --- SDF inflate ---------------------------------------------------------------------------------------------
1507
+ #
1508
+ # The inflate field below is ported from colinurbs/claude-modeling-skills
1509
+ # (skills/reference-modeling/scripts/sdf_mesher.py) -- Copyright (c) 2026 Colin Urban, MIT License:
1510
+ #
1511
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
1512
+ # of this software and associated documentation files (the "Software"), to deal
1513
+ # in the Software without restriction, including without limitation the rights
1514
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1515
+ # copies of the Software, and to permit persons to whom the Software is
1516
+ # furnished to do so, subject to the following conditions:
1517
+ #
1518
+ # The above copyright notice and this permission notice shall be included in all
1519
+ # copies or substantial portions of the Software.
1520
+ #
1521
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1522
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1523
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1524
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1525
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1526
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1527
+ # SOFTWARE.
1528
+ #
1529
+ # Changes: runs inside Blender with numpy only (no scipy / scikit-image): signed distances come from a
1530
+ # KD-tree over the outline, the surface is extracted with surface nets (quads) instead of marching
1531
+ # cubes, and lengths are metres throughout.
1532
+
1533
+ def _as_field(value, shape: tuple) -> np.ndarray:
1534
+ """A scalar or (height, width) array as a float32 field of the mask's shape."""
1535
+ if np.isscalar(value):
1536
+ return np.full(shape, float(value), dtype=np.float32)
1537
+ field = np.asarray(value, dtype=np.float32)
1538
+ if field.shape != shape:
1539
+ raise ValueError(f"field shape {field.shape} does not match the mask {shape}")
1540
+ return field
1541
+
1542
+
1543
+ def _outline_tree(mask: np.ndarray, pixels_per_metre: float, origin_column: float, origin_row: float) -> KDTree:
1544
+ """KD-tree of the mask outline (midpoints between inside and outside pixels) in world (y, z)."""
1545
+ padded = np.pad(mask, 1)
1546
+ points = []
1547
+ for row_shift, column_shift in ((0, 1), (1, 0)):
1548
+ first = padded[:padded.shape[0] - row_shift, :padded.shape[1] - column_shift]
1549
+ second = padded[row_shift:, column_shift:]
1550
+ rows, columns = np.nonzero(first != second)
1551
+ # The shared side of the two differing pixels, in unpadded continuous pixel coordinates: a
1552
+ # left/right pair meets on a column line at a row centre, an up/down pair on a row line.
1553
+ points.append(np.column_stack((columns - 0.5 * (1 - column_shift), rows - 0.5 * (1 - row_shift))))
1554
+ outline = np.concatenate(points)
1555
+ tree = KDTree(len(outline))
1556
+ for index, (column, row) in enumerate(outline):
1557
+ tree.insert(((column - origin_column) / pixels_per_metre, (origin_row - row) / pixels_per_metre, 0.0), index)
1558
+ tree.balance()
1559
+ return tree
1560
+
1561
+
1562
+ def _signed_distance(mask: np.ndarray, tree: KDTree, grid_y: np.ndarray, grid_z: np.ndarray,
1563
+ pixels_per_metre: float, origin_column: float, origin_row: float) -> np.ndarray:
1564
+ """Signed distance (metres, positive inside) from grid points to the mask outline."""
1565
+ columns = np.clip(np.floor(origin_column + grid_y * pixels_per_metre).astype(int), 0, mask.shape[1] - 1)
1566
+ rows = np.clip(np.floor(origin_row - grid_z * pixels_per_metre).astype(int), 0, mask.shape[0] - 1)
1567
+ inside = mask[rows, columns]
1568
+ distances = np.array([tree.find((y, z, 0.0))[2] for y, z in zip(grid_y.ravel(), grid_z.ravel())])
1569
+ return np.where(inside.ravel(), distances, -distances).reshape(grid_y.shape)
1570
+
1571
+
1572
+ def _sample_field(field: np.ndarray, grid_y: np.ndarray, grid_z: np.ndarray, pixels_per_metre: float,
1573
+ origin_column: float, origin_row: float) -> np.ndarray:
1574
+ """Nearest-pixel lookup of an image-aligned field at world (y, z) grid points."""
1575
+ columns = np.clip(np.floor(origin_column + grid_y * pixels_per_metre).astype(int), 0, field.shape[1] - 1)
1576
+ rows = np.clip(np.floor(origin_row - grid_z * pixels_per_metre).astype(int), 0, field.shape[0] - 1)
1577
+ return field[rows, columns]
1578
+
1579
+
1580
+ def _surface_nets(field: np.ndarray, origin: np.ndarray, step: float) -> tuple:
1581
+ """
1582
+ Extracts the zero level set of a sampled field (negative inside) as a quad mesh: one vertex per
1583
+ boundary cell at the average of its edge crossings, one quad per crossing grid edge.
1584
+ """
1585
+ cells_shape = tuple(size - 1 for size in field.shape)
1586
+ vertex_sum = np.zeros(cells_shape + (3,))
1587
+ vertex_count = np.zeros(cells_shape)
1588
+ crossings = []
1589
+ for axis in range(3):
1590
+ low = np.take(field, np.arange(field.shape[axis] - 1), axis=axis)
1591
+ high = np.take(field, np.arange(1, field.shape[axis]), axis=axis)
1592
+ crossing = (low < 0) != (high < 0)
1593
+ indices = np.column_stack(np.nonzero(crossing))
1594
+ fraction = low[crossing] / (low[crossing] - high[crossing])
1595
+ points = indices.astype(np.float64)
1596
+ points[:, axis] += fraction
1597
+ others = [(axis + 1) % 3, (axis + 2) % 3]
1598
+ cell_sets = []
1599
+ for first_offset, second_offset in ((-1, -1), (0, -1), (0, 0), (-1, 0)):
1600
+ cells = indices.copy()
1601
+ cells[:, others[0]] += first_offset
1602
+ cells[:, others[1]] += second_offset
1603
+ cell_sets.append(cells)
1604
+ valid = np.all((cells >= 0) & (cells < np.array(cells_shape)), axis=1)
1605
+ np.add.at(vertex_sum, tuple(cells[valid].T), points[valid])
1606
+ np.add.at(vertex_count, tuple(cells[valid].T), 1.0)
1607
+ crossings.append((cell_sets, low[crossing] < 0))
1608
+ occupied = vertex_count > 0
1609
+ vertex_index = np.full(cells_shape, -1, dtype=np.int64)
1610
+ vertex_index[occupied] = np.arange(int(occupied.sum()))
1611
+ vertices = vertex_sum[occupied] / vertex_count[occupied][:, None] * step + origin
1612
+ faces = []
1613
+ for cell_sets, low_inside in crossings:
1614
+ corner_indices = np.column_stack([vertex_index[tuple(cells.T)] for cells in cell_sets])
1615
+ complete = np.all(corner_indices >= 0, axis=1)
1616
+ # Quads wind counter-clockwise around +axis; flip where the inside is on the high side.
1617
+ oriented = np.where(low_inside[:, None], corner_indices, corner_indices[:, ::-1])
1618
+ faces.append(oriented[complete])
1619
+ return vertices, np.concatenate(faces)
1620
+
1621
+
1622
+ def sdf_inflate(name: str, mask: np.ndarray, pixels_per_metre: float, width, corner_radius, exponent=2.5,
1623
+ origin_pixel=None, voxel_size=None, rounding_mask=None, recess_depth=None,
1624
+ field_blur_pixels: float = 0.0) -> bpy.types.Object:
1625
+ """
1626
+ Inflates a moulded part from one side-view mask: the section across the part is a superellipse whose
1627
+ width, edge-rounding reach and squareness come from per-pixel fields, so width and roundness change
1628
+ smoothly along the part (housings, grips, shells, cast parts). The mask is the right view (image
1629
+ right = world +Y, image up = +Z); the part is inflated symmetrically along X.
1630
+
1631
+ Near the outline the section is (|x| / a)^p + v^p = 1 with a = width / 2, v = max(r - d, 0) / r and d
1632
+ the signed distance to the outline; that field is C1 across x = 0, so the silhouette equator is clean.
1633
+ The result is dense and smooth: decimate it, or use it as a shrinkwrap / bake target for a quad loft.
1634
+
1635
+ :param name: Object and mesh name.
1636
+ :param mask: Boolean (height, width) side-view mask, row 0 at the top.
1637
+ :param pixels_per_metre: Mask scale.
1638
+ :param width: Full part width in metres: a scalar or a field of the mask's shape.
1639
+ :param corner_radius: How far in from the outline the rounding reaches, metres (scalar or field).
1640
+ :param exponent: Superellipse exponent: 2 is round, 4+ boxy with a small fillet (scalar or field).
1641
+ :param origin_pixel: (column, row) of world y = 0, z = 0; default the mask's bottom-left corner.
1642
+ :param voxel_size: Sampling step in metres; default the largest dimension / 120.
1643
+ :param rounding_mask: Mask the rounding is measured against. Extend it past edges that must be cut
1644
+ flat (where the part meets another part); the solid is still clipped to `mask` there.
1645
+ :param recess_depth: Field of crisp recesses (metres) subtracted from the width, not blurred.
1646
+ :param field_blur_pixels: Gaussian blur of the width / radius / exponent fields, so regions blend.
1647
+ :returns: The new smooth-shaded quad mesh object.
1648
+ :raises ValueError: for an empty mask, mismatched fields or a grid over the voxel budget.
1649
+ """
1650
+ import image_measure
1651
+
1652
+ mask = np.asarray(mask, dtype=bool)
1653
+ if not mask.any():
1654
+ raise ValueError("sdf_inflate needs a non-empty mask")
1655
+ shape = mask.shape
1656
+ origin_column, origin_row = origin_pixel if origin_pixel is not None else (0.0, float(shape[0]))
1657
+ width_field, radius_field, exponent_field = (
1658
+ image_measure.gaussian_blur(_as_field(value, shape), field_blur_pixels)
1659
+ for value in (width, corner_radius, exponent))
1660
+ if recess_depth is not None:
1661
+ width_field = width_field - _as_field(recess_depth, shape)
1662
+ bounds = image_measure.subject_bounds(mask)
1663
+ y_range = ((bounds[0] - origin_column) / pixels_per_metre, (bounds[2] - origin_column) / pixels_per_metre)
1664
+ z_range = ((origin_row - bounds[3]) / pixels_per_metre, (origin_row - bounds[1]) / pixels_per_metre)
1665
+ half_width = float(width_field[mask].max()) / 2.0
1666
+ step = voxel_size or max(y_range[1] - y_range[0], z_range[1] - z_range[0], 2.0 * half_width) / SDF_DEFAULT_DIVISIONS
1667
+ padding = SDF_PADDING_VOXELS * step
1668
+ # The extra half step makes np.arange include the far padded end.
1669
+ axes = [np.arange(low - padding, high + padding + 0.5 * step, step)
1670
+ for low, high in ((-half_width, half_width), y_range, z_range)]
1671
+ voxel_count = len(axes[0]) * len(axes[1]) * len(axes[2])
1672
+ if voxel_count > SDF_MAXIMUM_VOXELS:
1673
+ raise ValueError(f"{voxel_count} voxels is over the budget of {SDF_MAXIMUM_VOXELS}; use a larger voxel_size")
1674
+ grid_y, grid_z = np.meshgrid(axes[1], axes[2], indexing="ij")
1675
+ frame = (pixels_per_metre, origin_column, origin_row)
1676
+ round_against = mask if rounding_mask is None else np.asarray(rounding_mask, dtype=bool)
1677
+ distance = _signed_distance(round_against, _outline_tree(round_against, *frame), grid_y, grid_z, *frame)
1678
+ half = np.maximum(_sample_field(width_field, grid_y, grid_z, *frame) / 2.0, step / 2.0)
1679
+ radius = np.maximum(_sample_field(radius_field, grid_y, grid_z, *frame), GEOMETRY_EPSILON)
1680
+ power = np.maximum(_sample_field(exponent_field, grid_y, grid_z, *frame), 1.0)
1681
+ reach = np.maximum(radius - distance, 0.0) / radius
1682
+ across = np.abs(axes[0])[:, None, None] / half[None, :, :]
1683
+ field = across ** power[None, :, :] + (reach ** power)[None, :, :] - 1.0
1684
+ if rounding_mask is not None:
1685
+ clip_distance = _signed_distance(mask, _outline_tree(mask, *frame), grid_y, grid_z, *frame)
1686
+ cap_gradient = float(np.mean(power)) / float(np.mean(half))
1687
+ field = np.maximum(field, (-clip_distance * cap_gradient)[None, :, :])
1688
+ field[0], field[-1], field[:, 0], field[:, -1], field[:, :, 0], field[:, :, -1] = (1.0,) * 6
1689
+ origin = np.array([axes[0][0], axes[1][0], axes[2][0]])
1690
+ vertices, faces = _surface_nets(field, origin, step)
1691
+ mesh = bpy.data.meshes.new(name)
1692
+ mesh.from_pydata(vertices.tolist(), [], faces.tolist())
1693
+ mesh.validate()
1694
+ edit_mesh = bmesh.new()
1695
+ edit_mesh.from_mesh(mesh)
1696
+ bmesh.ops.recalc_face_normals(edit_mesh, faces=edit_mesh.faces[:])
1697
+ for face in edit_mesh.faces:
1698
+ face.smooth = True
1699
+ pinched = any(len(edge.link_faces) != 2 for edge in edit_mesh.edges)
1700
+ edit_mesh.to_mesh(mesh)
1701
+ edit_mesh.free()
1702
+ obj = _link_new_object(name, mesh)
1703
+ if pinched:
1704
+ _close_pinches(obj, step)
1705
+ return obj
1706
+
1707
+
1708
+ def _close_pinches(obj: bpy.types.Object, step: float) -> None:
1709
+ """
1710
+ Surface nets gives one vertex per cell, so where two sheets of surface pass through one cell (at a
1711
+ sharp corner of the outline) the mesh pinches into a non-manifold edge. A voxel remesh at the same
1712
+ resolution rebuilds a closed, manifold quad surface without visibly changing the shape.
1713
+ """
1714
+ remesh = obj.modifiers.new("ClosePinches", "REMESH")
1715
+ remesh.mode = "VOXEL"
1716
+ remesh.voxel_size = step
1717
+ remesh.use_smooth_shade = True
1718
+ apply_modifiers(obj)
1719
+
1720
+
1721
+ # --- blueprint and traces ----------------------------------------------------------------------------------
1722
+
1723
+ def load_blueprint(path: str) -> bpy.types.Collection:
1724
+ """
1725
+ Appends the blueprint made by the `blueprint` tool (the reference images as planes at world scale in their
1726
+ view planes, an orthographic camera per view and the wire box at the known dimensions) into the current
1727
+ scene, so a build script models over the references. Every blueprint object's name starts with "_", so no
1728
+ tool measures or exports it.
1729
+
1730
+ :param path: The blueprint .blend.
1731
+ :returns: The linked-in blueprint collection.
1732
+ :raises FileNotFoundError: when the file does not exist.
1733
+ :raises ValueError: when the file holds no blueprint collection.
1734
+ """
1735
+ absolute = os.path.abspath(path)
1736
+ if not os.path.isfile(absolute):
1737
+ raise FileNotFoundError(f"blueprint not found: {absolute} (run the blueprint tool first)")
1738
+ with bpy.data.libraries.load(absolute, link=False) as (source, target):
1739
+ if BLUEPRINT_COLLECTION not in source.collections:
1740
+ raise ValueError(f"{absolute} has no '{BLUEPRINT_COLLECTION}' collection")
1741
+ target.collections = [BLUEPRINT_COLLECTION]
1742
+ collection = target.collections[0]
1743
+ bpy.context.scene.collection.children.link(collection)
1744
+ return collection
1745
+
1746
+
1747
+ def load_traces(path: str) -> reference_traces.TraceSet:
1748
+ """
1749
+ Reads the `trace` tool's traces.json: named design curves as (N, 3) world points (`.curve(name)`,
1750
+ `.curves`), each view's outline on its plane (`.outline(view)`, `.outline_points(view, depth)`), and
1751
+ station lookups (`.outline_boundary(view, axis, value, side)`, `.outline_extent(view, axis, value)`).
1752
+ Lay blockout sections, cage lines and loft rails on these, then `stamp_traces` the parts.
1753
+
1754
+ :param path: traces.json.
1755
+ :returns: The TraceSet.
1756
+ """
1757
+ return reference_traces.load_traces(path)
1758
+
1759
+
1760
+ def stamp_traces(objects, path: str) -> str:
1761
+ """
1762
+ Marks parts as built on a traces file: writes its SHA-256 to each object's `bt_traces` custom property.
1763
+ When a spec carries "require_traces", `world-gate` and `measure-stations` fail any measured part whose
1764
+ stamp is missing or belongs to an older traces file. Stamp only what was really built on the curves.
1765
+
1766
+ :param objects: The parts.
1767
+ :param path: traces.json.
1768
+ :returns: The SHA-256 written.
1769
+ """
1770
+ return reference_traces.stamp_objects(objects, path)