sidrefresh's picture
Add files using upload-large-folder tool
92f480e verified
Raw History Blame Contribute Delete
12.3 kB
"""Dump the grading-relevant facts of a rigging .blend as JSON. Runs INSIDE Blender:
blender -b <file.blend> -Y --python inspect_blend.py -- <out.json>
(the verifier calls it; the agent never has a Python path into Blender.)
Per armature: transform and display settings, every bone (parent, connected,
deform flag, world-space head/tail, colour palette, bone collections), the
bone collections (visibility, members), every pose bone (custom shape and its
transform, pose colour, constraints with the settings the tutorial touches:
IK target / pole / chain length / pole angle, Copy Location head-tail), the
action's F-curves (keyed frames, interpolation), the world-space head of every
bone sampled at the walk-cycle frames, and how far each bone sits from its
rest position when the pose is cleared and the action detached (an IK setup
whose pole angle is wrong flips the leg — that shows up here).
Per mesh: armature modifiers, vertex groups with a count of weighted vertices,
mirror settings, parent, world bounding box. Plus scene-level facts: frame
range, auto-normalize, collections and their visibility, object names and
modes, workspaces.
Everything is best-effort: a failure in one section leaves that section
absent rather than aborting the dump.
"""
import json
import math
import sys
import bpy
from mathutils import Vector
out_path = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else "/tmp/inspect.json"
R = {"file": bpy.data.filepath, "blender_version": bpy.app.version_string, "armatures": [], "meshes": [], "errors": []}
WALK_FRAMES = [1, 4, 7, 10, 13, 16, 19, 22, 25]
def safe(section, fn, *a):
try:
return fn(*a)
except Exception as e: # noqa: BLE001
R["errors"].append(f"{section}: {e!r}")
return None
def v3(v):
return [float(v[0]), float(v[1]), float(v[2])]
def bbox(points):
if not points:
return None
xs = [p.x for p in points]; ys = [p.y for p in points]; zs = [p.z for p in points]
return {"min": [min(xs), min(ys), min(zs)], "max": [max(xs), max(ys), max(zs)],
"dim": [max(xs) - min(xs), max(ys) - min(ys), max(zs) - min(zs)],
"center": [(max(xs) + min(xs)) / 2, (max(ys) + min(ys)) / 2, (max(zs) + min(zs)) / 2]}
def action_fcurves(action):
"""F-curves of an action across the legacy and the slotted (4.4+) APIs."""
fcs = []
try:
fcs = list(action.fcurves)
except Exception: # noqa: BLE001
fcs = []
if not fcs:
try:
for layer in action.layers:
for strip in layer.strips:
for cb in strip.channelbags:
fcs.extend(list(cb.fcurves))
except Exception: # noqa: BLE001
pass
return fcs
def constraint_info(c):
d = {"type": c.type, "name": c.name, "mute": c.mute, "influence": c.influence, "enabled": getattr(c, "enabled", None)}
for attr in ("target", "pole_target"):
t = getattr(c, attr, None)
d[attr] = t.name if t else None
for attr in ("subtarget", "pole_subtarget", "chain_count", "head_tail", "use_tail", "iterations", "use_offset", "use_bbone_shape"):
if hasattr(c, attr):
d[attr] = getattr(c, attr)
if hasattr(c, "pole_angle"):
d["pole_angle_deg"] = math.degrees(c.pole_angle)
return d
def bone_color(col):
try:
return {"palette": col.palette, "is_custom": col.is_custom}
except Exception: # noqa: BLE001
return None
def armature_info(ob):
arm = ob.data
M = ob.matrix_world
d = {"name": ob.name, "data_name": arm.name, "location": v3(ob.location),
"rotation_deg": [math.degrees(a) for a in ob.rotation_euler], "scale": v3(ob.scale),
"show_in_front": ob.show_in_front, "display_type": arm.display_type, "pose_position": arm.pose_position,
"mode": ob.mode, "parent": ob.parent.name if ob.parent else None,
"collections": [c.name for c in ob.users_collection], "bones": [], "bone_collections": [], "pose_bones": []}
for b in arm.bones:
bd = {"name": b.name, "parent": b.parent.name if b.parent else None, "use_connect": b.use_connect,
"use_deform": b.use_deform, "head": v3(M @ b.head_local), "tail": v3(M @ b.tail_local),
"length": float(b.length), "hide": b.hide, "inherit_rotation": b.use_inherit_rotation,
"children": [c.name for c in b.children], "color": bone_color(b.color),
"collections": [c.name for c in b.collections]}
d["bones"].append(bd)
try:
colls = list(arm.collections_all)
except Exception: # noqa: BLE001
colls = list(arm.collections)
for c in colls:
d["bone_collections"].append({"name": c.name, "is_visible": c.is_visible, "is_solo": getattr(c, "is_solo", None),
"parent": c.parent.name if getattr(c, "parent", None) else None,
"bones": [b.name for b in c.bones]})
for pb in ob.pose.bones:
pd = {"name": pb.name, "custom_shape": pb.custom_shape.name if pb.custom_shape else None,
"custom_shape_scale": v3(pb.custom_shape_scale_xyz), "custom_shape_rotation_deg": [math.degrees(a) for a in pb.custom_shape_rotation_euler],
"custom_shape_translation": v3(pb.custom_shape_translation), "color": bone_color(pb.color),
"rotation_mode": pb.rotation_mode, "location": v3(pb.location),
"constraints": [constraint_info(c) for c in pb.constraints]}
d["pose_bones"].append(pd)
# animation
ad = ob.animation_data
d["animation"] = None
if ad and ad.action:
act = ad.action
fcs = action_fcurves(act)
curves = []
keyed_frames = set()
bones_keyed = set()
for fc in fcs:
frames = [float(k.co[0]) for k in fc.keyframe_points]
interp = sorted({k.interpolation for k in fc.keyframe_points})
curves.append({"data_path": fc.data_path, "index": fc.array_index, "frames": frames, "interpolation": interp})
keyed_frames.update(round(f) for f in frames)
if fc.data_path.startswith('pose.bones["'):
bones_keyed.add(fc.data_path.split('"')[1])
d["animation"] = {"action": act.name, "frame_range": [float(x) for x in act.frame_range], "n_fcurves": len(fcs),
"keyed_frames": sorted(keyed_frames), "bones_keyed": sorted(bones_keyed), "fcurves": curves}
return d
def sample_poses(ob, frames):
"""world-space head of every bone at each frame (animation evaluated)."""
scene = bpy.context.scene
out = {}
cur = scene.frame_current
for f in frames:
scene.frame_set(int(f))
bpy.context.view_layer.update()
M = ob.matrix_world
out[str(int(f))] = {pb.name: v3(M @ pb.head) for pb in ob.pose.bones}
out[str(int(f))]["__tails__"] = {pb.name: v3(M @ pb.tail) for pb in ob.pose.bones}
scene.frame_set(cur)
return out
def rest_deviation(ob):
"""clear every pose transform and detach the action, then measure how far
each bone's evaluated head/tail sit from rest (constraints still act)."""
ad = ob.animation_data
if ad and ad.action:
ad.action = None
for pb in ob.pose.bones:
pb.location = (0, 0, 0)
pb.rotation_quaternion = (1, 0, 0, 0)
pb.rotation_euler = (0, 0, 0)
pb.rotation_axis_angle = (0, 0, 1, 0)
pb.scale = (1, 1, 1)
bpy.context.view_layer.update()
M = ob.matrix_world
dev = {}
for pb in ob.pose.bones:
b = pb.bone
dh = ((M @ pb.head) - (M @ b.head_local)).length
dt = ((M @ pb.tail) - (M @ b.tail_local)).length
dev[pb.name] = {"head": dh, "tail": dt}
return dev
def mesh_info(ob):
me = ob.data
M = ob.matrix_world
pts = [M @ v.co for v in me.vertices]
groups = []
counts = {g.index: 0 for g in ob.vertex_groups}
for v in me.vertices:
for g in v.groups:
if g.weight > 0.01 and g.group in counts:
counts[g.group] += 1
for g in ob.vertex_groups:
groups.append({"name": g.name, "weighted_verts": counts.get(g.index, 0)})
mods = []
for m in ob.modifiers:
md = {"type": m.type, "name": m.name, "show_viewport": m.show_viewport}
if m.type == "ARMATURE":
md.update(object=m.object.name if m.object else None, vertex_group=m.vertex_group,
use_vertex_groups=m.use_vertex_groups, use_deform_preserve_volume=m.use_deform_preserve_volume)
mods.append(md)
return {"name": ob.name, "verts": len(me.vertices), "faces": len(me.polygons), "edges": len(me.edges),
"parent": ob.parent.name if ob.parent else None, "parent_type": ob.parent_type,
"location": v3(ob.location), "rotation_deg": [math.degrees(a) for a in ob.rotation_euler], "scale": v3(ob.scale),
"dimensions": v3(ob.dimensions), "bbox": bbox(pts), "modifiers": mods, "vertex_groups": groups,
"use_mirror_x": me.use_mirror_x, "use_mirror_vertex_groups": me.use_mirror_vertex_groups,
"hide_viewport": ob.hide_viewport, "hide_render": ob.hide_render, "mode": ob.mode,
"collections": [c.name for c in ob.users_collection]}
scene = bpy.context.scene
objects = list(bpy.data.objects)
R["object_names"] = [(o.name, o.type) for o in objects]
R["workspaces"] = [w.name for w in bpy.data.workspaces]
try:
ts = scene.tool_settings
wp = None
try:
br = ts.weight_paint.brush
wp = {"brush": br.name if br else None, "blend": br.blend if br else None, "strength": br.strength if br else None}
except Exception: # noqa: BLE001
pass
R["scene"] = {"frame_start": scene.frame_start, "frame_end": scene.frame_end, "frame_current": scene.frame_current,
"fps": scene.render.fps, "use_auto_normalize": ts.use_auto_normalize,
"vertex_group_user": getattr(ts, "vertex_group_user", None), "weight_paint": wp,
"cursor": v3(scene.cursor.location), "camera": scene.camera.name if scene.camera else None}
except Exception as e: # noqa: BLE001
R["errors"].append(f"scene: {e!r}")
try:
def layer_flags(lc, acc):
acc[lc.name] = {"exclude": lc.exclude, "hide_viewport": lc.hide_viewport}
for ch in lc.children:
layer_flags(ch, acc)
return acc
lf = layer_flags(bpy.context.view_layer.layer_collection, {})
R["collections"] = [{"name": c.name, "hide_viewport": c.hide_viewport, "hide_render": c.hide_render,
"objects": [o.name for o in c.objects], "layer": lf.get(c.name)} for c in bpy.data.collections]
except Exception as e: # noqa: BLE001
R["errors"].append(f"collections: {e!r}")
try:
wins = bpy.data.window_managers[0].windows
R["active_workspaces"] = [w.workspace.name for w in wins if w.workspace]
R["screen_areas"] = sorted({a.type for w in wins for a in w.screen.areas})
except Exception as e: # noqa: BLE001
R["errors"].append(f"windows: {e!r}")
for ob in objects:
if ob.type == "MESH":
mi = safe(f"mesh:{ob.name}", mesh_info, ob)
if mi:
R["meshes"].append(mi)
for ob in objects:
if ob.type != "ARMATURE":
continue
ai = safe(f"armature:{ob.name}", armature_info, ob)
if not ai:
continue
frames = set(WALK_FRAMES) | {scene.frame_start, scene.frame_end}
if ai.get("animation"):
kf = ai["animation"]["keyed_frames"]
frames |= set(kf[:60])
if kf:
frames |= {kf[0], kf[-1]}
ai["samples"] = safe(f"samples:{ob.name}", sample_poses, ob, sorted(frames))
R["armatures"].append(ai)
# last: destructive (clears the pose and detaches the action; the file is never saved)
for ob in objects:
if ob.type != "ARMATURE":
continue
for ai in R["armatures"]:
if ai["name"] == ob.name:
ai["rest_deviation"] = safe(f"restdev:{ob.name}", rest_deviation, ob)
with open(out_path, "w") as f:
json.dump(R, f, indent=1, default=str)
print(f"inspect_blend: wrote {out_path} ({len(R['armatures'])} armatures, {len(R['meshes'])} meshes, {len(R['errors'])} errors)")