@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,374 @@
1
+ """
2
+ bt-blender hard-surface panels: the cut and finishing operations professional hard-surface modellers use
3
+ on a cage or a mid-poly mesh, done on data (bmesh) so they run headless and give the same result every run.
4
+
5
+ import construction_kit as kit
6
+ import hard_surface_panels as panels
7
+
8
+ plate = panels.grid_plate("Panel", 0.60, 0.40, 0.04, columns=6, rows=4)
9
+ recess = panels.inset_recess(plate, panels.top_faces_in(plate, (-0.15, 0.15), (-0.10, 0.10)), 0.02, 0.012)
10
+ kit.subdivision_cage(plate, levels=2, holding_corner_radius=0.004,
11
+ holding_edges=recess["rim_edges"] + recess["floor_edges"] + panels.outline_edges(plate))
12
+
13
+ What is in it:
14
+ - a cage to cut into: grid_plate (a slab with a quad grid on top, so every cut lands on existing loops);
15
+ - picking faces and edges by position (headless scripts cannot click): top_faces_in, edges_between,
16
+ outline_edges;
17
+ - cuts that stay subdivision-friendly because they follow the grid: inset_recess (a recessed panel or
18
+ hatch, vertical walls), panel_groove (a V panel line from two insets), round_hole (a socket whose side
19
+ count is the grid patch's boundary count: 8 on a 2 x 2 patch, 16 on 4 x 4);
20
+ - the mid-poly route: boolean_cut (every cutter in one cut, volume-checked, rim edges found by material;
21
+ it lives in construction_kit and is re-exported here, as are evaluated_volume and edges_between),
22
+ mid_poly_finish (angle bevel with hardened normals, then face-area weighted normals), transfer_normals
23
+ (copy smooth normals from an uncut proxy so shading flows around cuts).
24
+
25
+ Lengths are metres. Every function that changes topology returns edge or face indices valid for the mesh
26
+ it leaves behind, so the next step (holding loops, sharp design lines) can use them directly.
27
+ """
28
+ import math
29
+
30
+ import bmesh
31
+ import bpy
32
+ import numpy as np
33
+ from mathutils import Vector
34
+
35
+ import construction_kit as kit
36
+
37
+ # A face counts as facing up when its normal's Z is at least this.
38
+ UP_FACING = 0.9
39
+
40
+ # Two face sets touch along an edge when it is shared by one face of each.
41
+ EDGE_FACE_COUNT = 2
42
+
43
+ # Coplanar faces within this angle are merged after a boolean (dissolve_limit), in degrees, and the material
44
+ # slot the cutters bring into a boolean so the rim edges can be found afterwards (the kit's values).
45
+ BOOLEAN_CLEANUP_DEGREES = kit.BOOLEAN_CLEANUP_DEGREES
46
+ CUTTER_MATERIAL_SLOT = kit.CUTTER_MATERIAL_SLOT
47
+
48
+ # Mid-poly defaults: bevel angle limit in degrees, and the Weighted Normal modifier's weight (50 = neutral).
49
+ MID_POLY_ANGLE_DEGREES = 30.0
50
+ WEIGHTED_NORMAL_WEIGHT = 50
51
+
52
+ # Bevel profile shape that gives a circular (fillet) cross-section.
53
+ CIRCULAR_PROFILE = 0.5
54
+
55
+
56
+ # --- building and picking ------------------------------------------------------------------------------------
57
+
58
+ def grid_plate(name: str, width: float, depth: float, thickness: float, columns: int, rows: int) -> bpy.types.Object:
59
+ """
60
+ A slab with a regular quad grid on its top face: the cage that panel cuts are made into. The grid's
61
+ lines are where cuts may start and end, so choose columns and rows so that every planned cut lands on
62
+ grid lines (a hatch 0.30 m wide on a 0.60 m plate wants an even column count).
63
+
64
+ :param name: Object and mesh name.
65
+ :param width: Size along X in metres (centred on 0).
66
+ :param depth: Size along Y in metres (centred on 0).
67
+ :param thickness: Size along Z in metres (bottom at z = 0).
68
+ :param columns: Grid faces along X.
69
+ :param rows: Grid faces along Y.
70
+ :returns: The new object, linked to the scene, with outward normals.
71
+ :raises ValueError: for non-positive sizes or counts.
72
+ """
73
+ if min(width, depth, thickness) <= 0 or columns < 1 or rows < 1:
74
+ raise ValueError("grid_plate needs positive sizes and at least one column and row")
75
+ edit_mesh = bmesh.new()
76
+ grid = [[edit_mesh.verts.new((-width / 2 + width * column / columns, -depth / 2 + depth * row / rows, 0.0))
77
+ for column in range(columns + 1)] for row in range(rows + 1)]
78
+ faces = [edit_mesh.faces.new((grid[row][column], grid[row][column + 1], grid[row + 1][column + 1], grid[row + 1][column]))
79
+ for row in range(rows) for column in range(columns)]
80
+ extruded = bmesh.ops.extrude_face_region(edit_mesh, geom=faces)
81
+ lifted = [element for element in extruded["geom"] if isinstance(element, bmesh.types.BMVert)]
82
+ bmesh.ops.translate(edit_mesh, verts=lifted, vec=(0.0, 0.0, thickness))
83
+ bmesh.ops.recalc_face_normals(edit_mesh, faces=edit_mesh.faces[:])
84
+ mesh = bpy.data.meshes.new(name)
85
+ edit_mesh.to_mesh(mesh)
86
+ edit_mesh.free()
87
+ obj = bpy.data.objects.new(name, mesh)
88
+ bpy.context.scene.collection.objects.link(obj)
89
+ return obj
90
+
91
+
92
+ def top_faces_in(obj: bpy.types.Object, x_range: tuple, y_range: tuple) -> list:
93
+ """
94
+ Indices of the up-facing faces whose centres lie inside a rectangle (object space): how a script picks
95
+ the region of a cut.
96
+
97
+ :param obj: Mesh object.
98
+ :param x_range: (minimum, maximum) X in metres.
99
+ :param y_range: (minimum, maximum) Y in metres.
100
+ :returns: Face indices, ascending.
101
+ """
102
+ return [polygon.index for polygon in obj.data.polygons
103
+ if polygon.normal.z >= UP_FACING
104
+ and x_range[0] <= polygon.center.x <= x_range[1] and y_range[0] <= polygon.center.y <= y_range[1]]
105
+
106
+
107
+ # The line where two face regions meet; shared with construction_kit (one copy).
108
+ edges_between = kit.edges_between
109
+
110
+
111
+ def outline_edges(obj: bpy.types.Object, crease_degrees: float = 60.0) -> list:
112
+ """
113
+ Indices of the edges where the faces meet at more than `crease_degrees`: the outer corners of a slab
114
+ or a box, which need holding loops before subdivision.
115
+
116
+ :param obj: Mesh object.
117
+ :param crease_degrees: Smallest dihedral angle (between face normals) that counts as a corner.
118
+ :returns: Edge indices.
119
+ """
120
+ edit_mesh = bmesh.new()
121
+ edit_mesh.from_mesh(obj.data)
122
+ limit = math.radians(crease_degrees)
123
+ indices = [edge.index for edge in edit_mesh.edges
124
+ if len(edge.link_faces) == EDGE_FACE_COUNT and edge.calc_face_angle(0.0) >= limit]
125
+ edit_mesh.free()
126
+ return indices
127
+
128
+
129
+ def _region_normal(faces: list) -> Vector:
130
+ """Area-weighted average normal of a face region."""
131
+ total = Vector()
132
+ for face in faces:
133
+ total += face.normal * face.calc_area()
134
+ return total.normalized()
135
+
136
+
137
+ def _write_back(obj: bpy.types.Object, edit_mesh: bmesh.types.BMesh, edge_sets: dict, face_sets: dict) -> dict:
138
+ """Indexes the bmesh, collects the named element sets as index lists, writes the mesh and frees the bmesh."""
139
+ edit_mesh.verts.index_update()
140
+ edit_mesh.edges.index_update()
141
+ edit_mesh.faces.index_update()
142
+ report = {name: sorted(edge.index for edge in edges) for name, edges in edge_sets.items()}
143
+ report.update({name: sorted(face.index for face in faces) for name, faces in face_sets.items()})
144
+ edit_mesh.to_mesh(obj.data)
145
+ edit_mesh.free()
146
+ obj.data.update()
147
+ return report
148
+
149
+
150
+ def _faces_of(obj: bpy.types.Object, face_indices: list) -> tuple:
151
+ """A bmesh of the object and the BMFace list for the indices."""
152
+ if not face_indices:
153
+ raise ValueError("no faces given: pick the region with top_faces_in first")
154
+ edit_mesh = bmesh.new()
155
+ edit_mesh.from_mesh(obj.data)
156
+ edit_mesh.faces.ensure_lookup_table()
157
+ return edit_mesh, [edit_mesh.faces[index] for index in face_indices]
158
+
159
+
160
+ def _sink_region(edit_mesh: bmesh.types.BMesh, faces: list, depth: float) -> tuple:
161
+ """Extrudes a face region straight down its normal by `depth`; returns (floor faces, wall faces)."""
162
+ normal = _region_normal(faces)
163
+ extruded = bmesh.ops.extrude_face_region(edit_mesh, geom=faces)
164
+ floor = {element for element in extruded["geom"] if isinstance(element, bmesh.types.BMFace)}
165
+ floor_verts = [element for element in extruded["geom"] if isinstance(element, bmesh.types.BMVert)]
166
+ bmesh.ops.translate(edit_mesh, verts=floor_verts, vec=-normal * depth)
167
+ # FACES (not FACES_ONLY) also removes the edges inside the old region, which would be left as wire edges.
168
+ bmesh.ops.delete(edit_mesh, geom=[face for face in faces if face.is_valid], context="FACES")
169
+ walls = {face for vertex in floor_verts for face in vertex.link_faces if face not in floor}
170
+ bmesh.ops.recalc_face_normals(edit_mesh, faces=edit_mesh.faces[:])
171
+ return floor, walls
172
+
173
+
174
+ # --- subdivision-friendly cuts -------------------------------------------------------------------------------
175
+
176
+ def inset_recess(obj: bpy.types.Object, face_indices: list, rim_width: float, depth: float) -> dict:
177
+ """
178
+ Cuts a recessed panel (hatch, access panel, vent bed) into a cage: the region is inset by `rim_width`,
179
+ which leaves a quad ring of support topology around it, then sunk straight down by `depth`, so the
180
+ walls are vertical. Give the returned rim and floor edges holding loops (subdivision_cage) or a bevel
181
+ (mid-poly): the rim is the convex edge that catches the highlight, the floor edge the concave one.
182
+
183
+ :param obj: Mesh object (a cage with grid topology, e.g. grid_plate).
184
+ :param face_indices: The region's faces (one connected patch on a flat or gently curved surface).
185
+ :param rim_width: Width of the support ring left between the region and the surrounding faces, metres.
186
+ Keep it at least twice the holding-loop width you will use (radius / 0.57), so the loops do not
187
+ collide.
188
+ :param depth: How far the panel floor sinks, metres. Deeper than the holding-loop width.
189
+ :returns: {"rim_edges", "floor_edges", "floor_faces", "wall_faces", "ring_faces"} as index lists.
190
+ :raises ValueError: when no faces are given.
191
+ """
192
+ edit_mesh, faces = _faces_of(obj, face_indices)
193
+ ring = set(bmesh.ops.inset_region(edit_mesh, faces=faces, thickness=rim_width, use_even_offset=True)["faces"])
194
+ floor, walls = _sink_region(edit_mesh, faces, depth)
195
+ return _write_back(obj, edit_mesh,
196
+ {"rim_edges": edges_between(edit_mesh, ring, walls), "floor_edges": edges_between(edit_mesh, walls, floor)},
197
+ {"floor_faces": floor, "wall_faces": walls, "ring_faces": ring})
198
+
199
+
200
+ def panel_groove(obj: bpy.types.Object, face_indices: list, width: float, depth: float) -> dict:
201
+ """
202
+ A V-shaped panel line around a region: two insets of half the width each, the first sinking the region
203
+ by `depth` and the second lifting it back, so the region ends at its old height with a groove around
204
+ it. This is the geometric panel line of a mid-poly or cage model; below about 2 screen pixels wide it
205
+ aliases, so far-seen panel lines go into the normal map or a trim instead.
206
+
207
+ :param obj: Mesh object.
208
+ :param face_indices: The panel's faces.
209
+ :param width: Groove width at the surface, metres.
210
+ :param depth: Groove depth, metres.
211
+ :returns: {"lip_edges" (both top edges of the groove), "bottom_edges", "groove_faces"}.
212
+ :raises ValueError: when no faces are given.
213
+ """
214
+ edit_mesh, faces = _faces_of(obj, face_indices)
215
+ outer_wall = set(bmesh.ops.inset_region(edit_mesh, faces=faces, thickness=width / 2.0, depth=-depth,
216
+ use_even_offset=True)["faces"])
217
+ inner_wall = set(bmesh.ops.inset_region(edit_mesh, faces=faces, thickness=width / 2.0, depth=depth,
218
+ use_even_offset=True)["faces"])
219
+ panel = set(faces)
220
+ surround = {face for edge in edges_of_faces(outer_wall) for face in edge.link_faces} - outer_wall - inner_wall - panel
221
+ lips = edges_between(edit_mesh, outer_wall, surround) + edges_between(edit_mesh, inner_wall, panel)
222
+ return _write_back(obj, edit_mesh, {"lip_edges": lips, "bottom_edges": edges_between(edit_mesh, outer_wall, inner_wall)},
223
+ {"groove_faces": outer_wall | inner_wall})
224
+
225
+
226
+ def edges_of_faces(faces: set) -> set:
227
+ """Every edge of a face set."""
228
+ return {edge for face in faces for edge in face.edges}
229
+
230
+
231
+ def _boundary_loop(faces: list) -> list:
232
+ """The ordered boundary vertices of a disc-shaped face region."""
233
+ region = set(faces)
234
+ boundary = [edge for edge in edges_of_faces(region) if sum(face in region for face in edge.link_faces) == 1]
235
+ neighbours = {}
236
+ for edge in boundary:
237
+ first, second = edge.verts
238
+ neighbours.setdefault(first, []).append(second)
239
+ neighbours.setdefault(second, []).append(first)
240
+ start = boundary[0].verts[0]
241
+ loop, previous = [start], None
242
+ while len(loop) < len(neighbours):
243
+ following = next(vertex for vertex in neighbours[loop[-1]] if vertex is not previous and vertex not in loop[-2:])
244
+ previous = loop[-1]
245
+ loop.append(following)
246
+ return loop
247
+
248
+
249
+ def round_hole(obj: bpy.types.Object, face_indices: list, radius: float, depth: float, rim_width: float) -> dict:
250
+ """
251
+ A round socket (bolt hole, lamp seat, port) cut without a boolean: the region is inset to leave a
252
+ support ring, its boundary is projected onto a circle, and the disc is sunk by `depth`. The hole has as
253
+ many sides as the region's boundary has vertices (a 2 x 2 patch gives 8, a 4 x 4 patch 16), so the
254
+ ring between the square and the circle is all quads and subdivides without pinching.
255
+
256
+ :param obj: Mesh object with grid topology.
257
+ :param face_indices: A square-ish patch of faces (2 x 2 or 4 x 4 on the grid).
258
+ :param radius: Hole radius in metres; the patch must be wider than 2 x (radius + rim_width).
259
+ :param depth: Socket depth in metres.
260
+ :param rim_width: Width of the inset ring, metres.
261
+ :returns: {"rim_edges", "floor_edges", "floor_faces", "wall_faces", "ring_faces", "sides"}.
262
+ :raises ValueError: when no faces are given.
263
+ """
264
+ edit_mesh, faces = _faces_of(obj, face_indices)
265
+ ring = set(bmesh.ops.inset_region(edit_mesh, faces=faces, thickness=rim_width, use_even_offset=True)["faces"])
266
+ normal = _region_normal(faces)
267
+ loop = _boundary_loop(faces)
268
+ centre = sum((vertex.co for vertex in loop), Vector()) / len(loop)
269
+ inner = {vertex for face in faces for vertex in face.verts} - set(loop)
270
+ reach = max((vertex.co - centre).length for vertex in loop)
271
+ for vertex in loop:
272
+ offset = vertex.co - centre
273
+ offset -= normal * offset.dot(normal)
274
+ vertex.co = centre + offset.normalized() * radius
275
+ for vertex in inner:
276
+ vertex.co = centre + (vertex.co - centre) * (radius / reach)
277
+ floor, walls = _sink_region(edit_mesh, faces, depth)
278
+ report = _write_back(obj, edit_mesh,
279
+ {"rim_edges": edges_between(edit_mesh, ring, walls), "floor_edges": edges_between(edit_mesh, walls, floor)},
280
+ {"floor_faces": floor, "wall_faces": walls, "ring_faces": ring})
281
+ report["sides"] = len(loop)
282
+ return report
283
+
284
+
285
+ # --- mid-poly route -----------------------------------------------------------------------------------------
286
+
287
+ # Volume-checked booleans live in construction_kit (one copy each); these names keep working here.
288
+ evaluated_volume = kit.evaluated_volume
289
+ boolean_cut = kit.boolean_cut
290
+
291
+
292
+ def mid_poly_finish(obj: bpy.types.Object, bevel_width: float, segments: int = 2,
293
+ angle_degrees: float = MID_POLY_ANGLE_DEGREES, weighted_normals: bool = True,
294
+ flat_vertex_group=None) -> list:
295
+ """
296
+ The mid-poly finish for FACETED parts: an angle-limited bevel with hardened normals on every edge
297
+ sharper than `angle_degrees`, then face-area weighted normals so the big flats shade flat and the
298
+ shading turns inside the bevel. Never use it on rolled or curved surfaces (every facet would read);
299
+ restrict the weighted normals to the flat panels with `flat_vertex_group` when a part has both.
300
+
301
+ :param obj: Mesh object, scale applied.
302
+ :param bevel_width: Bevel width in metres; keep one width across the asset (0.5-2 % of the part size).
303
+ :param segments: 1-2 for a machined chamfer, 3+ for a soft round.
304
+ :param angle_degrees: Edges sharper than this are bevelled.
305
+ :param weighted_normals: Add the Weighted Normal modifier.
306
+ :param flat_vertex_group: Optional vertex group limiting the weighted normals to flat panels.
307
+ :returns: The modifier names, in stack order.
308
+ """
309
+ bevel = obj.modifiers.new("Bevel", "BEVEL")
310
+ bevel.limit_method, bevel.angle_limit = "ANGLE", math.radians(angle_degrees)
311
+ bevel.width, bevel.segments, bevel.profile = bevel_width, segments, CIRCULAR_PROFILE
312
+ bevel.use_clamp_overlap, bevel.harden_normals, bevel.miter_outer = True, True, "MITER_ARC"
313
+ bevel.face_strength_mode = "FSTR_AFFECTED"
314
+ names = [bevel.name]
315
+ if weighted_normals:
316
+ weighted = obj.modifiers.new("WeightedNormal", "WEIGHTED_NORMAL")
317
+ weighted.mode, weighted.weight, weighted.keep_sharp = "FACE_AREA", WEIGHTED_NORMAL_WEIGHT, True
318
+ weighted.use_face_influence = True
319
+ if flat_vertex_group:
320
+ weighted.vertex_group = flat_vertex_group
321
+ names.append(weighted.name)
322
+ obj.data.polygons.foreach_set("use_smooth", [True] * len(obj.data.polygons))
323
+ return names
324
+
325
+
326
+ def transfer_normals(obj: bpy.types.Object, source: bpy.types.Object) -> None:
327
+ """
328
+ Copies custom normals from an uncut, smooth twin onto a part that has been cut, so the shading keeps
329
+ flowing over the surface around the cut instead of pinching toward the new edges (Data Transfer:
330
+ face-corner custom normals, nearest corner and best matching face normal). Applied in place.
331
+
332
+ :param obj: The cut part.
333
+ :param source: The uncut part, same placement (a copy made before cutting).
334
+ """
335
+ modifier = obj.modifiers.new("KeepSmoothNormals", "DATA_TRANSFER")
336
+ modifier.object = source
337
+ modifier.use_loop_data = True
338
+ modifier.data_types_loops = {"CUSTOM_NORMAL"}
339
+ modifier.loop_mapping = "NEAREST_POLYNOR"
340
+ obj.data.polygons.foreach_set("use_smooth", [True] * len(obj.data.polygons))
341
+ kit.apply_modifiers(obj)
342
+
343
+
344
+ def corner_radius_in_section(obj: bpy.types.Object, axis: str, position: float, corner: tuple,
345
+ interior_angle_degrees: float = 90.0, window=None) -> float:
346
+ """
347
+ Measures how big the roll on an edge is, on the evaluated mesh, as the radius of the circular fillet
348
+ that cuts the corner equally deep: the section through `position` is cut, the distance d from the sharp
349
+ corner to the nearest surface point is taken (it lies on the bisector), and r = d / (1 / sin(a / 2) - 1)
350
+ for an interior angle a (d = 0.414 r at 90 degrees).
351
+
352
+ A circle fit is the wrong tool on a subdivided edge: the limit curve is not a circle, so the fitted
353
+ radius depends on which points count as "off the flats" (0.038-0.086 m for one 0.05 m corner on
354
+ Blender 5.3.0). The equal-depth radius is exact for a true fillet and returned 0.00399 m at
355
+ subdivision levels 1-3 for loops sized for 0.004 m.
356
+
357
+ :param obj: Mesh object (modifiers are evaluated).
358
+ :param axis: Section plane normal, "X", "Y" or "Z".
359
+ :param position: Plane position, metres.
360
+ :param corner: (u, v) of the sharp (unrounded) corner in the section's two other coordinates, in axis
361
+ order (for "X": (y, z)).
362
+ :param interior_angle_degrees: Angle between the two flats inside the material (90 for a box edge).
363
+ :param window: Only points within this distance of the corner are considered (default: any).
364
+ :returns: The equal-depth fillet radius in metres.
365
+ :raises ValueError: when the section has no points near the corner.
366
+ """
367
+ points = kit.section_points(obj, position, axis)
368
+ distances = np.linalg.norm(points - np.array(corner, dtype=np.float64), axis=1)
369
+ if window is not None:
370
+ distances = distances[distances <= window]
371
+ if len(distances) == 0:
372
+ raise ValueError(f"the section at {axis} = {position} has no points near {corner}")
373
+ half_angle = math.radians(interior_angle_degrees) / 2.0
374
+ return float(distances.min() / (1.0 / math.sin(half_angle) - 1.0))
@@ -0,0 +1,200 @@
1
+ """
2
+ bt-blender trims and decals: map geometry onto a trim sheet and place mesh decals, headless.
3
+
4
+ import hard_surface_trims as trims
5
+
6
+ strips = trims.trim_strips([32, 64, 128, 256], texture_pixels=1024, padding_pixels=4)
7
+ trims.map_quad_strip(obj, bevel_faces, strips[0], pixels_per_metre=512, texture_pixels=1024)
8
+ decal = trims.mesh_decal("Decal_Warning", obj, face_index, 0.12, 0.06, offset=0.0015)
9
+
10
+ A trim sheet is a texture of horizontal strips, each tiling along U only (a bevelled edge, a panel seam,
11
+ a bolt row, a rubber seal). Geometry is unwrapped as quad strips whose V spans one strip and whose U runs
12
+ along the strip at the kit's texel density, so one material serves a whole kit and texel density stays
13
+ constant. A mesh decal is a separate quad floating just above a surface, carrying a cell of a decal atlas
14
+ (a label, a vent, a warning stripe), so detail does not cut topology.
15
+ """
16
+ import bmesh
17
+ import bpy
18
+
19
+ # A quad strip face has exactly four corners.
20
+ QUAD_CORNERS = 4
21
+
22
+
23
+ def trim_strips(heights_pixels: list, texture_pixels: int = 1024, padding_pixels: int = 4) -> list:
24
+ """
25
+ Lays out trim strips from the top of the texture down, with padding between them so mip levels do not
26
+ bleed one strip into the next. Heights in powers of two (16, 32, 64, 128, 256) keep strips aligned to
27
+ texel blocks at every mip level.
28
+
29
+ :param heights_pixels: Strip heights in texture pixels, top first.
30
+ :param texture_pixels: Texture height in pixels.
31
+ :param padding_pixels: Gap above and below each strip, pixels.
32
+ :returns: [{"index", "height_pixels", "v_min", "v_max"}] in UV units (V up, so the top strip is near 1).
33
+ :raises ValueError: when the strips do not fit the texture.
34
+ """
35
+ used = sum(heights_pixels) + 2 * padding_pixels * len(heights_pixels)
36
+ if used > texture_pixels:
37
+ raise ValueError(f"strips need {used} px but the texture is {texture_pixels} px")
38
+ strips, top = [], texture_pixels
39
+ for index, height in enumerate(heights_pixels):
40
+ top -= padding_pixels
41
+ strips.append({"index": index, "height_pixels": height,
42
+ "v_min": (top - height) / texture_pixels, "v_max": top / texture_pixels})
43
+ top -= height + padding_pixels
44
+ return strips
45
+
46
+
47
+ def _shared_edge(first: bmesh.types.BMFace, second: bmesh.types.BMFace):
48
+ """The edge two faces share, or None."""
49
+ return next((edge for edge in first.edges if second in edge.link_faces), None)
50
+
51
+
52
+ def _order_strip(faces: list) -> list:
53
+ """Orders the faces of an open quad strip from one end to the other."""
54
+ region = set(faces)
55
+ neighbours = {face: [other for edge in face.edges for other in edge.link_faces if other in region and other is not face]
56
+ for face in faces}
57
+ if any(len(adjacent) > 2 for adjacent in neighbours.values()) or any(_turns(face, adjacent) for face, adjacent in neighbours.items()):
58
+ raise ValueError("the faces are wider than one quad: pick a single row (one quad across)")
59
+ start = next((face for face in faces if len(neighbours[face]) == 1), faces[0])
60
+ ordered = [start]
61
+ while len(ordered) < len(faces):
62
+ following = [face for face in neighbours[ordered[-1]] if face not in ordered]
63
+ if not following:
64
+ raise ValueError("the faces are not one connected quad strip")
65
+ ordered.append(following[0])
66
+ return ordered
67
+
68
+
69
+ def _turns(face: bmesh.types.BMFace, adjacent: list) -> bool:
70
+ """True when a quad's two neighbours meet it on edges that share a corner: the row turns, as in a 2 x 2 patch."""
71
+ if len(adjacent) != 2:
72
+ return False
73
+ first, second = (_shared_edge(face, other) for other in adjacent)
74
+ return any(vertex in second.verts for vertex in first.verts)
75
+
76
+
77
+ def _cross_edges(ordered: list) -> list:
78
+ """The edges across the strip, in order: the first face's free end, each shared edge, the last free end."""
79
+ shared = [_shared_edge(first, second) for first, second in zip(ordered, ordered[1:])]
80
+ first_end = next(edge for edge in ordered[0].edges if edge not in shared and not _touches(edge, shared[:1]))
81
+ last_end = next(edge for edge in ordered[-1].edges if edge not in shared and not _touches(edge, shared[-1:]))
82
+ return [first_end] + shared + [last_end]
83
+
84
+
85
+ def _touches(edge, edges: list) -> bool:
86
+ """True when the edge shares a vertex with any edge in the list."""
87
+ return any(vertex in other.verts for other in edges for vertex in edge.verts)
88
+
89
+
90
+ def _side_a_vertices(cross_edges: list) -> list:
91
+ """For each cross edge, the vertex on the strip's first rail (walking rail edges keeps the side)."""
92
+ side = [cross_edges[0].verts[0]]
93
+ for edge in cross_edges[1:]:
94
+ previous = side[-1]
95
+ side.append(next(vertex for vertex in edge.verts
96
+ if any(other is previous for rail in vertex.link_edges for other in rail.verts)))
97
+ return side
98
+
99
+
100
+ def map_quad_strip(obj: bpy.types.Object, face_indices: list, strip: dict, pixels_per_metre: float,
101
+ texture_pixels: int = 1024, uv_name=None) -> dict:
102
+ """
103
+ Unwraps an open strip of quads (a bevel row, a panel seam, a rim) onto one trim strip: V spans the
104
+ strip exactly from one rail of the quads to the other, U runs along the strip at the kit's texel
105
+ density (it may pass 1: trims tile along U). This is what Follow Active Quads plus "fit to strip" does
106
+ by hand.
107
+
108
+ :param obj: Mesh object.
109
+ :param face_indices: The strip's quads (connected end to end, one quad wide; a single quad is allowed).
110
+ :param strip: One entry of trim_strips.
111
+ :param pixels_per_metre: Texel density along the strip.
112
+ :param texture_pixels: Trim texture width in pixels.
113
+ :param uv_name: UV map to write (created if missing; default the active map or "UVMap").
114
+ :returns: {"faces", "length_m", "u_span"}.
115
+ :raises ValueError: for non-quads or faces that are not one strip.
116
+ """
117
+ mesh = obj.data
118
+ name = uv_name or (mesh.uv_layers.active.name if mesh.uv_layers.active else "UVMap")
119
+ if name not in mesh.uv_layers:
120
+ mesh.uv_layers.new(name=name)
121
+ edit_mesh = bmesh.new()
122
+ edit_mesh.from_mesh(mesh)
123
+ edit_mesh.faces.ensure_lookup_table()
124
+ faces = [edit_mesh.faces[index] for index in face_indices]
125
+ if any(len(face.verts) != QUAD_CORNERS for face in faces):
126
+ raise ValueError("map_quad_strip needs quads")
127
+ ordered = _order_strip(faces) if len(faces) > 1 else faces
128
+ cross = _cross_edges(ordered) if len(faces) > 1 else _single_quad_ends(faces[0])
129
+ side_a = _side_a_vertices(cross)
130
+ positions, length = [0.0], 0.0
131
+ for first, second in zip(cross, cross[1:]):
132
+ length += ((first.verts[0].co + first.verts[1].co) / 2 - (second.verts[0].co + second.verts[1].co) / 2).length
133
+ positions.append(length)
134
+ layer = edit_mesh.loops.layers.uv[name]
135
+ u_scale = pixels_per_metre / texture_pixels
136
+ for face_number, face in enumerate(ordered):
137
+ for slot in (face_number, face_number + 1):
138
+ for vertex in cross[slot].verts:
139
+ v = strip["v_max"] if vertex is side_a[slot] else strip["v_min"]
140
+ for loop in face.loops:
141
+ if loop.vert is vertex:
142
+ loop[layer].uv = (positions[slot] * u_scale, v)
143
+ edit_mesh.to_mesh(mesh)
144
+ edit_mesh.free()
145
+ return {"faces": len(faces), "length_m": round(length, 6), "u_span": round(length * u_scale, 6)}
146
+
147
+
148
+ def _single_quad_ends(face: bmesh.types.BMFace) -> list:
149
+ """For a lone quad, its two shorter opposite edges (the strip runs along the longer ones)."""
150
+ edges = list(face.edges)
151
+ first_pair, second_pair = (edges[0], edges[2]), (edges[1], edges[3])
152
+ if sum(edge.calc_length() for edge in first_pair) <= sum(edge.calc_length() for edge in second_pair):
153
+ return list(first_pair)
154
+ return list(second_pair)
155
+
156
+
157
+ def mesh_decal(name: str, target: bpy.types.Object, face_index: int, width: float, height: float,
158
+ offset: float = 0.0015, uv_rect: tuple = (0.0, 0.0, 1.0, 1.0), material=None) -> bpy.types.Object:
159
+ """
160
+ A mesh decal: a quad centred on a flat face of the target, lying in its plane and lifted `offset` along
161
+ its normal, with UVs on one cell of a decal atlas. Long side along the face's longest edge. The decal is
162
+ a separate object named so QA can allow it to float (qa-check --allow-floating <name>).
163
+
164
+ Lift it just enough that it never z-fights at the far end of the camera range: depth precision falls
165
+ with distance, so a decal seen from 50 m needs more lift than one seen from 2 m. 1-2 mm holds for
166
+ props seen within about 20 m with a 0.1 m near plane; check it in the game camera.
167
+
168
+ :param name: Object name.
169
+ :param target: The surface object (world transform applied to the decal).
170
+ :param face_index: A flat face of the target.
171
+ :param width: Decal size along the face's longest edge, metres.
172
+ :param height: Decal size across it, metres.
173
+ :param offset: Lift above the surface, metres.
174
+ :param uv_rect: (u_min, v_min, u_max, v_max) of the atlas cell.
175
+ :param material: Optional decal material (alpha-blended or alpha-tested, no shadow casting).
176
+ :returns: The decal object.
177
+ """
178
+ polygon = target.data.polygons[face_index]
179
+ world = target.matrix_world
180
+ normal = (world.to_3x3() @ polygon.normal).normalized()
181
+ centre = world @ polygon.center + normal * offset
182
+ corners = [world @ target.data.vertices[index].co for index in polygon.vertices]
183
+ longest = max(((corners[i], corners[(i + 1) % len(corners)]) for i in range(len(corners))),
184
+ key=lambda pair: (pair[1] - pair[0]).length)
185
+ along = (longest[1] - longest[0]).normalized()
186
+ across = normal.cross(along).normalized()
187
+ half_u, half_v = along * (width / 2), across * (height / 2)
188
+ # Counter-clockwise in (along, across), so the face normal is along x across = the surface normal.
189
+ points = [centre - half_u - half_v, centre + half_u - half_v, centre + half_u + half_v, centre - half_u + half_v]
190
+ mesh = bpy.data.meshes.new(name)
191
+ mesh.from_pydata([tuple(point) for point in points], [], [(0, 1, 2, 3)])
192
+ u_min, v_min, u_max, v_max = uv_rect
193
+ layer = mesh.uv_layers.new(name="UVMap")
194
+ for loop, uv in zip(mesh.loops, ((u_min, v_min), (u_max, v_min), (u_max, v_max), (u_min, v_max))):
195
+ layer.data[loop.index].uv = uv
196
+ if material is not None:
197
+ mesh.materials.append(material)
198
+ decal = bpy.data.objects.new(name, mesh)
199
+ bpy.context.scene.collection.objects.link(decal)
200
+ return decal