agent-manifesto-kit 1.6.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -0
- package/collection/NOTICE.md +8 -0
- package/collection/skills/astro-preview/SKILL.md +60 -0
- package/collection/skills/kimodo-motion/SKILL.md +101 -0
- package/collection/skills/kimodo-motion/agents/openai.yaml +4 -0
- package/collection/skills/kimodo-motion/patches/kimodo-cpp-keyposes.patch +398 -0
- package/collection/skills/kimodo-motion/scripts/kimodo_motion.py +459 -0
- package/collection/skills/kimodo-motion/scripts/kimodo_retarget.py +280 -0
- package/collection/skills/kimodo-motion/tests/blender_roundtrip.py +105 -0
- package/collection/skills/kimodo-motion/tests/test_kimodo_motion.py +183 -0
- package/collection/skills/self-reflection/SKILL.md +121 -0
- package/collection/skills/self-reflection/agents/openai.yaml +4 -0
- package/collection/skills/self-reflection/assets/report-template.json +8 -0
- package/collection/skills/self-reflection/assets/report.html +64 -0
- package/collection/skills/self-reflection/references/report-format.md +42 -0
- package/collection/skills/self-reflection/scripts/export_claude.py +59 -0
- package/collection/skills/self-reflection/scripts/reflect.py +320 -0
- package/collection/skills/self-reflection/scripts/report.py +322 -0
- package/collection/skills/self-reflection/tests/test_export_claude.py +83 -0
- package/collection/skills/self-reflection/tests/test_reflect.py +189 -0
- package/collection/skills/self-reflection/tests/test_report.py +250 -0
- package/package.json +1 -1
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
"""Kimodo SOMA30 motions to and from a Mixamo-named Blender rig (rotation copy through both rests). Runs in Blender.
|
|
2
|
+
|
|
3
|
+
blender -b RIG.blend --factory-startup --python-exit-code 1 --python kimodo_retarget.py -- \
|
|
4
|
+
keypose NAME=ACTION.blend[@FRAME] [...] --out POSES.json [--toe-y M] [--prefix mixamorig:]
|
|
5
|
+
each action's pose on the rig (an action-only .blend: its first action, applied at FRAME, default its first)
|
|
6
|
+
as a Kimodo key pose {"poses": {NAME: {"root", "local_xyzw", ...}}}, the root raised or lowered so the lower toe
|
|
7
|
+
stands at --toe-y (Kimodo's own standing height, about 0.015 m), then this script's direction check on it
|
|
8
|
+
blender -b RIG.blend --factory-startup --python-exit-code 1 --python kimodo_retarget.py -- \
|
|
9
|
+
retarget --clip NAME=MOTION_DIR [...] --out CLIPS.glb [--report REPORT.json] [--prefix mixamorig:]
|
|
10
|
+
each motion baked onto the rig as an action (every mapped bone's world turn copied, only the hips moved,
|
|
11
|
+
scaled by the hips' rest heights), exported together; fails above DIRECTION_TOL_DEG (the report is written,
|
|
12
|
+
no GLB)
|
|
13
|
+
|
|
14
|
+
The rig: one armature, Mixamo bone names (with --prefix), Z up, facing -Y (Blender's Mixamo import), with Hips, Spine,
|
|
15
|
+
Spine1, Spine2, Neck, Head, Left/Right Shoulder, Arm, ForeArm, Hand, HandMiddle1, HandThumb1, UpLeg, Leg, Foot,
|
|
16
|
+
ToeBase. Kimodo's Leg is Mixamo's UpLeg, its Shin Mixamo's Leg; Neck2 has no Mixamo bone. The rests are aligned once
|
|
17
|
+
(each rig bone's rest frame turned onto the Kimodo T-pose frame: the bone toward its mapped child and one side
|
|
18
|
+
vector, hands by the middle finger and the thumb). Unmapped rig bones (fingers, toe ends) keep their rest; Kimodo
|
|
19
|
+
has no fingers, so add finger poses in the consumer project. The check: every mapped bone's direction against
|
|
20
|
+
Kimodo's, on every frame (retarget) or on the pose (keypose).
|
|
21
|
+
"""
|
|
22
|
+
import json
|
|
23
|
+
import math
|
|
24
|
+
import os
|
|
25
|
+
import sys
|
|
26
|
+
|
|
27
|
+
import bpy
|
|
28
|
+
from mathutils import Matrix, Quaternion, Vector
|
|
29
|
+
|
|
30
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
31
|
+
import kimodo_motion as km # noqa: E402
|
|
32
|
+
|
|
33
|
+
DIRECTION_TOL_DEG = 3.0
|
|
34
|
+
FWD, SIDE, UP = Vector((0, -1, 0)), Vector((1, 0, 0)), Vector((0, 0, 1))
|
|
35
|
+
# rig bone (no prefix) -> (Kimodo joint, Kimodo child for the direction, rig child, side vector)
|
|
36
|
+
MAP = {
|
|
37
|
+
"Hips": ("Hips", "Spine1", "Spine", FWD),
|
|
38
|
+
"Spine": ("Spine1", "Spine2", "Spine1", FWD),
|
|
39
|
+
"Spine1": ("Spine2", "Chest", "Spine2", FWD),
|
|
40
|
+
"Spine2": ("Chest", "Neck1", "Neck", FWD),
|
|
41
|
+
"Neck": ("Neck1", "Head", "Head", FWD),
|
|
42
|
+
"Head": ("Head", None, None, FWD),
|
|
43
|
+
}
|
|
44
|
+
for _s in ("Left", "Right"):
|
|
45
|
+
MAP.update({
|
|
46
|
+
_s + "Shoulder": (_s + "Shoulder", _s + "Arm", _s + "Arm", FWD),
|
|
47
|
+
_s + "Arm": (_s + "Arm", _s + "ForeArm", _s + "ForeArm", FWD),
|
|
48
|
+
_s + "ForeArm": (_s + "ForeArm", _s + "Hand", _s + "Hand", FWD),
|
|
49
|
+
_s + "Hand": (_s + "Hand", _s + "HandMiddleEnd", _s + "HandMiddle1", "thumb"),
|
|
50
|
+
_s + "UpLeg": (_s + "Leg", _s + "Shin", _s + "Leg", FWD),
|
|
51
|
+
_s + "Leg": (_s + "Shin", _s + "Foot", _s + "Foot", FWD),
|
|
52
|
+
_s + "Foot": (_s + "Foot", _s + "ToeBase", _s + "ToeBase", SIDE),
|
|
53
|
+
_s + "ToeBase": (_s + "ToeBase", None, None, SIDE),
|
|
54
|
+
})
|
|
55
|
+
C = Quaternion((1, 0, 0), math.radians(90)) # Kimodo (Y up, +Z forward) into Blender (Z up, -Y forward)
|
|
56
|
+
PREFIX = "mixamorig:"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def pn(name):
|
|
60
|
+
return PREFIX + name
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def qk(q):
|
|
64
|
+
return Quaternion((q[3], q[0], q[1], q[2]))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def vk(v):
|
|
68
|
+
return C @ Vector(v)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def frame(primary, side):
|
|
72
|
+
y = primary.normalized()
|
|
73
|
+
z = side.cross(y).normalized()
|
|
74
|
+
x = y.cross(z)
|
|
75
|
+
return Matrix((x, y, z)).transposed().to_quaternion()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def rest_rot(b):
|
|
79
|
+
return b.matrix_local.to_quaternion()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def setup(rig):
|
|
83
|
+
"""Per mapped bone the alignment A (rig rest frame -> Kimodo rest frame)."""
|
|
84
|
+
bones = rig.data.bones
|
|
85
|
+
missing = [pn(n) for n in list(MAP) + [s + f for s in ("Left", "Right") for f in ("HandMiddle1", "HandThumb1")]
|
|
86
|
+
if pn(n) not in bones]
|
|
87
|
+
if missing:
|
|
88
|
+
raise SystemExit(f"FAIL rig lacks {missing} (prefix {PREFIX!r})")
|
|
89
|
+
rest_pos = km.fk(km.OFFSETS[0], [km.IDENTITY] * len(km.NAMES))[1]
|
|
90
|
+
align = {}
|
|
91
|
+
for hb, (kj, kc, hc, side) in MAP.items():
|
|
92
|
+
b = bones[pn(hb)]
|
|
93
|
+
if kc is None: # the head and the toes: up and forward
|
|
94
|
+
k1 = h1 = UP if hb == "Head" else FWD
|
|
95
|
+
k2 = h2 = FWD if hb == "Head" else UP
|
|
96
|
+
else:
|
|
97
|
+
k1 = vk(rest_pos[km.INDEX[kc]]) - vk(rest_pos[km.INDEX[kj]])
|
|
98
|
+
h1 = bones[pn(hc)].head_local - b.head_local
|
|
99
|
+
if side == "thumb":
|
|
100
|
+
k2 = vk(rest_pos[km.INDEX[hb + "ThumbEnd"]]) - vk(rest_pos[km.INDEX[kj]])
|
|
101
|
+
h2 = bones[pn(hb + "Thumb1")].head_local - b.head_local
|
|
102
|
+
k2, h2 = k2 - k2.project(k1), h2 - h2.project(h1)
|
|
103
|
+
else:
|
|
104
|
+
k2 = h2 = side
|
|
105
|
+
align[hb] = frame(k1, k2) @ frame(h1, h2).inverted()
|
|
106
|
+
return align
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def direction_worst(rig, kp):
|
|
110
|
+
"""Largest angle (deg) between a mapped rig bone's posed direction and Kimodo's, and that bone."""
|
|
111
|
+
worst = (0.0, "")
|
|
112
|
+
for short, (kj, kc, hc, _) in MAP.items():
|
|
113
|
+
if kc is not None:
|
|
114
|
+
h = rig.pose.bones[pn(hc)].head - rig.pose.bones[pn(short)].head
|
|
115
|
+
worst = max(worst, (math.degrees(h.angle(vk(kp[km.INDEX[kc]]) - vk(kp[km.INDEX[kj]]))), short))
|
|
116
|
+
return worst
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def kimodo_pose(rig, align):
|
|
120
|
+
"""The rig's current pose as Kimodo's root (metres, Y up) and local rotations (xyzw): mapped joints take their
|
|
121
|
+
rig bone's world turn through the alignment, the rest stay unturned against their parent. Returns (root, local,
|
|
122
|
+
the direction check)."""
|
|
123
|
+
bones = rig.data.bones
|
|
124
|
+
hips_scale = bones[pn("Hips")].head_local.z / km.OFFSETS[0][1]
|
|
125
|
+
rig_of = {kj: hb for hb, (kj, *_) in MAP.items()}
|
|
126
|
+
world = []
|
|
127
|
+
for j, name in enumerate(km.NAMES):
|
|
128
|
+
hb = rig_of.get(name)
|
|
129
|
+
if hb is None:
|
|
130
|
+
world.append(world[km.PARENTS[j]])
|
|
131
|
+
continue
|
|
132
|
+
w = rig.pose.bones[pn(hb)].matrix.to_quaternion()
|
|
133
|
+
world.append((C.inverted() @ w @ rest_rot(bones[pn(hb)]).inverted() @ align[hb].inverted() @ C).normalized())
|
|
134
|
+
local = []
|
|
135
|
+
for j, p in enumerate(km.PARENTS):
|
|
136
|
+
q = world[j] if p < 0 else world[p].inverted() @ world[j]
|
|
137
|
+
local.append((q.x, q.y, q.z, q.w))
|
|
138
|
+
root = tuple(C.inverted() @ (rig.pose.bones[pn("Hips")].head / hips_scale))
|
|
139
|
+
return root, local, direction_worst(rig, km.fk(root, local)[1])
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def load_action(path, name):
|
|
143
|
+
"""The first action of an action-only .blend."""
|
|
144
|
+
with bpy.data.libraries.load(path) as (src, dst):
|
|
145
|
+
dst.actions = src.actions[:1]
|
|
146
|
+
if not dst.actions:
|
|
147
|
+
raise SystemExit(f"FAIL no action in {path}")
|
|
148
|
+
dst.actions[0].name = name
|
|
149
|
+
return dst.actions[0]
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def apply(rig, act, frame_no):
|
|
153
|
+
rig.animation_data_create()
|
|
154
|
+
rig.animation_data.action = act
|
|
155
|
+
if hasattr(rig.animation_data, "action_slot") and act.slots:
|
|
156
|
+
rig.animation_data.action_slot = act.slots[0]
|
|
157
|
+
bpy.context.scene.frame_set(int(frame_no))
|
|
158
|
+
bpy.context.view_layer.update()
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def keypose_cmd(rig, specs, out, toe_y):
|
|
162
|
+
align = setup(rig)
|
|
163
|
+
result = {}
|
|
164
|
+
for spec in specs:
|
|
165
|
+
name, path = spec.split("=", 1)
|
|
166
|
+
path, _, at = path.partition("@")
|
|
167
|
+
act = load_action(os.path.abspath(path), name)
|
|
168
|
+
frame_no = int(at) if at else int(act.frame_range[0])
|
|
169
|
+
apply(rig, act, frame_no)
|
|
170
|
+
root, local, worst = kimodo_pose(rig, align)
|
|
171
|
+
pos = km.fk(root, local)[1]
|
|
172
|
+
shift = toe_y - min(pos[km.INDEX["LeftToeBase"]][1], pos[km.INDEX["RightToeBase"]][1])
|
|
173
|
+
result[name] = {"source": os.path.abspath(path), "frame": frame_no,
|
|
174
|
+
"root": [root[0], root[1] + shift, root[2]], "local_xyzw": [list(q) for q in local],
|
|
175
|
+
"ground_shift_m": round(shift, 4), "direction_worst_deg": round(worst[0], 2),
|
|
176
|
+
"direction_worst_bone": worst[1]}
|
|
177
|
+
print(f"KEYPOSE {name}: {path}@{frame_no} ground shift {shift * 1000:.0f} mm, direction worst {worst[0]:.2f} "
|
|
178
|
+
f"deg ({worst[1]})")
|
|
179
|
+
if worst[0] > DIRECTION_TOL_DEG:
|
|
180
|
+
raise SystemExit(f"FAIL keypose {name}: direction {worst[0]:.2f} deg > {DIRECTION_TOL_DEG}")
|
|
181
|
+
with open(out, "w") as fh:
|
|
182
|
+
json.dump({"_doc": "Kimodo key poses (SOMA30: root metres Y up, local xyzw)", "poses": result}, fh, indent=1)
|
|
183
|
+
print("POSES", out)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def bake(rig, name, motion_dir, align):
|
|
187
|
+
"""One motion as an action on the rig; returns it and the worst direction (deg, bone, frame)."""
|
|
188
|
+
roots, rots = km.load(motion_dir)
|
|
189
|
+
bones = rig.data.bones
|
|
190
|
+
hips_scale = bones[pn("Hips")].head_local.z / km.OFFSETS[0][1]
|
|
191
|
+
act = bpy.data.actions.new(name)
|
|
192
|
+
rig.animation_data_create()
|
|
193
|
+
rig.animation_data.action = act
|
|
194
|
+
for pb in rig.pose.bones:
|
|
195
|
+
pb.rotation_mode = "QUATERNION"
|
|
196
|
+
worst, last = (0.0, "", 0), {}
|
|
197
|
+
for f in range(len(roots)):
|
|
198
|
+
kw, kp = km.fk(roots[f], rots[f])
|
|
199
|
+
world = {}
|
|
200
|
+
for b in bones: # parents come before children in Blender's bone list
|
|
201
|
+
short = b.name[len(PREFIX):] if b.name.startswith(PREFIX) else b.name
|
|
202
|
+
parent = b.parent
|
|
203
|
+
rel = (rest_rot(parent).inverted() @ rest_rot(b)) if parent else rest_rot(b)
|
|
204
|
+
if short in MAP:
|
|
205
|
+
w = C @ qk(kw[km.INDEX[MAP[short][0]]]) @ C.inverted() @ align[short] @ rest_rot(b)
|
|
206
|
+
basis = rel.inverted() @ (world[parent.name].inverted() if parent else Quaternion()) @ w
|
|
207
|
+
else:
|
|
208
|
+
basis = Quaternion()
|
|
209
|
+
w = (world[parent.name] @ rel) if parent else rel
|
|
210
|
+
world[b.name] = w
|
|
211
|
+
basis = basis.normalized()
|
|
212
|
+
if b.name in last and last[b.name].dot(basis) < 0: # one hemisphere: no flips between keys
|
|
213
|
+
basis = -basis
|
|
214
|
+
last[b.name] = basis
|
|
215
|
+
pb = rig.pose.bones[b.name]
|
|
216
|
+
pb.rotation_quaternion = basis
|
|
217
|
+
pb.keyframe_insert("rotation_quaternion", frame=f + 1)
|
|
218
|
+
root = roots[f]
|
|
219
|
+
target = vk((root[0] - roots[0][0], root[1], root[2] - roots[0][2])) * hips_scale
|
|
220
|
+
hips = bones[pn("Hips")]
|
|
221
|
+
rig.pose.bones[hips.name].location = rest_rot(hips).inverted() @ (target - hips.head_local)
|
|
222
|
+
rig.pose.bones[hips.name].keyframe_insert("location", frame=f + 1)
|
|
223
|
+
bpy.context.scene.frame_set(f + 1)
|
|
224
|
+
angle, bone = direction_worst(rig, kp)
|
|
225
|
+
if angle > worst[0]:
|
|
226
|
+
worst = (angle, bone, f)
|
|
227
|
+
act.frame_range = (1, len(roots))
|
|
228
|
+
act.use_fake_user = True
|
|
229
|
+
return act, worst
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def retarget_cmd(rig, clips, out, report_path):
|
|
233
|
+
align = setup(rig)
|
|
234
|
+
report, failed = {}, []
|
|
235
|
+
for name, motion in clips:
|
|
236
|
+
act, worst = bake(rig, name, os.path.abspath(motion), align)
|
|
237
|
+
report[name] = {"motion": os.path.abspath(motion), "frames": round(act.frame_range[1]),
|
|
238
|
+
"direction_worst_deg": round(worst[0], 2), "direction_worst_bone": worst[1],
|
|
239
|
+
"direction_worst_frame": worst[2]}
|
|
240
|
+
print(f"DIRECTION {name}: worst {worst[0]:.2f} deg ({worst[1]}, frame {worst[2]})")
|
|
241
|
+
if worst[0] > DIRECTION_TOL_DEG:
|
|
242
|
+
failed.append(f"{name}: direction {worst[0]:.2f} > {DIRECTION_TOL_DEG}")
|
|
243
|
+
if report_path:
|
|
244
|
+
with open(report_path, "w") as fh:
|
|
245
|
+
json.dump(report, fh, indent=1)
|
|
246
|
+
if failed: # before the export: a failed bake never replaces an existing GLB
|
|
247
|
+
raise SystemExit("FAIL kimodo_retarget: " + "; ".join(failed))
|
|
248
|
+
rig.animation_data.action = bpy.data.actions[clips[0][0]]
|
|
249
|
+
bpy.ops.object.select_all(action="DESELECT")
|
|
250
|
+
rig.select_set(True)
|
|
251
|
+
bpy.context.view_layer.objects.active = rig
|
|
252
|
+
os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
|
|
253
|
+
bpy.ops.export_scene.gltf(filepath=os.path.abspath(out), export_format="GLB", use_selection=True,
|
|
254
|
+
export_animations=True, export_animation_mode="ACTIONS", export_force_sampling=True,
|
|
255
|
+
export_skins=True, export_yup=True)
|
|
256
|
+
print("PASS kimodo_retarget:", out, [n for n, _ in clips])
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def main():
|
|
260
|
+
global PREFIX
|
|
261
|
+
argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
|
|
262
|
+
PREFIX = km.flag(argv, "--prefix", PREFIX)
|
|
263
|
+
rigs = [o for o in bpy.data.objects if o.type == "ARMATURE"]
|
|
264
|
+
if len(rigs) != 1:
|
|
265
|
+
raise SystemExit(f"FAIL expected one armature, found {len(rigs)}")
|
|
266
|
+
rig = rigs[0]
|
|
267
|
+
values = ("--out", "--report", "--prefix", "--toe-y", "--clip")
|
|
268
|
+
positional = [a for i, a in enumerate(argv[1:], 1) if not a.startswith("--") and argv[i - 1] not in values]
|
|
269
|
+
if argv and argv[0] == "keypose":
|
|
270
|
+
keypose_cmd(rig, positional, km.flag(argv, "--out"), float(km.flag(argv, "--toe-y", km.TOE_Y)))
|
|
271
|
+
elif argv and argv[0] == "retarget":
|
|
272
|
+
clips = [a.split("=", 1) for i, a in enumerate(argv) if i and argv[i - 1] == "--clip"]
|
|
273
|
+
retarget_cmd(rig, clips, km.flag(argv, "--out"), km.flag(argv, "--report"))
|
|
274
|
+
else:
|
|
275
|
+
print(__doc__)
|
|
276
|
+
raise SystemExit(2)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
if __name__ == "__main__":
|
|
280
|
+
main()
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Blender check for kimodo_retarget.py (run by test_kimodo_motion.py): a synthetic Mixamo-named rig with its own
|
|
2
|
+
proportions and bone rolls, a random pose, kimodo_pose (rig -> Kimodo) then bake (Kimodo -> rig) must give back every
|
|
3
|
+
mapped bone's world turn and the hips' height.
|
|
4
|
+
|
|
5
|
+
blender -b --factory-startup --python-exit-code 1 --python blender_roundtrip.py
|
|
6
|
+
"""
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import random
|
|
10
|
+
import sys
|
|
11
|
+
import tempfile
|
|
12
|
+
|
|
13
|
+
import bpy
|
|
14
|
+
from mathutils import Quaternion, Vector
|
|
15
|
+
|
|
16
|
+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "scripts"))
|
|
17
|
+
import kimodo_motion as km # noqa: E402
|
|
18
|
+
import kimodo_retarget as kr # noqa: E402
|
|
19
|
+
|
|
20
|
+
rng = random.Random(3)
|
|
21
|
+
SCALE = 1.08 # a taller rig than Kimodo's body
|
|
22
|
+
RIG_OF = {kj: hb for hb, (kj, *_) in kr.MAP.items()}
|
|
23
|
+
EXTRA = {} # rig-only bones: name -> (Kimodo joint for the head, parent rig bone)
|
|
24
|
+
for s in ("Left", "Right"):
|
|
25
|
+
EXTRA[s + "HandMiddle1"] = (s + "HandMiddleEnd", s + "Hand")
|
|
26
|
+
EXTRA[s + "HandThumb1"] = (s + "HandThumbEnd", s + "Hand")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def build_rig():
|
|
30
|
+
rest = km.fk(km.OFFSETS[0], [km.IDENTITY] * len(km.NAMES))[1]
|
|
31
|
+
head = {}
|
|
32
|
+
for kj, hb in RIG_OF.items():
|
|
33
|
+
head[hb] = kr.vk(rest[km.INDEX[kj]]) * SCALE + Vector([rng.uniform(-0.01, 0.01) for _ in range(3)])
|
|
34
|
+
for name, (kj, _) in EXTRA.items():
|
|
35
|
+
head[name] = kr.vk(rest[km.INDEX[kj]]) * SCALE
|
|
36
|
+
parent = {}
|
|
37
|
+
for kj, hb in RIG_OF.items():
|
|
38
|
+
p = km.PARENTS[km.INDEX[kj]]
|
|
39
|
+
while p >= 0 and km.NAMES[p] not in RIG_OF: # Neck2 has no rig bone
|
|
40
|
+
p = km.PARENTS[p]
|
|
41
|
+
parent[hb] = RIG_OF[km.NAMES[p]] if p >= 0 else None
|
|
42
|
+
parent.update({n: p for n, (_, p) in EXTRA.items()})
|
|
43
|
+
children = {}
|
|
44
|
+
for b, p in parent.items():
|
|
45
|
+
children.setdefault(p, []).append(b)
|
|
46
|
+
arm = bpy.data.armatures.new("rig")
|
|
47
|
+
rig = bpy.data.objects.new("rig", arm)
|
|
48
|
+
bpy.context.scene.collection.objects.link(rig)
|
|
49
|
+
bpy.context.view_layer.objects.active = rig
|
|
50
|
+
bpy.ops.object.mode_set(mode="EDIT")
|
|
51
|
+
made = {}
|
|
52
|
+
order, todo = [], [b for b, p in parent.items() if p is None]
|
|
53
|
+
while todo:
|
|
54
|
+
b = todo.pop(0)
|
|
55
|
+
order.append(b)
|
|
56
|
+
todo += sorted(children.get(b, []))
|
|
57
|
+
for b in order:
|
|
58
|
+
eb = arm.edit_bones.new(kr.pn(b))
|
|
59
|
+
eb.head = head[b]
|
|
60
|
+
kids = [c for c in children.get(b, []) if c not in EXTRA or b.endswith("Hand")]
|
|
61
|
+
tail = sum((head[c] for c in kids), Vector()) / len(kids) if kids else head[b] + Vector((0, -0.05, 0.02))
|
|
62
|
+
eb.tail = tail if (tail - eb.head).length > 1e-3 else eb.head + Vector((0, 0, 0.05))
|
|
63
|
+
eb.roll = rng.uniform(-math.pi, math.pi)
|
|
64
|
+
if parent[b]:
|
|
65
|
+
eb.parent = made[parent[b]]
|
|
66
|
+
made[b] = eb
|
|
67
|
+
bpy.ops.object.mode_set(mode="POSE")
|
|
68
|
+
return rig
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def main():
|
|
72
|
+
rig = build_rig()
|
|
73
|
+
for pb in rig.pose.bones:
|
|
74
|
+
pb.rotation_mode = "QUATERNION"
|
|
75
|
+
name = pb.name[len(kr.PREFIX):]
|
|
76
|
+
if name in kr.MAP and name not in ("Head", "LeftToeBase", "RightToeBase"):
|
|
77
|
+
axis = Vector([rng.uniform(-1, 1) for _ in range(3)]).normalized()
|
|
78
|
+
pb.rotation_quaternion = Quaternion(axis, rng.uniform(0.1, 0.6))
|
|
79
|
+
rig.pose.bones[kr.pn("Hips")].location = Vector((0, 0.05, 0)) # bone-local: a lift or drop of the hips
|
|
80
|
+
bpy.context.view_layer.update()
|
|
81
|
+
want = {pb.name: pb.matrix.to_quaternion() for pb in rig.pose.bones}
|
|
82
|
+
hips_z = rig.pose.bones[kr.pn("Hips")].head.z
|
|
83
|
+
align = kr.setup(rig)
|
|
84
|
+
root, local, worst = kr.kimodo_pose(rig, align)
|
|
85
|
+
assert worst[0] < 0.5, f"direction on the pose {worst}"
|
|
86
|
+
d = tempfile.mkdtemp()
|
|
87
|
+
km.save(d, [root, root], [local, local])
|
|
88
|
+
for pb in rig.pose.bones:
|
|
89
|
+
pb.rotation_quaternion = Quaternion()
|
|
90
|
+
pb.location = Vector()
|
|
91
|
+
act, worst = kr.bake(rig, "trip", d, align)
|
|
92
|
+
assert worst[0] < 0.5, f"direction after bake {worst}"
|
|
93
|
+
bpy.context.scene.frame_set(1)
|
|
94
|
+
bpy.context.view_layer.update()
|
|
95
|
+
turn = max((math.degrees(want[pb.name].rotation_difference(pb.matrix.to_quaternion()).angle), pb.name)
|
|
96
|
+
for pb in rig.pose.bones if pb.name[len(kr.PREFIX):] in kr.MAP)
|
|
97
|
+
turn = (min(turn[0], 360 - turn[0]), turn[1])
|
|
98
|
+
height = abs(rig.pose.bones[kr.pn("Hips")].head.z - hips_z)
|
|
99
|
+
print(f"ROUNDTRIP worst bone turn {turn[0]:.4f} deg ({turn[1]}), hips height {height * 1000:.2f} mm")
|
|
100
|
+
assert turn[0] < 0.1, turn
|
|
101
|
+
assert height < 0.001, height
|
|
102
|
+
print("PASS blender_roundtrip")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
main()
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""kimodo_motion.py without the model; the Blender round trip runs when BLENDER (or `blender`) is available.
|
|
2
|
+
|
|
3
|
+
python3 -m unittest discover -s <skill>/tests -v
|
|
4
|
+
"""
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import random
|
|
9
|
+
import shutil
|
|
10
|
+
import struct
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import tempfile
|
|
14
|
+
import unittest
|
|
15
|
+
|
|
16
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
17
|
+
SCRIPTS = os.path.join(HERE, "..", "scripts")
|
|
18
|
+
sys.path.insert(0, SCRIPTS)
|
|
19
|
+
import kimodo_motion as km # noqa: E402
|
|
20
|
+
|
|
21
|
+
J = len(km.NAMES)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def rand_q(rng, scale):
|
|
25
|
+
return km.quat([rng.uniform(-scale, scale) for _ in range(3)])
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def motion(rng, n, drift):
|
|
29
|
+
"""A smooth synthetic take: every joint turning slowly, the root walking."""
|
|
30
|
+
base = [rand_q(rng, 0.4) for _ in range(J)]
|
|
31
|
+
rate = [[rng.uniform(-drift, drift) for _ in range(3)] for _ in range(J)]
|
|
32
|
+
roots = [(0.01 * t, 0.95, 0.005 * t) for t in range(n)]
|
|
33
|
+
rots = [[km.qmul(km.quat([r * t for r in rate[j]]), base[j]) for j in range(J)] for t in range(n)]
|
|
34
|
+
return roots, rots
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def positions(roots, rots):
|
|
38
|
+
return [km.fk(r, q)[1] for r, q in zip(roots, rots)]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def largest_step(pos):
|
|
42
|
+
return max(max(math.dist(a, b) for a, b in zip(pos[t], pos[t + 1])) for t in range(len(pos) - 1))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def pose_off(key, pos):
|
|
46
|
+
return max(math.dist(a, b) for a, b in zip(km.fk(*key)[1], pos))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class KimodoMotion(unittest.TestCase):
|
|
50
|
+
def setUp(self):
|
|
51
|
+
self.rng = random.Random(7)
|
|
52
|
+
self.tmp = tempfile.mkdtemp()
|
|
53
|
+
|
|
54
|
+
def tearDown(self):
|
|
55
|
+
shutil.rmtree(self.tmp)
|
|
56
|
+
|
|
57
|
+
def test_skeleton_and_rotations(self):
|
|
58
|
+
self.assertEqual((len(km.NAMES), len(km.PARENTS), len(km.OFFSETS)), (30, 30, 30))
|
|
59
|
+
self.assertTrue(all(p < j for j, p in enumerate(km.PARENTS)))
|
|
60
|
+
for _ in range(20):
|
|
61
|
+
q = rand_q(self.rng, 2.0)
|
|
62
|
+
self.assertLess(km.qangle(q, km.quat(km.axis_angle(q))), 1e-4)
|
|
63
|
+
rest = km.fk(km.OFFSETS[0], [km.IDENTITY] * J)[1]
|
|
64
|
+
self.assertAlmostEqual(rest[km.INDEX["Hips"]][1], 0.988)
|
|
65
|
+
self.assertGreater(rest[km.INDEX["LeftHand"]][0], 0.5) # the left side is +X
|
|
66
|
+
|
|
67
|
+
def test_constraints_json(self):
|
|
68
|
+
pose = {"root": [0.3, 1.0, -0.2], "local_xyzw": [list(rand_q(self.rng, 0.3)) for _ in range(J)]}
|
|
69
|
+
c = km.constraints([(0, pose), (1, pose), (74, pose)])
|
|
70
|
+
self.assertEqual([e["type"] for e in c], ["fullbody", "end-effector"])
|
|
71
|
+
self.assertEqual(c[1]["joint_names"], km.EFFECTORS)
|
|
72
|
+
self.assertEqual(c[0]["frame_indices"], [0, 1, 74])
|
|
73
|
+
self.assertEqual(c[0]["root_positions"][0], [0.0, 1.0, 0.0])
|
|
74
|
+
self.assertEqual(len(c[0]["local_joints_rot"][0]), J)
|
|
75
|
+
self.assertEqual([e["type"] for e in km.constraints([(0, pose)], effectors=[])], ["fullbody"])
|
|
76
|
+
|
|
77
|
+
def test_ease_exact_and_untouched_outside(self):
|
|
78
|
+
roots, rots = motion(self.rng, 75, 0.01)
|
|
79
|
+
keys = {f: (tuple(x + 0.03 for x in roots[f]), [km.qmul(rand_q(self.rng, 0.4), q) for q in rots[f]])
|
|
80
|
+
for f in (0, 1, 2, 72, 73, 74)}
|
|
81
|
+
er, eq = [tuple(r) for r in roots], [list(q) for q in rots]
|
|
82
|
+
km.ease_onto(er, eq, keys, 9)
|
|
83
|
+
got = positions(er, eq)
|
|
84
|
+
for f, key in keys.items():
|
|
85
|
+
self.assertLess(pose_off(key, got[f]), 1e-6, f)
|
|
86
|
+
for t in range(2 + 9, 72 - 9 + 1):
|
|
87
|
+
self.assertEqual((tuple(er[t]), list(eq[t])), (tuple(roots[t]), list(rots[t])), t)
|
|
88
|
+
|
|
89
|
+
def test_ease_overlapping_windows_continuous(self):
|
|
90
|
+
# keys 6 frames apart with a 9-frame window: a nearest-key rule snapped mid-gap (a step of ~the residual)
|
|
91
|
+
roots, rots = motion(self.rng, 15, 0.01)
|
|
92
|
+
keys = {f: (tuple(x + 0.05 * (1 if f else -1) for x in roots[f]), [km.qmul(rand_q(self.rng, 0.5), q) for q in rots[f]])
|
|
93
|
+
for f in (4, 10)}
|
|
94
|
+
er, eq = [tuple(r) for r in roots], [list(q) for q in rots]
|
|
95
|
+
km.ease_onto(er, eq, keys, 9)
|
|
96
|
+
eased, raw = positions(er, eq), positions(roots, rots)
|
|
97
|
+
residual = max(pose_off(keys[f], raw[f]) for f in keys)
|
|
98
|
+
self.assertLess(largest_step(eased), largest_step(raw) + residual / 3)
|
|
99
|
+
for f, key in keys.items():
|
|
100
|
+
self.assertLess(pose_off(key, eased[f]), 1e-6)
|
|
101
|
+
|
|
102
|
+
def write(self, roots, rots, cons):
|
|
103
|
+
km.save(self.tmp, roots, rots)
|
|
104
|
+
with open(os.path.join(self.tmp, "constraints.json"), "w") as fh:
|
|
105
|
+
json.dump(cons, fh)
|
|
106
|
+
|
|
107
|
+
def test_check_known_good_and_known_bad(self):
|
|
108
|
+
roots, rots = motion(self.rng, 75, 0.02)
|
|
109
|
+
pose_a = {"root": list(roots[0]), "local_xyzw": [list(q) for q in rots[0]]}
|
|
110
|
+
pose_b = {"root": list(roots[74]), "local_xyzw": [list(q) for q in rots[74]]}
|
|
111
|
+
cons = km.constraints([(0, pose_a), (74, pose_b)])
|
|
112
|
+
shifted = [(r[0] - roots[0][0], r[1], r[2] - roots[0][2]) for r in roots]
|
|
113
|
+
self.write(shifted, rots, cons)
|
|
114
|
+
ok, report = km.check(self.tmp)
|
|
115
|
+
self.assertTrue(ok, report)
|
|
116
|
+
other_roots, other = motion(self.rng, 75, 0.02)
|
|
117
|
+
self.write(other_roots, other, cons)
|
|
118
|
+
self.assertFalse(km.check(self.tmp)[0])
|
|
119
|
+
# one frame keyed twice (overlapping holds), the violated key listed first: it still fails
|
|
120
|
+
cons = km.constraints([(0, pose_a), (0, pose_b)])
|
|
121
|
+
for e in cons:
|
|
122
|
+
for f in ("frame_indices", "root_positions", "local_joints_rot"):
|
|
123
|
+
e[f] = e[f][::-1] # a copy: the two entries share their lists
|
|
124
|
+
self.write(shifted, rots, cons)
|
|
125
|
+
self.assertFalse(km.check(self.tmp)[0])
|
|
126
|
+
|
|
127
|
+
def test_post_keeps_raw_and_lands_on_keys(self):
|
|
128
|
+
roots, rots = motion(self.rng, 40, 0.01)
|
|
129
|
+
pose = {"root": [0.0, 0.97, 0.0], "local_xyzw": [list(rand_q(self.rng, 0.2)) for _ in range(J)]}
|
|
130
|
+
self.write(roots, rots, km.constraints([(f, pose) for f in (0, 1, 2)]))
|
|
131
|
+
before = [km.read(os.path.join(self.tmp, f), "rb") for f in ("root_positions.f32", "local_rotations_xyzw.f32")]
|
|
132
|
+
moved = km.post(self.tmp, 0.3)
|
|
133
|
+
self.assertGreater(moved, 0)
|
|
134
|
+
after = [km.read(os.path.join(self.tmp, "raw", f), "rb") for f in ("root_positions.f32", "local_rotations_xyzw.f32")]
|
|
135
|
+
self.assertEqual(before, after) # the model's take is kept untouched in raw/
|
|
136
|
+
self.assertTrue(km.check(self.tmp)[0])
|
|
137
|
+
|
|
138
|
+
def test_generate_refuses_overlapping_holds(self):
|
|
139
|
+
saved, km.KIMODO_ROOT = km.KIMODO_ROOT, self.tmp
|
|
140
|
+
try:
|
|
141
|
+
with self.assertRaises(SystemExit) as e:
|
|
142
|
+
km.generate("x", self.tmp, "never", [1], 4, "a.json:p", "b.json:p", hold=3)
|
|
143
|
+
finally:
|
|
144
|
+
km.KIMODO_ROOT = saved
|
|
145
|
+
self.assertIn("cannot hold", str(e.exception))
|
|
146
|
+
|
|
147
|
+
def test_check_model_gate_cli(self):
|
|
148
|
+
# the model gate reads raw/ beside the take: a take without keys (known-bad) fails it, the keyed one passes
|
|
149
|
+
roots, rots = motion(self.rng, 30, 0.02)
|
|
150
|
+
pose = {"root": list(roots[0]), "local_xyzw": [list(q) for q in rots[0]]}
|
|
151
|
+
self.write([(r[0] - roots[0][0], r[1], r[2] - roots[0][2]) for r in roots], rots, km.constraints([(0, pose)]))
|
|
152
|
+
os.makedirs(os.path.join(self.tmp, "raw"))
|
|
153
|
+
km.save(os.path.join(self.tmp, "raw"), *motion(self.rng, 30, 0.02))
|
|
154
|
+
cons = os.path.join(self.tmp, "constraints.json")
|
|
155
|
+
self.assertEqual(km.main(["check", self.tmp, "--model"]), 1)
|
|
156
|
+
km.save(os.path.join(self.tmp, "raw"), *km.load(self.tmp))
|
|
157
|
+
self.assertEqual(km.main(["check", self.tmp, "--model", "--constraints", cons]), 0)
|
|
158
|
+
|
|
159
|
+
def test_sheet_renders(self):
|
|
160
|
+
try:
|
|
161
|
+
import PIL # noqa: F401
|
|
162
|
+
except ImportError:
|
|
163
|
+
self.skipTest("Pillow not installed")
|
|
164
|
+
roots, rots = motion(self.rng, 20, 0.01)
|
|
165
|
+
pose = {"root": list(roots[0]), "local_xyzw": [list(q) for q in rots[0]]}
|
|
166
|
+
self.write(roots, rots, km.constraints([(0, pose)]))
|
|
167
|
+
out = os.path.join(self.tmp, "sheet.png")
|
|
168
|
+
km.sheet([self.tmp], out, span=(0, 5))
|
|
169
|
+
self.assertGreater(os.path.getsize(out), 1000)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@unittest.skipUnless(shutil.which(os.environ.get("BLENDER", "blender")), "Blender not found (set BLENDER)")
|
|
173
|
+
class BlenderRoundTrip(unittest.TestCase):
|
|
174
|
+
def test_pose_to_keypose_to_rig(self):
|
|
175
|
+
blender = shutil.which(os.environ.get("BLENDER", "blender"))
|
|
176
|
+
run = subprocess.run([blender, "-b", "--factory-startup", "--python-exit-code", "1", "--python",
|
|
177
|
+
os.path.join(HERE, "blender_roundtrip.py")], capture_output=True, text=True, timeout=600)
|
|
178
|
+
self.assertEqual(run.returncode, 0, run.stdout[-3000:] + run.stderr[-3000:])
|
|
179
|
+
self.assertIn("PASS blender_roundtrip", run.stdout)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
if __name__ == "__main__":
|
|
183
|
+
unittest.main()
|