Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import bpy
- from mathutils import Matrix, Vector
- MULT = 1.0 # 1.0 = keep visual size; 100.0 = also make it 100x bigger
- CENTER = "xy" # axes to recenter; "xyz" = all, "" = off
- CENTER_MODE = "ZERO" # ZERO = armature location goes to 0 on those axes
- # BONES = rest-pose bone bbox center goes to the world origin
- KEEP_SOURCE = False
- REPARENT = True
- def dims(ob, dg):
- ev = ob.evaluated_get(dg)
- return tuple(max(c) - min(c) for c in
- zip(*[ev.matrix_world @ Vector(v) for v in ev.bound_box]))
- def fcurves(act):
- yield from getattr(act, "fcurves", [])
- for l in getattr(act, "layers", []):
- for s in l.strips:
- for cb in getattr(s, "channelbags", []):
- yield from cb.fcurves
- def sel(*obs):
- for o in bpy.context.selected_objects:
- o.select_set(False)
- for o in obs:
- o.select_set(True)
- if obs:
- bpy.context.view_layer.objects.active = obs[0]
- def center_offset(arm, mw):
- """World vector to subtract so the rig lands on the origin. No side effects."""
- if not CENTER:
- return Vector()
- if CENTER_MODE.upper() == "ZERO":
- t = mw.translation
- return Vector([t[i] if a in CENTER else 0.0 for i, a in enumerate("xyz")])
- pts = [mw @ v for b in arm.data.bones for v in (b.head_local, b.tail_local)]
- if not pts:
- return Vector()
- return Vector([(min(c) + max(c)) / 2 if a in CENTER else 0.0
- for a, c in zip("xyz", zip(*pts))])
- def run():
- s = bpy.context.selected_objects
- rigs = [o for o in s if o.type == 'ARMATURE']
- meshes = [o for o in s if o.type == 'MESH']
- if len(rigs) != 1:
- return f"select exactly one armature (found {len(rigs)})"
- src = rigs[0]
- if bpy.context.object and bpy.context.object.mode != 'OBJECT':
- bpy.ops.object.mode_set(mode='OBJECT')
- sc = src.matrix_world.to_scale()
- if max(sc) - min(sc) > 1e-6:
- return f"rig has non-uniform scale {tuple(round(v, 4) for v in sc)} - not fixable this way"
- ad = src.animation_data
- acts = set()
- if ad:
- acts = {st.action for t in ad.nla_tracks for st in t.strips if st.action}
- if ad.action:
- acts.add(ad.action)
- bad = sorted({fc.data_path for a in acts for fc in fcurves(a)
- if fc.data_path.startswith(("location", "rotation", "scale", "delta_"))})
- if bad:
- return f"armature OBJECT is animated {bad} - bake or remove object-level animation first"
- shared = [o.name for o in meshes if o.data.users > 1]
- if shared:
- return f"multi-user mesh data on {shared} - make single-user first"
- scn = bpy.context.scene
- f0, f1 = scn.frame_start, scn.frame_end
- dg = bpy.context.evaluated_depsgraph_get()
- before = {o.name: dims(o, dg) for o in meshes}
- src_mw = src.matrix_world.copy()
- org = src_mw.translation
- # Recenter is folded into delta rather than applied afterwards, so the rig is
- # already in its final position before the bake. delta is applied identically
- # to the armature copy and every mesh copy, and src is temporarily moved by it
- # too, so the world-space constraints still line up during the bake.
- off = center_offset(src, src_mw)
- delta = (Matrix.Translation(-off) @ Matrix.Translation(org)
- @ Matrix.Scale(MULT, 4) @ Matrix.Translation(-org))
- copies = []
- for ob in meshes:
- sel(ob)
- bpy.ops.object.duplicate(linked=False)
- m = bpy.context.object
- m.name = ob.name + "_scaled"
- m.data.name = m.name
- mw = m.matrix_world.copy()
- m.parent = None
- m.matrix_world = mw
- copies.append((ob, m))
- sel(src)
- bpy.ops.object.duplicate(linked=False)
- dst = bpy.context.object
- dst.name = src.name + "_scaled"
- if dst.data == src.data:
- dst.data = src.data.copy()
- dst.data.name = dst.name
- dst.animation_data_clear()
- dst.matrix_world = delta @ src_mw
- sel(dst)
- bpy.ops.object.transform_apply(rotation=True, scale=True)
- for c in getattr(dst.data, "collections_all", []):
- c.is_visible = True
- for b in dst.data.bones:
- b.hide = False
- for ob, m in copies:
- m.matrix_world = delta @ ob.matrix_world
- for mod in m.modifiers:
- if mod.type == 'ARMATURE' and mod.object in (src, None):
- mod.object = dst
- sel(dst)
- src.matrix_world = delta @ src_mw
- bpy.context.view_layer.update()
- bpy.ops.object.mode_set(mode='POSE')
- linked, missing = 0, []
- for pb in dst.pose.bones:
- if pb.name not in src.pose.bones:
- missing.append(pb.name)
- continue
- for c in list(pb.constraints):
- pb.constraints.remove(c)
- for kind, space in (('COPY_LOCATION', 'WORLD'), ('COPY_ROTATION', 'WORLD'),
- ('COPY_SCALE', 'LOCAL')):
- c = pb.constraints.new(kind)
- c.target, c.subtarget = src, pb.name
- c.target_space = c.owner_space = space
- linked += 1
- if not linked:
- bpy.ops.object.mode_set(mode='OBJECT')
- src.matrix_world = src_mw
- return "no matching bones - aborted, delete the copies"
- bpy.ops.nla.bake(frame_start=f0, frame_end=f1, step=1, only_selected=False,
- visual_keying=True, clear_constraints=True, clear_parents=False,
- use_current_action=False, bake_types={'POSE'})
- bpy.ops.object.mode_set(mode='OBJECT')
- for pb in dst.pose.bones:
- for c in list(pb.constraints):
- pb.constraints.remove(c)
- if dst.animation_data and dst.animation_data.action:
- dst.animation_data.action.name = src.name + "_scaled_baked"
- src.matrix_world = src_mw
- bpy.context.view_layer.update()
- if copies:
- sel(*[m for _, m in copies])
- bpy.ops.object.transform_apply(rotation=True, scale=True)
- if REPARENT:
- bpy.context.view_layer.update()
- inv = dst.matrix_world.inverted()
- for _, m in copies:
- m.parent = dst
- m.matrix_parent_inverse = inv
- report = [(before[ob.name], m) for ob, m in copies]
- if KEEP_SOURCE:
- for o in [src] + [ob for ob, _ in copies]:
- o.hide_set(True)
- o.hide_render = True
- else:
- for ob, _ in copies:
- bpy.data.objects.remove(ob, do_unlink=True)
- bpy.data.objects.remove(src, do_unlink=True)
- sel(dst, *[m for _, m in copies])
- dg = bpy.context.evaluated_depsgraph_get()
- lines = [f" {m.name}: " + " ".join(f"{b / a:.4g}" if a > 1e-9 else "n/a"
- for a, b in zip(a0, dims(m, dg))) for a0, m in report]
- note = f", {len(missing)} unmatched bone(s): {missing[:5]}" if missing else ""
- mode = CENTER_MODE.upper() if CENTER else "off"
- loc = tuple(round(v, 4) for v in dst.matrix_world.translation)
- return (f"baked {linked} bones over {f0}-{f1}, size multiplier {MULT:g}, "
- f"centering {mode} on '{CENTER or '-'}' removed "
- f"{tuple(round(v, 4) for v in off)}, rig location now {loc}{note}\n"
- "mesh size ratios (should all equal the multiplier):\n" + "\n".join(lines))
- print(run())
Advertisement
Add Comment
Please, Sign In to add comment