sidrefresh's picture
Add files using upload-large-folder tool
7ec48b5 verified
Raw History Blame Contribute Delete
18.4 kB
"""Dump the grading-relevant facts of a .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 mesh object: transform, base-mesh topology (counts, boundary edges and
loops, Euler characteristic, quad fraction, smooth-shading fraction), world
bounding boxes for the base and the evaluated (modifiers applied) mesh, the
modifier stack with the settings the tutorial touches, edge-crease presence,
a z-profile of the mesh (radius per height bin, for the mug's taper and lip)
and an angular profile (lowest z per sector, for the icing's wavy rim and
drips). Torus parameters (centre, major/minor radius) are fitted to the
object named like the donut so the icing's distance to the donut surface can
be measured. Plus scene-level facts: object names/types, images, workspaces,
the saved active workspace and object modes.
Everything is best-effort: a failure in one section leaves that section
absent rather than aborting the dump.
"""
import json
import math
import sys
from collections import defaultdict
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, "objects": [], "errors": []}
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 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 topology(me):
V, E, F = len(me.vertices), len(me.edges), len(me.polygons)
edge_face = defaultdict(int)
quads = 0
for p in me.polygons:
if len(p.vertices) == 4:
quads += 1
for ek in p.edge_keys:
edge_face[ek] += 1
boundary = [ek for ek, n in edge_face.items() if n == 1]
nonmanifold = sum(1 for n in edge_face.values() if n > 2)
# boundary loops = connected components of the boundary edge graph
adj = defaultdict(list)
for a, b in boundary:
adj[a].append(b); adj[b].append(a)
seen, loops = set(), 0
for v0 in adj:
if v0 in seen:
continue
loops += 1
stack = [v0]
while stack:
v = stack.pop()
if v in seen:
continue
seen.add(v)
stack.extend(adj[v])
chi = V - E + F
# connected components of the mesh itself
vadj = defaultdict(list)
for e in me.edges:
a, b = e.vertices
vadj[a].append(b); vadj[b].append(a)
seen, comps = set(), 0
for v0 in range(V):
if v0 in seen:
continue
comps += 1
stack = [v0]
while stack:
v = stack.pop()
if v in seen:
continue
seen.add(v)
stack.extend(vadj[v])
genus = None
if comps == 1 and nonmanifold == 0:
genus = (2 - chi - loops) / 2
smooth = sum(1 for p in me.polygons if p.use_smooth)
return {"verts": V, "edges": E, "faces": F, "quad_fraction": (quads / F) if F else 0.0,
"boundary_edges": len(boundary), "boundary_loops": loops, "nonmanifold_edges": nonmanifold,
"euler": chi, "components": comps, "genus": genus,
"smooth_fraction": (smooth / F) if F else 0.0}
def crease_info(me):
info = {"crease_edge_attr": False, "crease_edges_nonzero": 0, "crease_max": 0.0}
a = me.attributes.get("crease_edge")
if a is not None:
info["crease_edge_attr"] = True
vals = [d.value for d in a.data]
info["crease_edges_nonzero"] = sum(1 for v in vals if v > 1e-4)
info["crease_max"] = max(vals) if vals else 0.0
return info
def modifiers(ob):
res = []
for m in ob.modifiers:
d = {"type": m.type, "name": m.name, "show_viewport": m.show_viewport, "show_render": m.show_render}
if m.type == "SOLIDIFY":
d.update(thickness=m.thickness, offset=m.offset, use_rim=m.use_rim,
edge_crease_inner=m.edge_crease_inner, edge_crease_outer=m.edge_crease_outer,
edge_crease_rim=m.edge_crease_rim, use_even_offset=m.use_even_offset)
elif m.type == "SUBSURF":
d.update(levels=m.levels, render_levels=m.render_levels, subdivision_type=m.subdivision_type)
elif m.type == "SHRINKWRAP":
d.update(target=m.target.name if m.target else None, wrap_method=m.wrap_method, offset=m.offset)
elif m.type == "MULTIRES":
d.update(levels=m.levels, total_levels=m.total_levels)
elif m.type == "NODES":
d.update(gn_modifier_info(m))
elif m.type == "LATTICE":
d.update(object=m.object.name if m.object else None, vertex_group=m.vertex_group)
res.append(d)
return res
def world_points(ob, me):
M = ob.matrix_world
return [M @ v.co for v in me.vertices]
def z_profile(pts, bins=12):
"""radius-from-axis per height bin (axis = XY centre of the bbox)."""
bb = bbox(pts)
if not bb or bb["dim"][2] < 1e-6:
return None
cx, cy = bb["center"][0], bb["center"][1]
z0, z1 = bb["min"][2], bb["max"][2]
acc = defaultdict(list)
for p in pts:
k = min(bins - 1, int((p.z - z0) / (z1 - z0) * bins))
acc[k].append(math.hypot(p.x - cx, p.y - cy))
prof = []
for k in range(bins):
r = acc.get(k)
rs = sorted(r) if r else []
prof.append({"z_lo": z0 + (z1 - z0) * k / bins, "n": len(rs),
"r_mean": (sum(rs) / len(rs)) if rs else None, "r_max": rs[-1] if rs else None,
"r_median": rs[len(rs) // 2] if rs else None})
return prof
def angular_profile(pts, center, sectors=48):
"""lowest z per angular sector around centre — the icing's rim/drips."""
minz = [None] * sectors
maxz = [None] * sectors
for p in pts:
a = math.atan2(p.y - center[1], p.x - center[0])
k = int(((a + math.pi) / (2 * math.pi)) * sectors) % sectors
minz[k] = p.z if minz[k] is None else min(minz[k], p.z)
maxz[k] = p.z if maxz[k] is None else max(maxz[k], p.z)
return {"min_z": minz, "max_z": maxz}
def fit_torus(pts):
"""centre + major radius R (mean axial distance) + minor radius r (half height)."""
bb = bbox(pts)
cx, cy, cz = bb["center"]
rho = [math.hypot(p.x - cx, p.y - cy) for p in pts]
Rm = sum(rho) / len(rho)
r = bb["dim"][2] / 2
# residual: how torus-like the point cloud is
res = [abs(math.hypot(rh - Rm, p.z - cz) - r) for rh, p in zip(rho, pts)]
return {"center": [cx, cy, cz], "R": Rm, "r": r, "resid_mean": sum(res) / len(res), "resid_max": max(res)}
def torus_distances(pts, tor):
cx, cy, cz = tor["center"]
d = []
for p in pts:
rho = math.hypot(p.x - cx, p.y - cy)
d.append(math.hypot(rho - tor["R"], p.z - cz) - tor["r"]) # signed: + outside the tube
d.sort()
n = len(d)
if not n:
return None
q = lambda f: d[min(n - 1, int(f * n))]
return {"n": n, "p05": q(0.05), "p25": q(0.25), "p50": q(0.5), "p75": q(0.75), "p95": q(0.95), "max": d[-1],
"frac_within_3mm": sum(1 for x in d if abs(x) < 0.003) / n,
"frac_within_6mm": sum(1 for x in d if abs(x) < 0.006) / n,
"frac_above_center": None}
def material_info(ob):
mats = []
for slot in ob.material_slots:
m = slot.material
if m is None:
continue
d = {"name": m.name, "use_nodes": m.use_nodes, "users": m.users, "nodes": [], "links": [],
"displacement_method": getattr(m, "displacement_method", None)}
if m.use_nodes and m.node_tree:
for n in m.node_tree.nodes:
nd = {"type": n.type, "name": n.name}
if n.type == "TEX_IMAGE":
img = n.image
nd["image"] = img.name if img else None
nd["filepath"] = img.filepath if img else None
nd["colorspace"] = img.colorspace_settings.name if img else None
elif n.type == "BSDF_PRINCIPLED":
def sock(name):
so = n.inputs.get(name)
if so is None:
return None
v = so.default_value
try:
return list(v)
except TypeError:
return v
nd["base_color"] = sock("Base Color")
nd["roughness"] = sock("Roughness")
nd["metallic"] = sock("Metallic")
nd["subsurface_weight"] = sock("Subsurface Weight")
nd["subsurface_radius"] = sock("Subsurface Radius")
nd["subsurface_scale"] = sock("Subsurface Scale")
nd["linked_inputs"] = [i.name for i in n.inputs if i.is_linked]
elif n.type == "VALTORGB":
nd["interpolation"] = n.color_ramp.interpolation
nd["stops"] = len(n.color_ramp.elements)
elif n.type == "OUTPUT_MATERIAL":
nd["linked_inputs"] = [i.name for i in n.inputs if i.is_linked]
d["nodes"].append(nd)
for l in m.node_tree.links:
d["links"].append([l.from_node.type, l.from_socket.name, l.to_node.type, l.to_socket.name])
mats.append(d)
return mats
def mesh_extras(ob, me):
seams = sum(1 for e in me.edges if e.use_seam)
return {"uv_layers": [uv.name for uv in me.uv_layers], "seam_edges": seams,
"vertex_groups": [vg.name for vg in ob.vertex_groups],
"color_attributes": [a.name for a in me.color_attributes]}
def gn_modifier_info(m):
d = {"node_group": m.node_group.name if m.node_group else None, "inputs": {}}
try:
for k in m.keys():
v = m[k]
if hasattr(v, "name") and hasattr(v, "bl_rna"):
d["inputs"][k] = f"<{v.bl_rna.identifier}:{v.name}>"
else:
try:
d["inputs"][k] = list(v) if hasattr(v, "__len__") and not isinstance(v, str) else v
except Exception:
d["inputs"][k] = str(v)
except Exception as e: # noqa: BLE001
d["inputs_error"] = repr(e)
return d
depsgraph = bpy.context.evaluated_depsgraph_get()
objects = list(bpy.data.objects)
R["object_names"] = [(o.name, o.type) for o in objects]
R["images"] = [{"name": i.name, "filepath": i.filepath, "users": i.users, "size": list(i.size)} for i in bpy.data.images]
R["workspaces"] = [w.name for w in bpy.data.workspaces]
R["empties"] = [{"name": o.name, "display": o.empty_display_type, "image": o.data.name if (o.empty_display_type == "IMAGE" and o.data) else None,
"rotation_deg": [math.degrees(a) for a in o.rotation_euler], "scale": list(o.scale)}
for o in objects if o.type == "EMPTY"]
scene = bpy.context.scene
try:
R["scene"] = {
"render_engine": scene.render.engine,
"resolution": [scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage],
"eevee_use_raytracing": getattr(scene.eevee, "use_raytracing", None),
"eevee_shadow_step_count": getattr(scene.eevee, "shadow_step_count", None),
"eevee_taa_render_samples": getattr(scene.eevee, "taa_render_samples", None),
"view_transform": scene.view_settings.view_transform,
"look": scene.view_settings.look,
"camera": scene.camera.name if scene.camera else None,
"collections": [c.name for c in bpy.data.collections],
"collection_objects": {c.name: [o.name for o in c.objects] for c in bpy.data.collections},
"excluded_collections": [lc.name for lc in bpy.context.view_layer.layer_collection.children if lc.exclude],
}
except Exception as e: # noqa: BLE001
R["errors"].append(f"scene: {e!r}")
try:
sc = R.setdefault("scene", {})
sc["fps"] = scene.render.fps
sc["cycles_samples"] = getattr(scene.cycles, "samples", None)
sc["cycles_denoise"] = getattr(scene.cycles, "use_denoising", None)
sc["cycles_adaptive"] = getattr(scene.cycles, "use_adaptive_sampling", None)
sc["use_nodes"] = scene.use_nodes
sc["compositor_nodes"] = [n.type for n in scene.node_tree.nodes] if scene.node_tree else []
sc["world_nodes"] = [n.type for n in scene.world.node_tree.nodes] if scene.world and scene.world.node_tree else []
sc["frame_range"] = [scene.frame_start, scene.frame_end]
sc["film_transparent"] = scene.render.film_transparent
except Exception as e: # noqa: BLE001
R["errors"].append(f"scene2: {e!r}")
R["actions"] = [{"name": a.name, "fcurves": [(fc.data_path, fc.array_index, len(fc.keyframe_points)) for fc in a.fcurves][:20],
"frame_range": list(a.frame_range)} for a in bpy.data.actions]
R["animated_objects"] = [{"name": o.name, "type": o.type, "action": o.animation_data.action.name,
"paths": sorted({fc.data_path for fc in o.animation_data.action.fcurves})}
for o in objects if o.animation_data and o.animation_data.action]
R["node_groups"] = {ng.name: {"bl_idname": ng.bl_idname, "node_types": sorted({n.type for n in ng.nodes}), "n": len(ng.nodes)} for ng in bpy.data.node_groups}
R["lights"] = [{"name": o.name, "light_type": o.data.type, "energy": o.data.energy,
"shadow_soft_size": getattr(o.data, "shadow_soft_size", None), "color": list(o.data.color),
"location": list(o.location), "rotation_deg": [math.degrees(a) for a in o.rotation_euler],
"collections": [c.name for c in o.users_collection], "hide_render": o.hide_render}
for o in objects if o.type == "LIGHT"]
R["cameras"] = [{"name": o.name, "location": list(o.location), "rotation_deg": [math.degrees(a) for a in o.rotation_euler],
"use_dof": o.data.dof.use_dof, "focus_object": o.data.dof.focus_object.name if o.data.dof.focus_object else None,
"focus_distance": o.data.dof.focus_distance, "lens": o.data.lens}
for o in objects if o.type == "CAMERA"]
R["lattices"] = [{"name": o.name, "points": [o.data.points_u, o.data.points_v, o.data.points_w]} for o in objects if o.type == "LATTICE"]
R["light_probes"] = [{"name": o.name, "probe_type": getattr(o.data, "type", None)} for o in objects if o.type == "LIGHT_PROBE"]
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}")
# first pass: find the torus (donut) to fit against
mesh_obs = [o for o in objects if o.type == "MESH"]
torus_fit = None
donut_candidates = []
for ob in mesh_obs:
me = ob.data
t = safe(f"topo:{ob.name}", topology, me)
if not t:
continue
pts = world_points(ob, me)
if t["boundary_edges"] == 0 and t["euler"] == 0 and t["quad_fraction"] > 0.95 and t["components"] == 1:
fit = fit_torus(pts)
donut_candidates.append((ob.name, fit, len(pts)))
# prefer a name match, then the best torus fit
def _score(c):
name, fit, n = c
named = 0 if ("donut" in name.lower() or "torus" in name.lower()) else 1
return (named, fit["resid_mean"] / max(fit["r"], 1e-6))
donut_candidates.sort(key=_score)
if donut_candidates:
torus_fit = donut_candidates[0][1]
R["torus_fit"] = dict(torus_fit, object=donut_candidates[0][0])
for ob in objects:
d = {"name": ob.name, "type": ob.type, "mode": ob.mode, "location": list(ob.location),
"animated": bool(ob.animation_data and ob.animation_data.action),
"rotation_deg": [math.degrees(a) for a in ob.rotation_euler], "scale": list(ob.scale),
"dimensions": list(ob.dimensions), "parent": ob.parent.name if ob.parent else None,
"hide_viewport": ob.hide_viewport, "hide_render": ob.hide_render,
"collections": [c.name for c in ob.users_collection]}
if ob.type == "MESH":
me = ob.data
d["mesh_name"] = me.name
d["topology"] = safe(f"topo:{ob.name}", topology, me)
d["crease"] = safe(f"crease:{ob.name}", crease_info, me)
d["modifiers"] = safe(f"mods:{ob.name}", modifiers, ob)
d["materials"] = safe(f"mats:{ob.name}", material_info, ob)
d["mesh_extras"] = safe(f"extras:{ob.name}", mesh_extras, ob, me)
pts = world_points(ob, me)
d["bbox_base"] = bbox(pts)
d["z_profile_base"] = safe(f"zprof:{ob.name}", z_profile, pts)
if d["bbox_base"]:
d["mean_z_base"] = sum(p.z for p in pts) / len(pts)
if torus_fit:
d["angular_base"] = safe(f"ang:{ob.name}", angular_profile, pts, torus_fit["center"])
d["torus_dist_base"] = safe(f"tdist:{ob.name}", torus_distances, pts, torus_fit)
try:
ev = ob.evaluated_get(depsgraph)
eme = ev.to_mesh()
epts = [ev.matrix_world @ v.co for v in eme.vertices]
d["evaluated"] = {"verts": len(eme.vertices), "faces": len(eme.polygons), "bbox": bbox(epts)}
if epts:
d["evaluated"]["mean_z"] = sum(p.z for p in epts) / len(epts)
if torus_fit and epts:
d["evaluated"]["angular"] = angular_profile(epts, torus_fit["center"])
d["evaluated"]["torus_dist"] = torus_distances(epts, torus_fit)
ev.to_mesh_clear()
except Exception as e: # noqa: BLE001
R["errors"].append(f"evaluated:{ob.name}: {e!r}")
R["objects"].append(d)
with open(out_path, "w") as f:
json.dump(R, f, indent=1, default=str)
print(f"inspect_blend: wrote {out_path} ({len(R['objects'])} objects, {len(R['errors'])} errors)")