220 lines
10 KiB
Python
220 lines
10 KiB
Python
# tools/fixtures/_blend_ref: run by tools/fixtures/blend.py inside Blender (blender -b --factory-startup --python
|
|
# <this> -- <json list of .blend paths> <out dir>): opens each file (old ones through Blender's versioning) and writes
|
|
# <out dir>/<file>.json with the reference values (object world matrices, mesh counts / bounds / attribute sums / corner normals,
|
|
# vertex groups, shape keys, materials, images, cameras, lights, bones, f-curve values, posed world matrices per frame),
|
|
# and exports a .glb of each file (Z up, no modifiers) whose JSON part is returned as "gltf".
|
|
import bpy, sys, os, json, struct, math
|
|
|
|
args = sys.argv[sys.argv.index("--") + 1:]
|
|
paths, outdir = json.loads(args[0]), args[1]
|
|
V = bpy.app.version
|
|
|
|
|
|
def mat(m):
|
|
return [m[r][c] for c in range(4) for r in range(4)] # column-major
|
|
|
|
|
|
def r6(x):
|
|
return round(float(x), 6)
|
|
|
|
|
|
def color_attrs(me):
|
|
out = []
|
|
attrs = me.color_attributes if hasattr(me, "color_attributes") else []
|
|
for a in attrs:
|
|
s = [0.0, 0.0, 0.0, 0.0]
|
|
for l in me.loops:
|
|
d = a.data[l.index if a.domain == "CORNER" else l.vertex_index]
|
|
for k in range(4):
|
|
s[k] += d.color[k]
|
|
out.append({"name": a.name, "domain": a.domain, "type": a.data_type, "count": len(a.data), "cornerSum": [r6(x) for x in s]})
|
|
return out
|
|
|
|
|
|
def mesh_info(ob):
|
|
me = ob.data
|
|
me.calc_loop_triangles()
|
|
vs = [v.co for v in me.vertices]
|
|
lo = [min(v[k] for v in vs) for k in range(3)] if vs else [0, 0, 0]
|
|
hi = [max(v[k] for v in vs) for k in range(3)] if vs else [0, 0, 0]
|
|
info = {
|
|
"name": me.name, "vertices": len(me.vertices), "corners": len(me.loops), "faces": len(me.polygons),
|
|
"triangles": len(me.loop_triangles), "min": [r6(x) for x in lo], "max": [r6(x) for x in hi],
|
|
"possum": [r6(sum(v[k] for v in vs)) for k in range(3)],
|
|
"uvs": [], "colors": color_attrs(me), "slots": [s.material.name if s.material else "" for s in ob.material_slots],
|
|
"facemats": [p.material_index for p in me.polygons],
|
|
"smooth": [1 if p.use_smooth else 0 for p in me.polygons],
|
|
}
|
|
for layer in me.uv_layers:
|
|
su = sv = 0.0
|
|
for d in layer.data:
|
|
su += d.uv[0]
|
|
sv += d.uv[1]
|
|
info["uvs"].append({"name": layer.name, "sum": [r6(su), r6(sv)], "active_render": bool(layer.active_render)})
|
|
if len(me.loops) <= 400:
|
|
if hasattr(me, "corner_normals"):
|
|
info["normals"] = [[r6(c) for c in n.vector] for n in me.corner_normals]
|
|
info["cornerVerts"] = [l.vertex_index for l in me.loops]
|
|
info["custom"] = bool(me.has_custom_normals)
|
|
groups = {g.index: g.name for g in ob.vertex_groups}
|
|
if groups:
|
|
info["weights"] = [[[groups.get(g.group, "?"), r6(g.weight)] for g in v.groups] for v in me.vertices]
|
|
if me.shape_keys:
|
|
k = me.shape_keys
|
|
info["shapes"] = [{"name": b.name, "value": r6(b.value), "relative": b.relative_key.name,
|
|
"co": [r6(p.co[c]) for p in b.data for c in range(3)]} for b in k.key_blocks]
|
|
info["reference"] = k.reference_key.name
|
|
info["modifiers"] = [m.type for m in ob.modifiers]
|
|
return info
|
|
|
|
|
|
def socket_val(s):
|
|
if s is None:
|
|
return None
|
|
v = s.default_value
|
|
try:
|
|
return [r6(x) for x in v]
|
|
except TypeError:
|
|
return r6(v)
|
|
|
|
|
|
def linked_image(s):
|
|
if s is None or not s.is_linked:
|
|
return None
|
|
n = s.links[0].from_node
|
|
if n.bl_idname == "ShaderNodeNormalMap":
|
|
return linked_image(n.inputs["Color"])
|
|
if n.bl_idname == "ShaderNodeTexImage" and n.image:
|
|
return n.image.name
|
|
return "?" + n.bl_idname
|
|
|
|
|
|
def material_info(m):
|
|
info = {"name": m.name, "diffuse": [r6(x) for x in m.diffuse_color], "metallic": r6(m.metallic), "roughness": r6(m.roughness),
|
|
"use_nodes": bool(m.use_nodes), "cull": bool(m.use_backface_culling)}
|
|
if m.node_tree:
|
|
for n in m.node_tree.nodes:
|
|
if n.bl_idname == "ShaderNodeBsdfPrincipled":
|
|
ins = n.inputs
|
|
g = lambda *names: next((ins[x] for x in names if x in ins), None)
|
|
info["principled"] = {
|
|
"base": socket_val(g("Base Color")), "metallic": socket_val(g("Metallic")), "roughness": socket_val(g("Roughness")),
|
|
"emission": socket_val(g("Emission Color", "Emission")), "strength": socket_val(g("Emission Strength")),
|
|
"alpha": socket_val(g("Alpha")),
|
|
"baseTex": linked_image(g("Base Color")), "normalTex": linked_image(g("Normal")),
|
|
"emissionTex": linked_image(g("Emission Color", "Emission")),
|
|
}
|
|
if n.bl_idname == "ShaderNodeNormalMap":
|
|
info["normalStrength"] = r6(n.inputs["Strength"].default_value)
|
|
return info
|
|
|
|
|
|
def fcurves(act):
|
|
if act is None:
|
|
return []
|
|
if hasattr(act, "fcurves") and V < (5, 0):
|
|
return list(act.fcurves)
|
|
out = []
|
|
for layer in act.layers:
|
|
for strip in layer.strips:
|
|
for bag in strip.channelbags:
|
|
out.extend(bag.fcurves)
|
|
return out
|
|
|
|
|
|
FRAMES = [1 + 0.5 * i for i in range(43)] # 1 .. 22 (past the last key: extrapolation)
|
|
|
|
|
|
def curve_info(act):
|
|
out = []
|
|
for fc in fcurves(act):
|
|
out.append({"path": fc.data_path, "index": fc.array_index, "extrapolation": fc.extrapolation,
|
|
"keys": len(fc.keyframe_points), "values": [r6(fc.evaluate(f)) for f in FRAMES]})
|
|
return out
|
|
|
|
|
|
def dump(path):
|
|
bpy.ops.wm.open_mainfile(filepath=path)
|
|
sc = bpy.context.scene
|
|
sc.frame_set(sc.frame_current)
|
|
obs = list(sc.objects)
|
|
ref = {"version": list(bpy.data.version), "fps": sc.render.fps / sc.render.fps_base, "frameStart": sc.frame_start,
|
|
"frameCurrent": sc.frame_current, "resolution": [sc.render.resolution_x, sc.render.resolution_y],
|
|
"objects": [], "materials": [], "images": [], "cameras": {}, "lights": {}, "armatures": {}, "actions": {}}
|
|
for ob in obs:
|
|
o = {"name": ob.name, "type": ob.type, "parent": ob.parent.name if ob.parent else "", "parent_type": ob.parent_type,
|
|
"parent_bone": ob.parent_bone, "world": [r6(x) for x in mat(ob.matrix_world)],
|
|
"collections": [c.name for c in ob.users_collection]}
|
|
if ob.type == "MESH":
|
|
o["mesh"] = mesh_info(ob)
|
|
if ob.animation_data and ob.animation_data.action:
|
|
a = ob.animation_data.action
|
|
ref["actions"][a.name] = curve_info(a)
|
|
o["action"] = a.name
|
|
if ob.type == "MESH" and ob.data.shape_keys and ob.data.shape_keys.animation_data and ob.data.shape_keys.animation_data.action:
|
|
a = ob.data.shape_keys.animation_data.action
|
|
ref["actions"][a.name] = curve_info(a)
|
|
o["shapeAction"] = a.name
|
|
ref["objects"].append(o)
|
|
if ob.type == "CAMERA":
|
|
c = ob.data
|
|
ref["cameras"][ob.name] = {"type": c.type, "lens": r6(c.lens), "sensor": [r6(c.sensor_width), r6(c.sensor_height)],
|
|
"fit": c.sensor_fit, "ortho": r6(c.ortho_scale), "clip": [r6(c.clip_start), r6(c.clip_end)],
|
|
"angle": [r6(c.angle_x), r6(c.angle_y)]}
|
|
if ob.type == "LIGHT":
|
|
l = ob.data
|
|
ref["lights"][ob.name] = {"type": l.type, "color": [r6(x) for x in l.color], "energy": r6(l.energy),
|
|
"spot": [r6(l.spot_size), r6(l.spot_blend)] if l.type == "SPOT" else [0, 0]}
|
|
if ob.type == "ARMATURE":
|
|
ref["armatures"][ob.name] = [{"name": b.name, "parent": b.parent.name if b.parent else "", "deform": b.use_deform,
|
|
"local": [r6(x) for x in mat(b.matrix_local)], "length": r6(b.length)} for b in ob.data.bones]
|
|
for m in bpy.data.materials:
|
|
ref["materials"].append(material_info(m))
|
|
for im in bpy.data.images:
|
|
if im.source in ("FILE", "GENERATED") and im.type == "IMAGE":
|
|
ref["images"].append({"name": im.name, "filepath": im.filepath, "packed": im.packed_file.size if im.packed_file else 0,
|
|
"source": im.source})
|
|
# posed world matrices: objects, pose bones (world), shape key values
|
|
poses = []
|
|
if ref["actions"]:
|
|
for f in FRAMES:
|
|
sc.frame_set(int(math.floor(f)), subframe=f - math.floor(f))
|
|
p = {"frame": f, "objects": {}, "bones": {}, "shapes": {}}
|
|
for ob in obs:
|
|
p["objects"][ob.name] = [r6(x) for x in mat(ob.matrix_world)]
|
|
if ob.type == "ARMATURE":
|
|
for pb in ob.pose.bones:
|
|
p["bones"][ob.name + "/" + pb.name] = [r6(x) for x in mat(ob.matrix_world @ pb.matrix)]
|
|
if ob.type == "MESH" and ob.data.shape_keys:
|
|
p["shapes"][ob.name] = [r6(b.value) for b in ob.data.shape_keys.key_blocks]
|
|
if ob.type == "MESH" and any(m.type == "ARMATURE" for m in ob.modifiers) and f == math.floor(f):
|
|
ev = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())
|
|
em = ev.to_mesh()
|
|
w = ob.matrix_world
|
|
p.setdefault("skinned", {})[ob.name] = [r6(c) for v in em.vertices for c in (w @ v.co)]
|
|
ev.to_mesh_clear()
|
|
poses.append(p)
|
|
ref["poses"] = poses
|
|
# Blender's glTF exporter on the same file (Z up, modifiers not applied)
|
|
glb = os.path.join(outdir, os.path.basename(path) + ".glb")
|
|
try:
|
|
bpy.ops.export_scene.gltf(filepath=glb, export_format="GLB", export_yup=False, export_apply=False,
|
|
export_cameras=True, export_lights=True)
|
|
with open(glb, "rb") as fh:
|
|
data = fh.read()
|
|
n = struct.unpack_from("<I", data, 12)[0]
|
|
ref["gltf"] = json.loads(data[20:20 + n].decode("utf-8"))
|
|
ref["gltf"].pop("buffers", None)
|
|
except Exception as e: # noqa: BLE001
|
|
ref["gltfError"] = str(e)
|
|
return ref
|
|
|
|
|
|
for p in paths:
|
|
try:
|
|
r = dump(p)
|
|
except Exception as e: # noqa: BLE001
|
|
r = {"error": str(e)}
|
|
with open(os.path.join(outdir, os.path.basename(p) + ".json"), "w") as fh:
|
|
json.dump(r, fh)
|