File size: 12,270 Bytes
92f480e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"""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)")