@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,1170 @@
1
+ """
2
+ bt-blender rigging tools: deform skeletons, engine-legal skin weights, keyframed clips, retargeting,
3
+ shape keys, mechanical (object-hierarchy) rigs, and the export settings and round-trip measurements for
4
+ Unity (FBX, Humanoid) and BabylonJS (glTF). Import from a build script run with `bt-blender.mjs run`:
5
+
6
+ import character_blockout as blockout, rigging_tools as rig
7
+ chart = blockout.humanoid_chart(1.75)
8
+ armature = rig.build_armature("Rig", chart) # Mixamo / Unity-Humanoid names, rolls set
9
+ report = rig.bind_auto(body, armature) # heat weights, proxy fallback, 4 influences
10
+ walk = rig.new_action(armature, "Walk")
11
+ rig.key_pose(armature, walk, 1, {"LeftUpLeg": (-25, 0, 0)})
12
+ rig.make_cyclic(walk)
13
+ rig.stash_action(armature, walk) # one glTF animation / FBX take per action
14
+
15
+ Blender 5.x actions are layered and slotted: an action's F-curves live in a channelbag per slot, reached
16
+ with bpy_extras.anim_utils (Action.fcurves no longer exists). Everything here is data-level where Blender
17
+ allows it; every operator's return value is checked. Lengths are metres, angles degrees unless named
18
+ otherwise. Z up, the character faces -Y.
19
+
20
+ Technique credits (ideas, no code copied): the heat-weights-then-voxel-proxy fallback and the deform-only
21
+ game skeleton follow EL4CTEO/blender-skills (bind_mesh.py, rigify_build.py, MIT).
22
+ """
23
+ import json
24
+ import math
25
+ import os
26
+ import struct
27
+
28
+ import bpy
29
+ import numpy as np
30
+ from bpy_extras import anim_utils
31
+ from mathutils import Matrix, Quaternion, Vector
32
+
33
+ # Unity HumanBodyBones names for the Mixamo-style bone names character_blockout writes. Unity's Humanoid
34
+ # auto-mapping recognises these names (with or without the `mixamorig:` prefix Mixamo adds).
35
+ UNITY_HUMANOID_MAP = {
36
+ "Hips": "Hips", "Spine": "Spine", "Spine1": "Chest", "Spine2": "UpperChest", "Neck": "Neck", "Head": "Head",
37
+ "LeftShoulder": "LeftShoulder", "LeftArm": "LeftUpperArm", "LeftForeArm": "LeftLowerArm", "LeftHand": "LeftHand",
38
+ "RightShoulder": "RightShoulder", "RightArm": "RightUpperArm", "RightForeArm": "RightLowerArm",
39
+ "RightHand": "RightHand",
40
+ "LeftUpLeg": "LeftUpperLeg", "LeftLeg": "LeftLowerLeg", "LeftFoot": "LeftFoot", "LeftToeBase": "LeftToes",
41
+ "RightUpLeg": "RightUpperLeg", "RightLeg": "RightLowerLeg", "RightFoot": "RightFoot", "RightToeBase": "RightToes",
42
+ }
43
+
44
+ # The 15 bones a Unity Humanoid Avatar cannot be created without.
45
+ UNITY_REQUIRED_BONES = {"Hips", "Spine", "Head", "LeftUpperArm", "LeftLowerArm", "LeftHand", "RightUpperArm",
46
+ "RightLowerArm", "RightHand", "LeftUpperLeg", "LeftLowerLeg", "LeftFoot", "RightUpperLeg",
47
+ "RightLowerLeg", "RightFoot"}
48
+
49
+ # Each Humanoid bone's parent in Unity's model, nearest first: the closest mapped ancestor must be one of these.
50
+ UNITY_HUMANOID_PARENTS = {
51
+ "Spine": ("Hips",), "Chest": ("Spine",), "UpperChest": ("Chest",), "Neck": ("UpperChest", "Chest", "Spine"),
52
+ "Head": ("Neck", "UpperChest", "Chest"), "LeftShoulder": ("UpperChest", "Chest", "Spine"),
53
+ "RightShoulder": ("UpperChest", "Chest", "Spine"), "LeftUpperArm": ("LeftShoulder", "UpperChest", "Chest"),
54
+ "RightUpperArm": ("RightShoulder", "UpperChest", "Chest"), "LeftLowerArm": ("LeftUpperArm",),
55
+ "RightLowerArm": ("RightUpperArm",), "LeftHand": ("LeftLowerArm",), "RightHand": ("RightLowerArm",),
56
+ "LeftUpperLeg": ("Hips",), "RightUpperLeg": ("Hips",), "LeftLowerLeg": ("LeftUpperLeg",),
57
+ "RightLowerLeg": ("RightUpperLeg",), "LeftFoot": ("LeftLowerLeg",), "RightFoot": ("RightLowerLeg",),
58
+ "LeftToes": ("LeftFoot",), "RightToes": ("RightFoot",),
59
+ }
60
+
61
+ # Prefix Mixamo puts on every bone; add it only when an animation library expects it.
62
+ MIXAMO_PREFIX = "mixamorig:"
63
+
64
+ # Roll convention: every bone's local Z points to the character's front (-Y), so every hinge (elbow, knee)
65
+ # folds about its local X axis on both sides, and right-side rolls mirror left-side rolls.
66
+ DEFAULT_ROLL_TYPE = "GLOBAL_NEG_Y"
67
+
68
+ # Skin weights legal for glTF / BabylonJS / Unity's default quality: 4 influences, normalised, none tiny.
69
+ MAX_INFLUENCES = 4
70
+ MINIMUM_WEIGHT = 0.01
71
+
72
+ # Heat weighting leaves vertices unweighted on a bad mesh; above this share of the vertices, use the proxy.
73
+ PROXY_FALLBACK_SHARE = 0.0
74
+
75
+ # Voxel size of the weighting proxy, as a share of the mesh height.
76
+ PROXY_VOXEL_SHARE = 1.0 / 160.0
77
+
78
+ # Bone heat solves well at human size; meshes outside this height range are bound at 1.8 m and scaled back.
79
+ HEAT_MIN_HEIGHT = 0.5
80
+ HEAT_MAX_HEIGHT = 20.0
81
+ HEAT_BIND_HEIGHT = 1.8
82
+
83
+ # Tolerances.
84
+ NORMALISED_TOLERANCE = 1e-4
85
+ MIRROR_TOLERANCE = 1e-4
86
+ INFLUENCE_EPSILON = 1e-4
87
+
88
+
89
+ # --- context helpers ------------------------------------------------------------------------------------------
90
+
91
+ def _override(obj: bpy.types.Object, extra=()) -> dict:
92
+ """A full context override with `obj` active and selected (plus any extra selected objects)."""
93
+ selected = [obj] + list(extra)
94
+ return {"object": obj, "active_object": obj, "selected_objects": selected, "selected_editable_objects": selected}
95
+
96
+
97
+ def _select(objects: list, active: bpy.types.Object) -> None:
98
+ """
99
+ Selects exactly `objects` and makes `active` the view layer's active object. The view layer is updated
100
+ first: objects linked by a script are missing from view_layer.objects until then (Blender 5.3.0), and a
101
+ selection-only export of them silently writes an empty file.
102
+ """
103
+ bpy.context.view_layer.update()
104
+ for other in bpy.context.view_layer.objects:
105
+ other.select_set(other in objects)
106
+ bpy.context.view_layer.objects.active = active
107
+
108
+
109
+ def _check(outcome: set, what: str) -> None:
110
+ """Raises when an operator did not finish (operators never raise on their own)."""
111
+ if "FINISHED" not in outcome:
112
+ raise RuntimeError(f"{what} returned {outcome}")
113
+
114
+
115
+ # --- armature -------------------------------------------------------------------------------------------------
116
+
117
+ def build_armature(name: str, chart: list, roll_type: str = DEFAULT_ROLL_TYPE, prefix: str = "") -> bpy.types.Object:
118
+ """
119
+ Builds a deform armature from a joint chart (character_blockout.humanoid_chart or your own list of
120
+ ChartBone): one bone per chart entry, parents and connections as charted, rolls recalculated so all
121
+ hinges fold about local X and the two sides mirror.
122
+
123
+ :param name: Armature object and data name.
124
+ :param chart: List of ChartBone, parents before children.
125
+ :param roll_type: armature.calculate_roll type for every bone.
126
+ :param prefix: Added to every bone name (e.g. MIXAMO_PREFIX for a Mixamo-compatible file).
127
+ :returns: The armature object, in Object Mode, at the world origin with identity transform.
128
+ """
129
+ data = bpy.data.armatures.new(name)
130
+ armature = bpy.data.objects.new(name, data)
131
+ bpy.context.scene.collection.objects.link(armature)
132
+ _select([armature], armature)
133
+ with bpy.context.temp_override(**_override(armature)):
134
+ _check(bpy.ops.object.mode_set(mode="EDIT"), "mode_set EDIT")
135
+ for bone in chart:
136
+ edit_bone = data.edit_bones.new(prefix + bone.name)
137
+ edit_bone.head, edit_bone.tail = bone.head, bone.tail
138
+ edit_bone.use_deform = bone.deform
139
+ for bone in chart:
140
+ if bone.parent:
141
+ edit_bone = data.edit_bones[prefix + bone.name]
142
+ edit_bone.parent = data.edit_bones[prefix + bone.parent]
143
+ edit_bone.use_connect = bone.connected
144
+ for edit_bone in data.edit_bones:
145
+ edit_bone.select = edit_bone.select_head = edit_bone.select_tail = True
146
+ _check(bpy.ops.armature.calculate_roll(type=roll_type), "calculate_roll")
147
+ _check(bpy.ops.object.mode_set(mode="OBJECT"), "mode_set OBJECT")
148
+ return armature
149
+
150
+
151
+ def mirror_report(armature: bpy.types.Object) -> dict:
152
+ """
153
+ Checks the Left / Right bone pairs mirror across X: heads, tails and rolls. Mirrored rolls make a
154
+ pose copied to the other side (and Unity's Humanoid mirror) behave.
155
+
156
+ :returns: {"pairs", "position_errors", "roll_errors"} (error lists hold bone names).
157
+ """
158
+ bones = armature.data.bones
159
+ position_errors, roll_errors, pairs = [], [], 0
160
+ for bone in bones:
161
+ if "Left" not in bone.name:
162
+ continue
163
+ other = bones.get(bone.name.replace("Left", "Right"))
164
+ if other is None:
165
+ position_errors.append(bone.name)
166
+ continue
167
+ pairs += 1
168
+ flip = Vector((-1.0, 1.0, 1.0))
169
+ if ((bone.head_local * flip) - other.head_local).length > MIRROR_TOLERANCE or \
170
+ ((bone.tail_local * flip) - other.tail_local).length > MIRROR_TOLERANCE:
171
+ position_errors.append(bone.name)
172
+ # A mirrored bone's X axis flips sign and its Z axis keeps it.
173
+ left_z, right_z = bone.matrix_local.col[2].xyz, other.matrix_local.col[2].xyz
174
+ if ((left_z * flip) - right_z).length > 1e-3:
175
+ roll_errors.append(bone.name)
176
+ return {"pairs": pairs, "position_errors": position_errors, "roll_errors": roll_errors}
177
+
178
+
179
+ def humanoid_report(armature: bpy.types.Object, name_map: dict = None, prefix: str = "") -> dict:
180
+ """
181
+ What Unity needs to build a Humanoid Avatar from this rig: the 15 required bones present, each mapped
182
+ bone's nearest mapped ancestor where Unity expects it, uniform unit object scale, and how far the arms
183
+ are from a T-pose (Unity asks for a T-pose; an A-pose works with Configure > Pose > Enforce T-Pose).
184
+
185
+ :param armature: Armature object.
186
+ :param name_map: {bone name: Unity HumanBodyBones name}; default UNITY_HUMANOID_MAP.
187
+ :param prefix: Bone-name prefix to strip before mapping (e.g. "mixamorig:").
188
+ :returns: {"mapped", "missing_required", "hierarchy_errors", "arm_angle_degrees", "scale_ok", "pass"}.
189
+ """
190
+ name_map = name_map or UNITY_HUMANOID_MAP
191
+ bones = armature.data.bones
192
+ mapped = {}
193
+ for bone in bones:
194
+ plain = bone.name[len(prefix):] if prefix and bone.name.startswith(prefix) else bone.name
195
+ if plain in name_map:
196
+ mapped[name_map[plain]] = bone
197
+ missing = sorted(UNITY_REQUIRED_BONES - set(mapped))
198
+ by_bone = {bone.name: unity for unity, bone in mapped.items()}
199
+ hierarchy_errors = []
200
+ for unity, bone in mapped.items():
201
+ expected = UNITY_HUMANOID_PARENTS.get(unity)
202
+ if not expected:
203
+ continue
204
+ ancestor = bone.parent
205
+ while ancestor is not None and ancestor.name not in by_bone:
206
+ ancestor = ancestor.parent
207
+ found = by_bone.get(ancestor.name) if ancestor else None
208
+ if found not in expected:
209
+ hierarchy_errors.append(f"{bone.name} ({unity}) under {found}, expected one of {list(expected)}")
210
+ arm_angle = None
211
+ if "LeftUpperArm" in mapped:
212
+ direction = mapped["LeftUpperArm"].tail_local - mapped["LeftUpperArm"].head_local
213
+ arm_angle = round(math.degrees(math.atan2(-direction.z, math.hypot(direction.x, direction.y))), 2)
214
+ scale_ok = all(abs(value - 1.0) < 1e-6 for value in armature.scale)
215
+ return {"mapped": len(mapped), "missing_required": missing, "hierarchy_errors": hierarchy_errors,
216
+ "arm_angle_degrees": arm_angle, "scale_ok": scale_ok,
217
+ "pass": not missing and not hierarchy_errors and scale_ok}
218
+
219
+
220
+ # --- skin weights ---------------------------------------------------------------------------------------------
221
+
222
+ def weight_report(mesh: bpy.types.Object, armature: bpy.types.Object) -> dict:
223
+ """
224
+ The skin-weight numbers that decide whether a mesh ships: unweighted vertices, the most influences on
225
+ any vertex, vertices over the 4-influence limit, and vertices whose deform weights do not sum to 1.
226
+
227
+ :returns: {"vertices", "unweighted", "max_influences", "over_limit", "not_normalised", "groups"}.
228
+ """
229
+ deform = {bone.name for bone in armature.data.bones if bone.use_deform}
230
+ deform_groups = {group.index for group in mesh.vertex_groups if group.name in deform}
231
+ unweighted = over = not_normalised = most = 0
232
+ for vertex in mesh.data.vertices:
233
+ weights = [entry.weight for entry in vertex.groups if entry.group in deform_groups
234
+ and entry.weight > INFLUENCE_EPSILON]
235
+ most = max(most, len(weights))
236
+ unweighted += not weights
237
+ over += len(weights) > MAX_INFLUENCES
238
+ not_normalised += bool(weights) and abs(sum(weights) - 1.0) > NORMALISED_TOLERANCE
239
+ return {"vertices": len(mesh.data.vertices), "unweighted": unweighted, "max_influences": most,
240
+ "over_limit": over, "not_normalised": not_normalised, "groups": len(deform_groups)}
241
+
242
+
243
+ def make_engine_legal(mesh: bpy.types.Object, limit: int = MAX_INFLUENCES, minimum: float = MINIMUM_WEIGHT) -> None:
244
+ """
245
+ Cleans, limits and normalises the weights, in that order (normalising first and then limiting leaves
246
+ the sums wrong again). keep_single stops cleaning from leaving a vertex with no weight at all.
247
+
248
+ :param mesh: Skinned mesh object.
249
+ :param limit: Influences per vertex (4 for glTF JOINTS_0 / Unity's default quality).
250
+ :param minimum: Weights at or below this are removed.
251
+ """
252
+ with bpy.context.temp_override(**_override(mesh)):
253
+ _check(bpy.ops.object.vertex_group_clean(group_select_mode="ALL", limit=minimum, keep_single=True),
254
+ "vertex_group_clean")
255
+ _check(bpy.ops.object.vertex_group_limit_total(group_select_mode="ALL", limit=limit),
256
+ "vertex_group_limit_total")
257
+ _check(bpy.ops.object.vertex_group_normalize_all(group_select_mode="ALL", lock_active=False),
258
+ "vertex_group_normalize_all")
259
+
260
+
261
+ def _detach(mesh: bpy.types.Object) -> None:
262
+ """Removes old weights, Armature modifiers and the parent, keeping the world transform."""
263
+ world = mesh.matrix_world.copy()
264
+ mesh.vertex_groups.clear()
265
+ for modifier in [modifier for modifier in mesh.modifiers if modifier.type == "ARMATURE"]:
266
+ mesh.modifiers.remove(modifier)
267
+ mesh.parent = None
268
+ mesh.matrix_world = world
269
+
270
+
271
+ def attach(mesh: bpy.types.Object, armature: bpy.types.Object) -> bpy.types.ArmatureModifier:
272
+ """
273
+ Parents a mesh to an armature and adds the Armature modifier, without operators (the result of
274
+ parent_set ARMATURE_NAME, but keeping the existing vertex groups). The mesh keeps its world transform.
275
+
276
+ :returns: The Armature modifier.
277
+ """
278
+ world = mesh.matrix_world.copy()
279
+ mesh.parent = armature
280
+ mesh.matrix_parent_inverse = armature.matrix_world.inverted()
281
+ mesh.matrix_world = world
282
+ modifier = next((existing for existing in mesh.modifiers if existing.type == "ARMATURE"), None)
283
+ modifier = modifier or mesh.modifiers.new("Armature", "ARMATURE")
284
+ modifier.object = armature
285
+ modifier.use_vertex_groups = True
286
+ modifier.use_bone_envelopes = False
287
+ return modifier
288
+
289
+
290
+ def _height(objects: list) -> float:
291
+ """World-space height of the objects' mesh vertices."""
292
+ heights = []
293
+ for obj in objects:
294
+ matrix = obj.matrix_world
295
+ heights.extend((matrix @ vertex.co).z for vertex in obj.data.vertices)
296
+ return max(heights) - min(heights) if heights else 0.0
297
+
298
+
299
+ def heat_weights(mesh: bpy.types.Object, armature: bpy.types.Object) -> None:
300
+ """
301
+ Plain bone heat: parent_set ARMATURE_AUTO with no scale fix, no fallback and no cleanup - what a
302
+ one-line script gets. Use bind_auto for real work; this exists to show and test the failure modes.
303
+ The armature must be active and both selected (done here).
304
+ """
305
+ _select([mesh, armature], armature)
306
+ with bpy.context.temp_override(**_override(armature, [mesh])):
307
+ _check(bpy.ops.object.parent_set(type="ARMATURE_AUTO", keep_transform=True), "parent_set ARMATURE_AUTO")
308
+
309
+
310
+ def _proxy_weights(mesh: bpy.types.Object, armature: bpy.types.Object, voxel_size: float) -> None:
311
+ """
312
+ Heat-weights a voxel-remeshed (closed, manifold, single-shell) copy of the mesh, then transfers its
313
+ weights back by nearest interpolated face. Bone heat needs a watertight mesh; the proxy is one even
314
+ when the real mesh is a kitbash of open, intersecting or floating parts.
315
+ """
316
+ proxy = mesh.copy()
317
+ proxy.data = mesh.data.copy()
318
+ proxy.name = mesh.name + "_WeightProxy"
319
+ proxy.modifiers.clear()
320
+ proxy.vertex_groups.clear()
321
+ if proxy.data.shape_keys:
322
+ proxy.shape_key_clear()
323
+ proxy.parent = None
324
+ proxy.matrix_world = mesh.matrix_world
325
+ bpy.context.scene.collection.objects.link(proxy)
326
+ proxy.data.remesh_voxel_size = voxel_size
327
+ proxy.data.use_remesh_fix_poles = True
328
+ _select([proxy], proxy)
329
+ with bpy.context.temp_override(**_override(proxy)):
330
+ _check(bpy.ops.object.voxel_remesh(), "voxel_remesh (weight proxy)")
331
+ heat_weights(proxy, armature)
332
+ _select([proxy, mesh], proxy)
333
+ with bpy.context.temp_override(**_override(proxy, [mesh])):
334
+ _check(bpy.ops.object.data_transfer(data_type="VGROUP_WEIGHTS", vert_mapping="POLYINTERP_NEAREST",
335
+ layers_select_src="ALL", layers_select_dst="NAME"),
336
+ "data_transfer VGROUP_WEIGHTS")
337
+ proxy_mesh = proxy.data
338
+ bpy.data.objects.remove(proxy)
339
+ bpy.data.meshes.remove(proxy_mesh)
340
+
341
+
342
+ def bind_auto(mesh: bpy.types.Object, armature: bpy.types.Object, limit: int = MAX_INFLUENCES,
343
+ minimum: float = MINIMUM_WEIGHT, method: str = "auto", proxy_voxel_size: float = None) -> dict:
344
+ """
345
+ Skins a mesh to an armature with automatic (bone heat) weights and makes them engine-legal. Bone heat
346
+ fails quietly on non-manifold, intersecting or floating geometry (vertices are left with no weight);
347
+ method "auto" then re-binds through a voxel proxy, and any vertex still unweighted (a part far from
348
+ every bone) takes the weights of its nearest weighted neighbour. Meshes far from human size are bound
349
+ at 1.8 m and scaled back, because heat weighting depends on scale.
350
+
351
+ :param mesh: Mesh object, transforms applied, in the rest pose.
352
+ :param armature: Deform armature in its rest pose.
353
+ :param limit: Influences per vertex after cleanup.
354
+ :param minimum: Smallest weight kept.
355
+ :param method: "auto" (heat, proxy when it leaves vertices unweighted), "heat" or "proxy".
356
+ :param proxy_voxel_size: Proxy voxel size in metres (default height / 160).
357
+ :returns: {"method", "heat_unweighted", "filled_from_nearest", "scaled_for_heat", plus weight_report()}.
358
+ :raises ValueError: for an unknown method.
359
+ """
360
+ if method not in ("auto", "heat", "proxy"):
361
+ raise ValueError("method must be 'auto', 'heat' or 'proxy'")
362
+ _detach(mesh)
363
+ height = _height([mesh])
364
+ factor = HEAT_BIND_HEIGHT / height if height and not HEAT_MIN_HEIGHT <= height <= HEAT_MAX_HEIGHT else 1.0
365
+ saved = (armature.matrix_world.copy(), mesh.matrix_world.copy())
366
+ if factor != 1.0:
367
+ scale = Matrix.Scale(factor, 4)
368
+ armature.matrix_world = scale @ saved[0]
369
+ mesh.matrix_world = scale @ saved[1]
370
+ bpy.context.view_layer.update()
371
+ heat_unweighted = None
372
+ used = method
373
+ if method in ("auto", "heat"):
374
+ heat_weights(mesh, armature)
375
+ heat_unweighted = weight_report(mesh, armature)["unweighted"]
376
+ if method == "auto" and heat_unweighted > PROXY_FALLBACK_SHARE * len(mesh.data.vertices):
377
+ used = "proxy"
378
+ if used == "proxy":
379
+ _detach(mesh)
380
+ _proxy_weights(mesh, armature, proxy_voxel_size or _height([mesh]) * PROXY_VOXEL_SHARE)
381
+ attach(mesh, armature)
382
+ if factor != 1.0:
383
+ armature.matrix_world = saved[0]
384
+ mesh.matrix_world = saved[1]
385
+ bpy.context.view_layer.update()
386
+ filled = fill_unweighted(mesh, armature) if method == "auto" else 0
387
+ make_engine_legal(mesh, limit, minimum)
388
+ return {"method": used, "heat_unweighted": heat_unweighted, "filled_from_nearest": filled,
389
+ "scaled_for_heat": round(factor, 4), **weight_report(mesh, armature)}
390
+
391
+
392
+ def fill_unweighted(mesh: bpy.types.Object, armature: bpy.types.Object) -> int:
393
+ """
394
+ Gives every vertex with no deform weight the weights of the nearest weighted vertex. The last resort
395
+ for parts bone heat cannot reach (a detached accessory, a floating card); prefer rigid_bind for parts
396
+ that should follow exactly one bone.
397
+
398
+ :returns: How many vertices were filled.
399
+ """
400
+ from mathutils.kdtree import KDTree
401
+
402
+ deform = {bone.name for bone in armature.data.bones if bone.use_deform}
403
+ deform_groups = {group.index for group in mesh.vertex_groups if group.name in deform}
404
+ weighted, empty = [], []
405
+ for vertex in mesh.data.vertices:
406
+ entries = [(entry.group, entry.weight) for entry in vertex.groups
407
+ if entry.group in deform_groups and entry.weight > INFLUENCE_EPSILON]
408
+ (weighted if entries else empty).append((vertex.index, entries))
409
+ if not empty or not weighted:
410
+ return 0
411
+ tree = KDTree(len(weighted))
412
+ for slot, (index, _) in enumerate(weighted):
413
+ tree.insert(mesh.data.vertices[index].co, slot)
414
+ tree.balance()
415
+ for index, _ in empty:
416
+ _, slot, _ = tree.find(mesh.data.vertices[index].co)
417
+ for group_index, weight in weighted[slot][1]:
418
+ mesh.vertex_groups[group_index].add([index], weight, "REPLACE")
419
+ return len(empty)
420
+
421
+
422
+ def rigid_bind(mesh: bpy.types.Object, armature: bpy.types.Object, bone: str) -> None:
423
+ """
424
+ Weights every vertex of a rigid part (helmet, armour plate, prop in hand) 1.0 to one bone: rigid parts
425
+ must not stretch between bones.
426
+ """
427
+ _detach(mesh)
428
+ group = mesh.vertex_groups.new(name=bone)
429
+ group.add([vertex.index for vertex in mesh.data.vertices], 1.0, "REPLACE")
430
+ attach(mesh, armature)
431
+
432
+
433
+ # --- actions and keys -----------------------------------------------------------------------------------------
434
+
435
+ def new_action(owner, name: str) -> bpy.types.Action:
436
+ """
437
+ Creates an action and makes it the owner's active action (its slot is created by the first key).
438
+ The action gets a fake user, so it survives being unassigned when the next clip is authored.
439
+
440
+ :param owner: An object (armature, mesh, empty) or a shape-key block (mesh.data.shape_keys).
441
+ :param name: Clip name; it becomes the glTF animation / BabylonJS AnimationGroup / FBX take name.
442
+ :returns: The action.
443
+ """
444
+ existing = bpy.data.actions.get(name)
445
+ if existing is not None:
446
+ bpy.data.actions.remove(existing)
447
+ action = bpy.data.actions.new(name)
448
+ action.use_fake_user = True
449
+ owner.animation_data_create()
450
+ owner.animation_data.action = action
451
+ return action
452
+
453
+
454
+ def _slot_for(owner, action: bpy.types.Action):
455
+ """
456
+ The slot of `action` that belongs to `owner`: the one named after it, else the one it used last
457
+ (importers name FBX slots "Slot" and assign them). Every object slot "suits" every object, so with
458
+ several objects sharing one action (a mechanical rig's Drive clip) taking the first suitable or the
459
+ only existing slot would key every object into the first object's curves - one channel exported
460
+ instead of six. Returns None when the action has no slot for the owner yet.
461
+ """
462
+ slots = [slot for slot in action.slots if slot.target_id_type == owner.id_type]
463
+ by_name = next((slot for slot in slots if slot.name_display == owner.name), None)
464
+ if by_name is not None:
465
+ return by_name
466
+ last = owner.animation_data.last_slot_identifier if owner.animation_data else ""
467
+ by_last = next((slot for slot in slots if slot.identifier == last), None)
468
+ return by_last
469
+
470
+
471
+ def use_action(owner, action: bpy.types.Action) -> None:
472
+ """Makes `action` the owner's active action with the owner's own slot (created when there is none)."""
473
+ owner.animation_data_create()
474
+ owner.animation_data.action = action
475
+ slot = _slot_for(owner, action) or action.slots.new(id_type=owner.id_type, name=owner.name)
476
+ owner.animation_data.action_slot = slot
477
+
478
+
479
+ def fcurves(action: bpy.types.Action, owner=None) -> list:
480
+ """
481
+ The F-curves of an action (Blender 5.x: per slot, through the channelbag). With `owner`, only the
482
+ slot assigned to that owner; without, every slot's curves.
483
+ """
484
+ if owner is not None:
485
+ bag = anim_utils.action_get_channelbag_for_slot(action, owner.animation_data.action_slot)
486
+ return list(bag.fcurves) if bag else []
487
+ curves = []
488
+ for slot in action.slots:
489
+ bag = anim_utils.action_get_channelbag_for_slot(action, slot)
490
+ curves.extend(bag.fcurves if bag else [])
491
+ return curves
492
+
493
+
494
+ def key_pose(armature: bpy.types.Object, action: bpy.types.Action, frame: float, rotations: dict = None,
495
+ locations: dict = None, rotation_mode: str = "XYZ") -> None:
496
+ """
497
+ Keys a pose: bone rotations (Euler degrees in the bone's local space, from the rest pose) and
498
+ locations (metres, local). Every bone listed is keyed on every channel of that property, so poses stay
499
+ exact at the keys. Bones not listed keep whatever they had.
500
+
501
+ :param armature: Armature object.
502
+ :param action: The clip; it is made active on the armature.
503
+ :param frame: Frame number.
504
+ :param rotations: {bone: (x, y, z) degrees}.
505
+ :param locations: {bone: (x, y, z) metres}.
506
+ :param rotation_mode: Euler order used for authoring; exporters sample it into quaternions.
507
+ """
508
+ use_action(armature, action)
509
+ for bone_name, degrees in (rotations or {}).items():
510
+ pose_bone = armature.pose.bones[bone_name]
511
+ pose_bone.rotation_mode = rotation_mode
512
+ pose_bone.rotation_euler = [math.radians(value) for value in degrees]
513
+ pose_bone.keyframe_insert("rotation_euler", frame=frame, group=bone_name)
514
+ for bone_name, offset in (locations or {}).items():
515
+ pose_bone = armature.pose.bones[bone_name]
516
+ pose_bone.location = offset
517
+ pose_bone.keyframe_insert("location", frame=frame, group=bone_name)
518
+
519
+
520
+ def key_object(obj: bpy.types.Object, action: bpy.types.Action, frame: float, location=None,
521
+ rotation_degrees=None, scale=None) -> None:
522
+ """
523
+ Keys an object's transform (mechanical rigs: wheels, doors, turrets are objects in a hierarchy, each
524
+ pivoting about its own origin). Only the given channels are keyed.
525
+ """
526
+ use_action(obj, action)
527
+ if location is not None:
528
+ obj.location = location
529
+ obj.keyframe_insert("location", frame=frame)
530
+ if rotation_degrees is not None:
531
+ obj.rotation_mode = "XYZ"
532
+ obj.rotation_euler = [math.radians(value) for value in rotation_degrees]
533
+ obj.keyframe_insert("rotation_euler", frame=frame)
534
+ if scale is not None:
535
+ obj.scale = scale
536
+ obj.keyframe_insert("scale", frame=frame)
537
+
538
+
539
+ def set_interpolation(action: bpy.types.Action, interpolation: str = "BEZIER", easing: str = "AUTO") -> int:
540
+ """
541
+ Sets every key's interpolation: BEZIER (organic motion), LINEAR (constant-speed spins, mechanical
542
+ motion), CONSTANT (stepped). Exporters sample the curves, so what plays is what Blender evaluates.
543
+
544
+ :returns: The number of keys changed.
545
+ """
546
+ changed = 0
547
+ for curve in fcurves(action):
548
+ for key in curve.keyframe_points:
549
+ key.interpolation = interpolation
550
+ key.easing = easing
551
+ changed += 1
552
+ curve.update()
553
+ return changed
554
+
555
+
556
+ def make_cyclic(action: bpy.types.Action, first_frame: float = None, last_frame: float = None) -> dict:
557
+ """
558
+ Makes a looping clip: the last frame's key is set equal to the first frame's on every curve (so time
559
+ T and time 0 are the same pose and the loop has no pop), the curves get a Cycles modifier and
560
+ cyclic-aware handles, and the action's manual frame range is set to [first, last] for exporters.
561
+
562
+ :param action: The clip.
563
+ :param first_frame: Loop start (default: the first key).
564
+ :param last_frame: Loop end, the frame that repeats the start (default: the last key).
565
+ :returns: {"frame_start", "frame_end", "curves", "max_seam_jump"} (the largest value change the seam
566
+ fix made, in curve units).
567
+ """
568
+ curves = fcurves(action)
569
+ first = first_frame if first_frame is not None else min(curve.range()[0] for curve in curves)
570
+ last = last_frame if last_frame is not None else max(curve.range()[1] for curve in curves)
571
+ seam = 0.0
572
+ for curve in curves:
573
+ start_value = curve.evaluate(first)
574
+ seam = max(seam, abs(curve.evaluate(last) - start_value))
575
+ curve.keyframe_points.insert(first, start_value, options={"REPLACE"})
576
+ curve.keyframe_points.insert(last, start_value, options={"REPLACE"})
577
+ if not any(modifier.type == "CYCLES" for modifier in curve.modifiers):
578
+ curve.modifiers.new("CYCLES")
579
+ curve.update()
580
+ action.use_cyclic = True
581
+ action.use_frame_range = True
582
+ action.frame_start, action.frame_end = first, last
583
+ return {"frame_start": first, "frame_end": last, "curves": len(curves), "max_seam_jump": seam}
584
+
585
+
586
+ def stash_action(owner, action: bpy.types.Action, mute: bool = True) -> bpy.types.NlaTrack:
587
+ """
588
+ Puts an action on its own NLA track named after it, so the glTF exporter (animation mode NLA_TRACKS)
589
+ writes it as its own animation and the FBX exporter as its own take. The track is muted so stashed
590
+ clips do not blend into what the scene plays.
591
+
592
+ :returns: The NLA track.
593
+ """
594
+ owner.animation_data_create()
595
+ track = owner.animation_data.nla_tracks.get(action.name) or owner.animation_data.nla_tracks.new()
596
+ track.name = action.name
597
+ for strip in list(track.strips):
598
+ track.strips.remove(strip)
599
+ start = action.frame_range[0]
600
+ strip = track.strips.new(action.name, int(start), action)
601
+ strip.name = action.name
602
+ slot = _slot_for(owner, action)
603
+ if slot is not None:
604
+ strip.action_slot = slot
605
+ track.mute = mute
606
+ return track
607
+
608
+
609
+ def clear_active_action(owner) -> None:
610
+ """Unassigns the active action (the clips stay in the file through their fake user and NLA tracks)."""
611
+ if owner.animation_data:
612
+ owner.animation_data.action = None
613
+
614
+
615
+ def split_action(source: bpy.types.Action, name: str, frame_start: float, frame_end: float,
616
+ start_at: float = None) -> bpy.types.Action:
617
+ """
618
+ Cuts a clip out of a longer action (a mocap take, an authored sequence): a copy keyed exactly at the
619
+ cut frames with the evaluated values, keys outside removed, optionally shifted to start at `start_at`.
620
+
621
+ :param source: The long action.
622
+ :param name: New clip name.
623
+ :param frame_start: First frame of the clip.
624
+ :param frame_end: Last frame of the clip.
625
+ :param start_at: Frame the clip is moved to start on (None keeps the original timing).
626
+ :returns: The new action, with a fake user and its manual frame range set.
627
+ """
628
+ clip = source.copy()
629
+ clip.name = name
630
+ clip.use_fake_user = True
631
+ shift = 0.0 if start_at is None else start_at - frame_start
632
+ for curve in fcurves(clip):
633
+ for modifier in list(curve.modifiers):
634
+ curve.modifiers.remove(modifier)
635
+ start_value, end_value = curve.evaluate(frame_start), curve.evaluate(frame_end)
636
+ curve.keyframe_points.insert(frame_start, start_value, options={"REPLACE"})
637
+ curve.keyframe_points.insert(frame_end, end_value, options={"REPLACE"})
638
+ for key in reversed(list(curve.keyframe_points)):
639
+ if key.co.x < frame_start - 1e-6 or key.co.x > frame_end + 1e-6:
640
+ curve.keyframe_points.remove(key)
641
+ if shift:
642
+ for key in curve.keyframe_points:
643
+ key.co.x += shift
644
+ key.handle_left.x += shift
645
+ key.handle_right.x += shift
646
+ curve.update()
647
+ clip.use_frame_range = True
648
+ clip.frame_start, clip.frame_end = frame_start + shift, frame_end + shift
649
+ return clip
650
+
651
+
652
+ def bake_to_keys(armature: bpy.types.Object, action_name: str, frame_start: int, frame_end: int,
653
+ clear_constraints: bool = True, step: int = 1) -> bpy.types.Action:
654
+ """
655
+ Bakes what the rig evaluates (IK, constraints, drivers, NLA) into plain FK keys on every pose bone, one
656
+ key per frame, in a new action. Exporters and engines do not run Blender constraints, so a rig that
657
+ uses them must ship baked keys.
658
+
659
+ :param armature: Armature object.
660
+ :param action_name: Name of the baked clip.
661
+ :param frame_start: First frame.
662
+ :param frame_end: Last frame.
663
+ :param clear_constraints: Remove the constraints after baking (keep them on the authoring copy).
664
+ :param step: Frame step.
665
+ :returns: The baked action, active on the armature, with a fake user.
666
+ """
667
+ _select([armature], armature)
668
+ with bpy.context.temp_override(**_override(armature)):
669
+ _check(bpy.ops.object.mode_set(mode="POSE"), "mode_set POSE")
670
+ _check(bpy.ops.pose.select_all(action="SELECT"), "pose select_all")
671
+ _check(bpy.ops.nla.bake(frame_start=frame_start, frame_end=frame_end, step=step, only_selected=False,
672
+ visual_keying=True, clear_constraints=clear_constraints, use_current_action=False,
673
+ bake_types={"POSE"}), "nla.bake")
674
+ _check(bpy.ops.object.mode_set(mode="OBJECT"), "mode_set OBJECT")
675
+ action = armature.animation_data.action
676
+ action.name = action_name
677
+ action.use_fake_user = True
678
+ return action
679
+
680
+
681
+ def fit_pole_angle(armature: bpy.types.Object, ik_bone: str, steps: int = 72) -> float:
682
+ """
683
+ Finds the IK pole angle that leaves the rest pose where it is (the right angle depends on the bone
684
+ rolls, so it is searched, not guessed): the angle whose solve moves the chain's middle joint least,
685
+ refined to 0.1 degree. Call with the IK constraint already on `ik_bone` and the scene at rest.
686
+
687
+ :returns: The pole angle in degrees (already set on the constraint).
688
+ :raises ValueError: when the bone has no IK constraint.
689
+ """
690
+ pose_bone = armature.pose.bones[ik_bone]
691
+ constraint = next((item for item in pose_bone.constraints if item.type == "IK"), None)
692
+ if constraint is None:
693
+ raise ValueError(f"{ik_bone} has no IK constraint")
694
+ rest_head = armature.data.bones[ik_bone].head_local.copy()
695
+
696
+ def moved(angle_degrees: float) -> float:
697
+ constraint.pole_angle = math.radians(angle_degrees)
698
+ bpy.context.view_layer.update()
699
+ return (pose_bone.head - rest_head).length
700
+
701
+ best = min((index * 360.0 / steps - 180.0 for index in range(steps)), key=moved)
702
+ step = 360.0 / steps
703
+ while step > 0.1:
704
+ step /= 2.0
705
+ best = min((best - step, best, best + step), key=moved)
706
+ moved(best)
707
+ return best
708
+
709
+
710
+ # --- retargeting ----------------------------------------------------------------------------------------------
711
+
712
+ def _rest_world_rotation(armature: bpy.types.Object, bone_name: str) -> Quaternion:
713
+ """World-space rest orientation of a bone."""
714
+ return (armature.matrix_world @ armature.data.bones[bone_name].matrix_local).to_quaternion()
715
+
716
+
717
+ def _ordered(bones: list, armature: bpy.types.Object) -> list:
718
+ """Target bone names sorted parents first."""
719
+ def depth(name: str) -> int:
720
+ return len(armature.data.bones[name].parent_recursive)
721
+ return sorted(bones, key=depth)
722
+
723
+
724
+ def retarget_action(source: bpy.types.Object, target: bpy.types.Object, bone_map: dict, frames: list,
725
+ action_name: str, root_source: str = None, root_target: str = None) -> bpy.types.Action:
726
+ """
727
+ Retargets a clip between two rigs whose bone names, proportions and rolls differ. Each mapped target
728
+ bone gets the source bone's world-space rotation change from its rest pose (delta = pose x rest^-1,
729
+ applied on the target's own rest), which makes the method independent of bone rolls. The root bone's
730
+ translation from rest is scaled by the two root heights, so a shorter character takes shorter strides.
731
+
732
+ :param source: Armature playing the source action at the frames given.
733
+ :param target: Armature that receives the keys (rest poses need not match).
734
+ :param bone_map: {source bone: target bone}.
735
+ :param frames: Frames to sample (every frame of the clip; the result is one key per frame).
736
+ :param action_name: Name of the new action on the target.
737
+ :param root_source: Source root (hips) bone, whose translation is carried over; None for rotation only.
738
+ :param root_target: The matching target bone.
739
+ :returns: The new action.
740
+ """
741
+ action = new_action(target, action_name)
742
+ order = _ordered(list(bone_map.values()), target)
743
+ inverse_map = {value: key for key, value in bone_map.items()}
744
+ rest_source = {name: _rest_world_rotation(source, name) for name in bone_map}
745
+ rest_target = {name: _rest_world_rotation(target, name) for name in order}
746
+ ratio = 1.0
747
+ if root_source and root_target:
748
+ ratio = (target.matrix_world @ target.data.bones[root_target].head_local).z / \
749
+ max((source.matrix_world @ source.data.bones[root_source].head_local).z, 1e-6)
750
+ scene = bpy.context.scene
751
+ for pose_bone in target.pose.bones:
752
+ pose_bone.rotation_mode = "QUATERNION"
753
+ for frame in frames:
754
+ scene.frame_set(int(frame), subframe=frame - int(frame))
755
+ source_world = {name: (source.matrix_world @ source.pose.bones[name].matrix) for name in bone_map}
756
+ for target_name in order:
757
+ source_name = inverse_map[target_name]
758
+ delta = source_world[source_name].to_quaternion() @ rest_source[source_name].inverted()
759
+ world_rotation = delta @ rest_target[target_name]
760
+ pose_bone = target.pose.bones[target_name]
761
+ current = target.matrix_world @ pose_bone.matrix
762
+ if target_name == root_target and root_source:
763
+ rest_head = source.matrix_world @ source.data.bones[root_source].head_local
764
+ moved = (source_world[root_source].translation - rest_head) * ratio
765
+ head = target.matrix_world @ target.data.bones[root_target].head_local + moved
766
+ else:
767
+ head = current.translation
768
+ world = Matrix.LocRotScale(head, world_rotation, Vector((1.0, 1.0, 1.0)))
769
+ pose_bone.matrix = target.matrix_world.inverted() @ world
770
+ # Children read the parent's evaluated matrix: update before setting the next bone.
771
+ bpy.context.view_layer.update()
772
+ for target_name in order:
773
+ pose_bone = target.pose.bones[target_name]
774
+ pose_bone.keyframe_insert("rotation_quaternion", frame=frame, group=target_name)
775
+ if target_name == root_target and root_source:
776
+ pose_bone.keyframe_insert("location", frame=frame, group=target_name)
777
+ return action
778
+
779
+
780
+ def bone_direction_error(source: bpy.types.Object, target: bpy.types.Object, bone_map: dict) -> float:
781
+ """Largest angle (degrees) between the world-space directions of mapped bones in the current pose."""
782
+ worst = 0.0
783
+ for source_name, target_name in bone_map.items():
784
+ source_bone, target_bone = source.pose.bones[source_name], target.pose.bones[target_name]
785
+ source_direction = source.matrix_world.to_3x3() @ (source_bone.tail - source_bone.head)
786
+ target_direction = target.matrix_world.to_3x3() @ (target_bone.tail - target_bone.head)
787
+ worst = max(worst, math.degrees(source_direction.angle(target_direction)))
788
+ return worst
789
+
790
+
791
+ # --- game skeleton from a control rig -------------------------------------------------------------------------
792
+
793
+ # Prefixes of a Rigify rig's non-deform layers; ORG-x / MCH-x stand for the deform bone DEF-x.
794
+ CONTROL_PREFIXES = ("ORG-", "MCH-")
795
+ DEFORM_PREFIX = "DEF-"
796
+
797
+
798
+ def _deform_ancestor(bone: bpy.types.Bone, deform_names: set):
799
+ """
800
+ The deform bone a deform bone should hang from: its nearest deform ancestor, where an ORG- / MCH-
801
+ ancestor counts as the DEF- bone of the same name (Rigify parents DEF-thigh.L to ORG-spine, which stands
802
+ for DEF-spine). None for the skeleton root.
803
+ """
804
+ ancestor = bone.parent
805
+ while ancestor is not None:
806
+ if ancestor.name in deform_names:
807
+ return ancestor.name
808
+ if ancestor.name.startswith(CONTROL_PREFIXES):
809
+ counterpart = DEFORM_PREFIX + ancestor.name[len(CONTROL_PREFIXES[0]):]
810
+ if counterpart in deform_names and counterpart != bone.name:
811
+ return counterpart
812
+ ancestor = ancestor.parent
813
+ return None
814
+
815
+
816
+ def game_skeleton(control: bpy.types.Object, name: str, rename=None) -> bpy.types.Object:
817
+ """
818
+ Builds a clean deform-only skeleton from a control rig (e.g. a Rigify rig, whose DEF bones hang under
819
+ ORG / MCH bones): every deform bone copied at its rest matrix, parented to its nearest deform ancestor,
820
+ and constrained (Copy Transforms) to the control rig, so animating the control rig moves it. Bake it
821
+ with bake_to_keys and export it alone; re-point the skinned meshes to it with attach().
822
+
823
+ :param control: The control rig.
824
+ :param name: New armature name.
825
+ :param rename: Optional function old bone name -> new name (e.g. strip "DEF-").
826
+ :returns: The new armature.
827
+ """
828
+ rename = rename or (lambda bone_name: bone_name)
829
+ deform = [bone for bone in control.data.bones if bone.use_deform]
830
+ deform_names = {bone.name for bone in deform}
831
+ data = bpy.data.armatures.new(name)
832
+ skeleton = bpy.data.objects.new(name, data)
833
+ bpy.context.scene.collection.objects.link(skeleton)
834
+ skeleton.matrix_world = control.matrix_world
835
+ _select([skeleton], skeleton)
836
+ with bpy.context.temp_override(**_override(skeleton)):
837
+ _check(bpy.ops.object.mode_set(mode="EDIT"), "mode_set EDIT")
838
+ for bone in deform:
839
+ edit_bone = data.edit_bones.new(rename(bone.name))
840
+ edit_bone.head, edit_bone.tail = bone.head_local, bone.tail_local
841
+ edit_bone.matrix = bone.matrix_local
842
+ for bone in deform:
843
+ parent_name = _deform_ancestor(bone, deform_names)
844
+ if parent_name is not None:
845
+ data.edit_bones[rename(bone.name)].parent = data.edit_bones[rename(parent_name)]
846
+ _check(bpy.ops.object.mode_set(mode="OBJECT"), "mode_set OBJECT")
847
+ for bone in deform:
848
+ constraint = skeleton.pose.bones[rename(bone.name)].constraints.new("COPY_TRANSFORMS")
849
+ constraint.target, constraint.subtarget = control, bone.name
850
+ for mesh in [obj for obj in bpy.data.objects if obj.type == "MESH"]:
851
+ modifier = next((item for item in mesh.modifiers if item.type == "ARMATURE" and item.object == control), None)
852
+ if modifier is None:
853
+ continue
854
+ for group in mesh.vertex_groups:
855
+ if group.name in deform_names:
856
+ group.name = rename(group.name)
857
+ attach(mesh, skeleton)
858
+ return skeleton
859
+
860
+
861
+ # --- shape keys -----------------------------------------------------------------------------------------------
862
+
863
+ def add_shape_key(mesh: bpy.types.Object, name: str, offsets: np.ndarray) -> bpy.types.ShapeKey:
864
+ """
865
+ Adds a shape key (glTF morph target / Unity and BabylonJS blendshape) from per-vertex offsets.
866
+ The Basis key is created first when missing. Keys hold full vertex positions, so every key costs a
867
+ copy of the positions (and normals) in the exported file.
868
+
869
+ :param mesh: Mesh object.
870
+ :param name: Key name; exported as the morph target name (glTF mesh.extras.targetNames).
871
+ :param offsets: (vertices, 3) displacement from the basis, metres, local space.
872
+ :returns: The key block.
873
+ :raises ValueError: when the offsets do not match the vertex count.
874
+ """
875
+ count = len(mesh.data.vertices)
876
+ offsets = np.asarray(offsets, dtype=np.float64)
877
+ if offsets.shape != (count, 3):
878
+ raise ValueError(f"offsets must be ({count}, 3), got {offsets.shape}")
879
+ if mesh.data.shape_keys is None:
880
+ mesh.shape_key_add(name="Basis", from_mix=False)
881
+ key = mesh.shape_key_add(name=name, from_mix=False)
882
+ basis = np.empty(count * 3)
883
+ mesh.data.shape_keys.key_blocks["Basis"].data.foreach_get("co", basis)
884
+ key.data.foreach_set("co", (basis.reshape(-1, 3) + offsets).ravel())
885
+ mesh.data.update()
886
+ return key
887
+
888
+
889
+ def key_shape(mesh: bpy.types.Object, action: bpy.types.Action, frame: float, values: dict) -> None:
890
+ """Keys shape-key values {key name: 0..1} at a frame on the mesh's shape-key block."""
891
+ keys = mesh.data.shape_keys
892
+ use_action(keys, action)
893
+ for key_name, value in values.items():
894
+ keys.key_blocks[key_name].value = value
895
+ keys.key_blocks[key_name].keyframe_insert("value", frame=frame)
896
+
897
+
898
+ # --- mechanical rigs ------------------------------------------------------------------------------------------
899
+
900
+ def set_origin(obj: bpy.types.Object, pivot_world) -> None:
901
+ """
902
+ Moves a mesh object's origin to a world-space pivot (wheel axle centre, hinge line, turret ring)
903
+ without moving its geometry: an object rotates about its origin, so the pivot must be exact.
904
+ """
905
+ bpy.context.view_layer.update()
906
+ pivot = Vector(pivot_world)
907
+ local_pivot = obj.matrix_world.inverted() @ pivot
908
+ obj.data.transform(Matrix.Translation(-local_pivot))
909
+ obj.data.update()
910
+ obj.matrix_world = obj.matrix_world @ Matrix.Translation(local_pivot)
911
+
912
+
913
+ def pivot_empty(name: str, location, parent: bpy.types.Object = None, display_size: float = 0.1) -> bpy.types.Object:
914
+ """An empty at a world-space pivot (steering knuckle, suspension arm), optionally parented."""
915
+ empty = bpy.data.objects.new(name, None)
916
+ empty.empty_display_type = "ARROWS"
917
+ empty.empty_display_size = display_size
918
+ bpy.context.scene.collection.objects.link(empty)
919
+ empty.location = location
920
+ if parent is not None:
921
+ parent_to(empty, parent)
922
+ return empty
923
+
924
+
925
+ def parent_to(child: bpy.types.Object, parent: bpy.types.Object) -> None:
926
+ """
927
+ Parents keeping the child's world transform (a clean parent inverse, no operator). The view layer is
928
+ updated first: matrix_world is stale after setting .location in a script, and parenting with the stale
929
+ (identity) matrices silently moves the child to the origin.
930
+ """
931
+ bpy.context.view_layer.update()
932
+ world = child.matrix_world.copy()
933
+ child.parent = parent
934
+ child.matrix_parent_inverse = parent.matrix_world.inverted()
935
+ child.matrix_world = world
936
+
937
+
938
+ def wheel_degrees_per_frame(speed_mps: float, radius: float, fps: float) -> float:
939
+ """Spin a rolling wheel needs to match ground speed: (speed / radius) radians per second."""
940
+ return math.degrees(speed_mps / radius) / fps
941
+
942
+
943
+ # --- export and round trip ------------------------------------------------------------------------------------
944
+
945
+ # glTF for BabylonJS: every NLA track name becomes one animation (one AnimationGroup), merged across the
946
+ # objects that carry a track of that name; 4 influences, shape keys as morph targets, no leaf bones.
947
+ # Modifiers are not applied: the Armature modifier is the skin. NLA_TRACKS, not the default ACTIONS: with
948
+ # ACTIONS and "Export all Armature Actions" (export_anim_single_armature, on by default) a file with one
949
+ # armature gets every armature action in the .blend - a control rig's authoring clip turned up as a second
950
+ # animation on a baked game skeleton. Here only stashed clips ship.
951
+ GLTF_RIG_SETTINGS = {
952
+ "export_format": "GLB", "export_yup": True, "export_apply": False, "export_animations": True,
953
+ "export_animation_mode": "NLA_TRACKS", "export_nla_strips": True, "export_force_sampling": True,
954
+ "export_frame_step": 1, "export_def_bones": True, "export_leaf_bone": False, "export_influence_nb": 4,
955
+ "export_all_influences": False, "export_morph": True, "export_morph_animation": True,
956
+ "export_anim_slide_to_zero": False, "export_reset_pose_bones": True, "export_optimize_animation_size": True,
957
+ }
958
+
959
+ # FBX for Unity (guide 8.2a): -Z forward, Y up, unit scale, NO baked space transform for rigs, no leaf
960
+ # bones, deform bones only, one take per action, start and end keyed.
961
+ UNITY_FBX_RIG_SETTINGS = {
962
+ "axis_forward": "-Z", "axis_up": "Y", "apply_scale_options": "FBX_SCALE_UNITS", "bake_space_transform": False,
963
+ "add_leaf_bones": False, "use_armature_deform_only": True, "mesh_smooth_type": "OFF",
964
+ "bake_anim": True, "bake_anim_use_all_bones": True, "bake_anim_use_nla_strips": False,
965
+ "bake_anim_use_all_actions": True, "bake_anim_force_startend_keying": True, "bake_anim_step": 1.0,
966
+ "bake_anim_simplify_factor": 0.0,
967
+ }
968
+
969
+
970
+ # Overrides for a mechanical (object-hierarchy) rig: one scene take per file. With all-actions on, the FBX
971
+ # exporter writes a take per object x action (14 for a 7-object rig with 2 clips); with NLA strips on, a
972
+ # take per strip (6 identical "Drive" takes). Make the clip active on its objects, set the scene frame range
973
+ # to the clip, and export with these: exactly one take, which round-trips to 1e-7 m.
974
+ UNITY_FBX_SCENE_TAKE = {"bake_anim_use_nla_strips": False, "bake_anim_use_all_actions": False}
975
+
976
+ # GLB layout: 12-byte header, then the JSON chunk's length (4 bytes), type (4 bytes) and data.
977
+ GLB_MAGIC = b"glTF"
978
+ GLB_JSON_LENGTH_OFFSET = 12
979
+ GLB_JSON_OFFSET = 20
980
+
981
+
982
+ def export_rig(path: str, objects: list, settings: dict = None) -> dict:
983
+ """
984
+ Exports a rig and its meshes: .glb / .gltf with GLTF_RIG_SETTINGS, .fbx with UNITY_FBX_RIG_SETTINGS.
985
+
986
+ :param path: Output file; the extension picks the format.
987
+ :param objects: Armature, its meshes, and any mechanical-rig objects to export.
988
+ :param settings: Overrides merged into the preset.
989
+ :returns: The settings used.
990
+ :raises RuntimeError: when the exporter does not finish or writes nothing.
991
+ """
992
+ fbx = path.lower().endswith(".fbx")
993
+ used = dict(UNITY_FBX_RIG_SETTINGS if fbx else GLTF_RIG_SETTINGS)
994
+ if not fbx and path.lower().endswith(".gltf"):
995
+ used["export_format"] = "GLTF_SEPARATE"
996
+ used.update(settings or {})
997
+ _select(objects, objects[0])
998
+ exporter = bpy.ops.export_scene.fbx if fbx else bpy.ops.export_scene.gltf
999
+ _check(exporter(filepath=path, use_selection=True, **used), f"export {path}")
1000
+ if not os.path.exists(path):
1001
+ raise RuntimeError(f"nothing was written to {path}")
1002
+ return used
1003
+
1004
+
1005
+ def _gltf_document(path: str) -> dict:
1006
+ """The JSON document of a .glb (its first chunk) or a .gltf file."""
1007
+ with open(path, "rb") as handle:
1008
+ data = handle.read()
1009
+ if data[:4] == GLB_MAGIC:
1010
+ length = struct.unpack_from("<I", data, GLB_JSON_LENGTH_OFFSET)[0]
1011
+ return json.loads(data[GLB_JSON_OFFSET:GLB_JSON_OFFSET + length])
1012
+ return json.loads(data)
1013
+
1014
+
1015
+ def gltf_animation_summary(path: str) -> dict:
1016
+ """
1017
+ Reads a .glb / .gltf and lists what BabylonJS will load: animations (one AnimationGroup each) with
1018
+ their duration in seconds and channel paths, skins with joint counts, and morph target names.
1019
+ """
1020
+ document = _gltf_document(path)
1021
+ animations = []
1022
+ for animation in document.get("animations", []):
1023
+ inputs = {animation["samplers"][channel["sampler"]]["input"] for channel in animation["channels"]}
1024
+ duration = max(document["accessors"][index]["max"][0] for index in inputs)
1025
+ start = min(document["accessors"][index]["min"][0] for index in inputs)
1026
+ animations.append({"name": animation.get("name"), "start_s": round(start, 4), "end_s": round(duration, 4),
1027
+ "channels": len(animation["channels"]),
1028
+ "paths": sorted({channel["target"]["path"] for channel in animation["channels"]})})
1029
+ skins = [{"name": skin.get("name"), "joints": len(skin["joints"])} for skin in document.get("skins", [])]
1030
+ targets = [mesh.get("extras", {}).get("targetNames", []) for mesh in document.get("meshes", [])]
1031
+ attributes = sorted({name for mesh in document.get("meshes", []) for primitive in mesh["primitives"]
1032
+ for name in primitive["attributes"]})
1033
+ return {"animations": animations, "skins": skins, "morph_targets": [names for names in targets if names],
1034
+ "attributes": attributes}
1035
+
1036
+
1037
+ def evaluated_positions(mesh: bpy.types.Object) -> np.ndarray:
1038
+ """World-space positions (N, 3) of the mesh as currently evaluated (skinning and shape keys applied)."""
1039
+ depsgraph = bpy.context.evaluated_depsgraph_get()
1040
+ evaluated = mesh.evaluated_get(depsgraph)
1041
+ data = evaluated.to_mesh()
1042
+ try:
1043
+ coordinates = np.empty(len(data.vertices) * 3)
1044
+ data.vertices.foreach_get("co", coordinates)
1045
+ matrix = np.array(evaluated.matrix_world)
1046
+ finally:
1047
+ evaluated.to_mesh_clear()
1048
+ return coordinates.reshape(-1, 3) @ matrix[:3, :3].T + matrix[:3, 3]
1049
+
1050
+
1051
+ def reset_pose(armature: bpy.types.Object) -> None:
1052
+ """Puts every pose bone back to its rest transform (bones a clip does not key keep their last values)."""
1053
+ for pose_bone in armature.pose.bones:
1054
+ pose_bone.location = (0.0, 0.0, 0.0)
1055
+ pose_bone.rotation_quaternion = (1.0, 0.0, 0.0, 0.0)
1056
+ pose_bone.rotation_euler = (0.0, 0.0, 0.0)
1057
+ pose_bone.scale = (1.0, 1.0, 1.0)
1058
+
1059
+
1060
+ def play(owner, action: bpy.types.Action, frame: float) -> None:
1061
+ """
1062
+ Plays a clip at a frame the way the exporters write it: an armature's pose is reset first (glTF
1063
+ "Reset Pose Bones Between Actions", FBX "Key All Bones"), so bones the clip does not key sit at rest
1064
+ instead of keeping the previous clip's pose. Then the clip is assigned with a fitting slot and the
1065
+ scene is evaluated.
1066
+ """
1067
+ if getattr(owner, "type", None) == "ARMATURE":
1068
+ reset_pose(owner)
1069
+ use_action(owner, action)
1070
+ bpy.context.scene.frame_set(int(frame), subframe=frame - int(frame))
1071
+
1072
+
1073
+ # --- round trip ---------------------------------------------------------------------------------------------
1074
+
1075
+ def import_rig(path: str, fps: int = 30) -> tuple:
1076
+ """
1077
+ Loads an exported .glb / .gltf / .fbx into an empty scene, the way a round-trip check needs it: every
1078
+ other datablock is discarded first (objects held from before become invalid). Returns the armature and
1079
+ the mesh skinned to it (the mesh is None for a file with no skinned mesh).
1080
+
1081
+ :param path: The exported file.
1082
+ :param fps: Scene frame rate to compare frames at (glTF stores seconds, FBX stores time).
1083
+ :raises RuntimeError: when the importer does not finish or the file holds no armature.
1084
+ """
1085
+ bpy.ops.wm.read_factory_settings(use_empty=True)
1086
+ bpy.context.scene.render.fps = fps
1087
+ importer = bpy.ops.import_scene.fbx if path.lower().endswith(".fbx") else bpy.ops.import_scene.gltf
1088
+ _check(importer(filepath=path), f"import {path}")
1089
+ armature = next((obj for obj in bpy.data.objects if obj.type == "ARMATURE"), None)
1090
+ if armature is None:
1091
+ raise RuntimeError(f"{path} holds no armature")
1092
+ mesh = next((obj for obj in bpy.data.objects if obj.type == "MESH" and obj.find_armature() == armature), None)
1093
+ return armature, mesh
1094
+
1095
+
1096
+ def find_clip(name: str) -> bpy.types.Action:
1097
+ """
1098
+ The imported action for a clip name. glTF keeps the name ("Walk"); FBX re-imports a take written as
1099
+ "Rig|Walk" as "Rig|Rig|Walk", so the part after the last "|" is compared.
1100
+ """
1101
+ return next((action for action in bpy.data.actions if action.name.split("|")[-1] == name), None)
1102
+
1103
+
1104
+ def nearest_vertex(mesh: bpy.types.Object, armature: bpy.types.Object, point) -> int:
1105
+ """Index of the mesh vertex nearest a world point in the rest pose (vertex order is not kept by exporters)."""
1106
+ armature.data.pose_position = "REST"
1107
+ bpy.context.view_layer.update()
1108
+ positions = evaluated_positions(mesh)
1109
+ armature.data.pose_position = "POSE"
1110
+ bpy.context.view_layer.update()
1111
+ return int(np.argmin(np.linalg.norm(positions - np.asarray(point), axis=1)))
1112
+
1113
+
1114
+ def gltf_rest(path: str) -> dict:
1115
+ """
1116
+ The static node transforms of a .glb / .gltf, converted to Blender's Z-up object space: {node name:
1117
+ (location, rotation_quaternion, scale)}. Blender's glTF importer evaluates the active animation at the
1118
+ current frame straight after import, overwriting object transforms; this is the rest to return to.
1119
+ """
1120
+ document = _gltf_document(path)
1121
+ rest = {}
1122
+ for node in document.get("nodes", []):
1123
+ x_value, y_value, z_value = node.get("translation", (0.0, 0.0, 0.0))
1124
+ x_rotation, y_rotation, z_rotation, w_rotation = node.get("rotation", (0.0, 0.0, 0.0, 1.0))
1125
+ x_scale, y_scale, z_scale = node.get("scale", (1.0, 1.0, 1.0))
1126
+ rest[node.get("name")] = ((x_value, -z_value, y_value), (w_rotation, x_rotation, -z_rotation, y_rotation),
1127
+ (x_scale, z_scale, y_scale))
1128
+ return rest
1129
+
1130
+
1131
+ def play_clip(name: str, frame: float, rest: dict = None) -> int:
1132
+ """
1133
+ Plays one imported clip on every object it animates, at a frame: all NLA tracks muted and every active
1134
+ action cleared first, then each action of that clip (glTF: one action, a slot per object; FBX: "Owner|Clip"
1135
+ actions) assigned to the objects its slots name. Armatures are reset to rest first, and with `rest`
1136
+ (gltf_rest) every object is put back on its node transform, as an engine shows nodes a clip does not
1137
+ animate. Returns how many objects were assigned.
1138
+
1139
+ :raises KeyError: when no action belongs to the clip.
1140
+ """
1141
+ for obj in bpy.data.objects:
1142
+ if obj.animation_data is None:
1143
+ continue
1144
+ obj.animation_data.action = None
1145
+ for track in obj.animation_data.nla_tracks:
1146
+ track.mute = True
1147
+ if obj.type == "ARMATURE":
1148
+ reset_pose(obj)
1149
+ for node_name, (location, rotation, scale) in (rest or {}).items():
1150
+ obj = bpy.data.objects.get(node_name)
1151
+ if obj is not None and obj.type != "ARMATURE":
1152
+ obj.location, obj.scale = location, scale
1153
+ obj.rotation_mode = "QUATERNION"
1154
+ obj.rotation_quaternion = rotation
1155
+ actions = [action for action in bpy.data.actions if action.name.split("|")[-1] == name]
1156
+ if not actions:
1157
+ raise KeyError(f"no imported action for clip {name}")
1158
+ assigned = 0
1159
+ for action in actions:
1160
+ owner_name = action.name.split("|")[0] if "|" in action.name else None
1161
+ for slot in action.slots:
1162
+ owner = bpy.data.objects.get(slot.name_display) or bpy.data.objects.get(owner_name or "")
1163
+ if owner is None:
1164
+ continue
1165
+ owner.animation_data_create()
1166
+ owner.animation_data.action = action
1167
+ owner.animation_data.action_slot = slot
1168
+ assigned += 1
1169
+ bpy.context.scene.frame_set(int(frame), subframe=frame - int(frame))
1170
+ return assigned