Linzhan's picture
Initial release: prompts, metadata, T-pose renders, build pipeline (no commercial motion files)
a84fca7 verified
Raw
History Blame Contribute Delete
22.5 kB
#!/usr/bin/env python3
"""Graft a mesh and its skin from a donor FBX into one that was exported without geometry.
fbx_graft_mesh.py --selftest <fbx>... byte-identical round trip
fbx_graft_mesh.py --inspect <fbx>... what geometry/skin a file holds
fbx_graft_mesh.py --donor <donor> [--bind X] <target> graft, in place
`--bind` decides whose bind pose — whose rest pose, as an importer will show it —
the repaired clip ends up with. `donor` (the default) adopts the donor's, which is
what keeps a species' clips sharing one rest pose; `self` keeps the target's own,
re-posing the grafted mesh to match; a path takes a third file's.
`KingCobra-Walk.fbx` is the one clip in this dataset with no geometry: the export
dropped `Geometry::Mesh` and `Model::Mesh` while keeping the skeleton, the
animation curves, the materials and the embedded textures. Its two `Deformer::Skin`
objects survived as orphans, and they index a 1110-vertex mesh that exists in no
file — every other KingCobra clip carries the same 2220-vertex mesh instead. The
orphan skin is therefore unrecoverable, and the fix is to bring in a sibling's
complete geometry-plus-skin package.
That is sound because the two rigs are the same skeleton: identical bone names,
identical parenting, and identical `PreRotation` on all 19 bones. The donor's
bind *posture* differs, but a skin cluster stores
`Transform = MeshGlobal_bind · inverse(TransformLink)`, which resolves a vertex
into the bone's own local frame and so cancels the posture it was bound in. The
deformation is then reconstructed from whatever world matrix the target's own
animation gives each bone, frame by frame.
What moves: `Geometry::Mesh`, `Model::Mesh`, `Deformer::Skin`, its `Cluster`s and
`Pose::BindPose`. What is deleted: the target's orphan skins and clusters. Every
copied object gets a fresh uid, and connections that point at the donor's bones,
materials or textures are re-pointed at the target's own by name — nothing about
the target's skeleton, curves or embedded pixels is touched.
Correctness gate: with no edits the serializer must reproduce its input byte for
byte (`--selftest`), the same gate `fbx_embed_texture.py` uses.
Writes through a temporary file and renames it into place. Clips here are
hardlinks of files in `Truebone_Z-OO/`, and writing to such a path writes through
to the original; `os.replace` swaps the name and leaves the source alone.
"""
import collections, math, os, struct, sys, zlib
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from fbx_embed_texture import parse, serialize, Node, ELEM, SCALAR
# ---------------------------------------------------------------- properties
def sval(pr):
t, pay = pr
if t in "SR": return pay
return {"L": "<q", "I": "<i", "D": "<d", "F": "<f", "Y": "<h"}.get(t) and \
struct.unpack({"L": "<q", "I": "<i", "D": "<d", "F": "<f", "Y": "<h"}[t], pay)[0]
def uid_prop(uid):
return ("L", struct.pack("<q", uid))
def clean(name):
return name.decode("utf-8", "replace").split("\x00")[0]
# ---------------------------------------------------------------- tree access
def top(tree, name):
for n in tree["top"]:
if n.name == name: return n
return None
def objects(tree):
"""uid -> (class, name, subtype, node)"""
o = top(tree, b"Objects"); out = {}
if not o: return out
for ch in o.children:
if len(ch.props) >= 3:
out[sval(ch.props[0])] = (ch.name, sval(ch.props[1]), sval(ch.props[2]), ch)
return out
def connections(tree):
c = top(tree, b"Connections")
return [] if not c else [tuple(sval(x) for x in ch.props) for ch in c.children]
def copy_node(n):
c = Node(n.name)
c.props = list(n.props)
c.nullrec = n.nullrec
c.children = [copy_node(x) for x in n.children]
return c
# ---------------------------------------------------------------- inspection
def inspect(path):
t = parse(path); o = objects(t)
verts = polys = 0
for uid, (cls, nm, sub, node) in o.items():
if cls == b"Geometry":
for ch in node.children:
if ch.name == b"Vertices":
length = struct.unpack("<I", ch.props[0][1][:4])[0]; verts = length // 3
if ch.name == b"PolygonVertexIndex":
polys = struct.unpack("<I", ch.props[0][1][:4])[0]
census = collections.Counter((clean(cls), clean(sub)) for cls, _, sub, _ in
((c, n, s, x) for c, n, s, x in o.values()))
return {"verts": verts, "poly_indices": polys,
"geometry": census[("Geometry", "Mesh")],
"model_mesh": census[("Model", "Mesh")],
"limbs": census[("Model", "LimbNode")],
"skins": census[("Deformer", "Skin")],
"clusters": census[("Deformer", "Cluster")],
"bindpose": census[("Pose", "BindPose")]}
# ---------------------------------------------------------------- arrays
FMT = {"d": ("d", 8), "f": ("f", 4), "i": ("i", 4), "l": ("q", 8), "b": ("b", 1)}
def rd_array(pr):
t, pay = pr
n, enc, clen = struct.unpack("<III", pay[:12])
body = pay[12:]
if enc: body = zlib.decompress(body)
f, sz = FMT[t]
return list(struct.unpack("<%d%s" % (n, f), body[:n * sz])), enc
def wr_array(t, vals, enc=1):
"""An array property: `(length, encoding, byte count)` then the payload.
The third header field must carry the payload's byte count even when the data
is stored uncompressed — readers take it as the number of bytes to consume,
not as a compressed-only field. Writing 0 there produces a file that this
module still round-trips happily and that Blender refuses to open.
"""
f, sz = FMT[t]
raw = struct.pack("<%d%s" % (len(vals), f), *vals)
if enc:
raw = zlib.compress(raw)
return (t, struct.pack("<III", len(vals), 1 if enc else 0, len(raw)) + raw)
# ---------------------------------------------------------------- rebinding
def _mat(vals):
"""FBX stores a 4x4 as 16 doubles with the translation last — row-vector layout."""
return [vals[i * 4:i * 4 + 4] for i in range(4)]
def _mul(a, b):
return [[sum(a[i][k] * b[k][j] for k in range(4)) for j in range(4)] for i in range(4)]
def _inv(m):
"""Gauss-Jordan; these are affine but may carry scale, so invert generally."""
n = 4
a = [row[:] + [1.0 if i == j else 0.0 for j in range(n)] for i, row in enumerate(m)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(a[r][c]))
if abs(a[p][c]) < 1e-14: raise ValueError("singular matrix")
a[c], a[p] = a[p], a[c]
d = a[c][c]
a[c] = [x / d for x in a[c]]
for r in range(n):
if r == c: continue
f = a[r][c]
if f: a[r] = [x - f * y for x, y in zip(a[r], a[c])]
return [row[n:] for row in a]
def _flat(m):
return [x for row in m for x in row]
def bind_pose_of(path):
"""`{bone name: TransformLink}` — where each bone stood when the mesh was bound."""
t = parse(path); o = objects(t)
kids = collections.defaultdict(list)
for con in connections(t):
if con[0] == b"OO": kids[con[2]].append(con[1])
out = {}
for u, (c, n, s, node) in o.items():
if c != b"Deformer" or s != b"Cluster": continue
bone = next((clean(o[k][1]) for k in kids[u]
if k in o and o[k][0] == b"Model"), None)
g = {ch.name: ch for ch in node.children}
if bone and b"TransformLink" in g and bone not in out:
out[bone] = _mat(rd_array(g[b"TransformLink"].props[0])[0])
return out
def rebind(tt, tl_target, log):
"""Re-pose the grafted mesh into the target's own bind pose.
The mesh arrives bound in the donor's posture, and an importer that reads the
bind matrices will show the donor's rest pose rather than this clip's. The two
are different postures of the same skeleton, so the mesh can be moved between
them by the skin itself: evaluate it at the target's bind pose and rebind there.
A cluster stores `Transform = MeshGlobal_bind · inverse(TransformLink)`, so with
`K_i = Transform_i · TransformLink_target_i · inverse(MeshGlobal)` every vertex
becomes `v' = Σ w_i · v · K_i` and the cluster matrices follow. Weights here sum
to exactly 1 per vertex, so the blend is affine and needs no normalising.
"""
to = objects(tt)
geo = [node for u, (c, n, s, node) in to.items() if c == b"Geometry"]
if not geo: return False
geo = geo[0]
clusters = []
kids = collections.defaultdict(list)
for con in connections(tt):
if con[0] == b"OO": kids[con[2]].append(con[1])
for u, (c, n, s, node) in to.items():
if c != b"Deformer" or s != b"Cluster": continue
bone = next((clean(to[k][1]) for k in kids[u]
if k in to and to[k][0] == b"Model"), None)
g = {ch.name: ch for ch in node.children}
if bone is None or b"TransformLink" not in g: continue
clusters.append((bone, node, g))
missing = [b for b, _, _ in clusters if b not in tl_target]
if missing:
log.append("目标自身缺 %d 根骨骼的绑定矩阵,保留供体绑定姿势" % len(missing))
return False
# MeshGlobal is Transform · TransformLink, identical for every cluster
b0, _, g0 = clusters[0]
mesh_global = _mul(_mat(rd_array(g0[b"Transform"].props[0])[0]),
_mat(rd_array(g0[b"TransformLink"].props[0])[0]))
inv_mg = _inv(mesh_global)
K = {}
for bone, node, g in clusters:
tf = _mat(rd_array(g[b"Transform"].props[0])[0])
K[bone] = _mul(_mul(tf, tl_target[bone]), inv_mg)
verts, venc = rd_array(next(ch for ch in geo.children
if ch.name == b"Vertices").props[0])
nv = len(verts) // 3
acc = [[0.0, 0.0, 0.0] for _ in range(nv)]
nacc = [[0.0, 0.0, 0.0] for _ in range(nv)]
nrm_node = None
for ch in geo.children:
if ch.name != b"LayerElementNormal": continue
mapping = next((clean(cc.props[0][1]) for cc in ch.children
if cc.name == b"MappingInformationType"), "")
if mapping == "ByVertice":
nrm_node = next((cc for cc in ch.children if cc.name == b"Normals"), None)
normals = rd_array(nrm_node.props[0])[0] if nrm_node else None
for bone, node, g in clusters:
idx = rd_array(g[b"Indexes"].props[0])[0]
wts = rd_array(g[b"Weights"].props[0])[0]
k = K[bone]
# normals are directions: rotate by the inverse transpose of the 3x3
it = _inv([row[:3] + [0.0] for row in k[:3]] + [[0.0, 0.0, 0.0, 1.0]])
nk = [[it[j][i] for j in range(3)] for i in range(3)]
for i, w in zip(idx, wts):
x, y, z = verts[3 * i], verts[3 * i + 1], verts[3 * i + 2]
for j in range(3):
acc[i][j] += w * (x * k[0][j] + y * k[1][j] + z * k[2][j] + k[3][j])
if normals:
a, b_, c_ = normals[3 * i], normals[3 * i + 1], normals[3 * i + 2]
for j in range(3):
nacc[i][j] += w * (a * nk[0][j] + b_ * nk[1][j] + c_ * nk[2][j])
moved = max(math.dist((verts[3*i], verts[3*i+1], verts[3*i+2]), acc[i])
for i in range(nv))
for ch in geo.children:
if ch.name == b"Vertices":
ch.props[0] = wr_array("d", [c for v in acc for c in v], venc)
if normals:
out = []
for v in nacc:
L = math.sqrt(sum(c * c for c in v)) or 1.0
out += [c / L for c in v]
nrm_node.props[0] = wr_array("d", out, rd_array(nrm_node.props[0])[1])
for bone, node, g in clusters:
tl = tl_target[bone]
g[b"TransformLink"].props[0] = wr_array("d", _flat(tl), 0)
g[b"Transform"].props[0] = wr_array("d", _flat(_mul(mesh_global, _inv(tl))), 0)
log.append("重绑定到本片自身的绑定姿势:%d 根骨骼,顶点最大位移 %.4f" % (len(clusters), moved))
return True
# ---------------------------------------------------------------- the graft
MOVE = {(b"Geometry", b"Mesh"), (b"Model", b"Mesh"),
(b"Deformer", b"Skin"), (b"Deformer", b"Cluster"), (b"Pose", b"BindPose")}
def graft(donor_path, target_path, dry=False, bind="donor"):
dt, tt = parse(donor_path), parse(target_path)
do, to = objects(dt), objects(tt)
tobj, tcon = top(tt, b"Objects"), top(tt, b"Connections")
log = []
# 1. drop the target's orphan skins and clusters, keeping their bind pose
# — the clusters index a mesh that no longer exists, but `TransformLink`
# records where this clip's own bones stood at bind, which the graft must
# preserve or an importer will show the donor's rest pose instead.
had_pose = any(c == b"Pose" for c, _, _, _ in to.values())
tkids = collections.defaultdict(list)
for con in connections(tt):
if con[0] == b"OO": tkids[con[2]].append(con[1])
tl_target = {}
for u, (c, n, s, node) in to.items():
if c != b"Deformer" or s != b"Cluster": continue
bone = next((clean(to[k][1]) for k in tkids[u]
if k in to and to[k][0] == b"Model"), None)
g = {ch.name: ch for ch in node.children}
if bone and b"TransformLink" in g and bone not in tl_target:
tl_target[bone] = _mat(rd_array(g[b"TransformLink"].props[0])[0])
if bind == "donor":
tl_target = {} # adopt the donor's bind pose wholesale
elif bind != "self":
tl_target = bind_pose_of(bind) # a third file's, e.g. the species' own
if tl_target:
log.append("目标绑定姿势来源 %s:%d 根骨骼" %
("本片自身" if bind == "self" else os.path.basename(bind), len(tl_target)))
else:
log.append("采用供体的绑定姿势(与供体所属的物种基准一致)")
orphan = {u for u, (c, n, s, _) in to.items()
if c == b"Deformer" and s in (b"Skin", b"Cluster")}
if orphan:
tobj.children = [ch for ch in tobj.children
if not (len(ch.props) >= 3 and sval(ch.props[0]) in orphan)]
tcon.children = [ch for ch in tcon.children
if not ({sval(ch.props[1]), sval(ch.props[2])} & orphan)]
log.append("删除孤儿 %d 个 Deformer 及其连接" % len(orphan))
# 2. name-indexed lookup into the target, for re-pointing --------------
by_name = collections.defaultdict(dict)
for u, (c, n, s, _) in to.items():
by_name[c][clean(n)] = u
# 3. copy the donor's geometry package in, with fresh uids -------------
nxt = max(list(to) + list(do)) + 1000
remap, moved = {}, []
for u, (c, n, s, node) in sorted(do.items()):
if (c, s) in MOVE:
remap[u] = nxt; nxt += 1
moved.append((u, c, n, s, node))
for u, c, n, s, node in moved:
cp = copy_node(node)
cp.props[0] = uid_prop(remap[u])
tobj.children.append(cp)
log.append("移入 %d 个对象: %s" % (len(moved), ", ".join(
"%s::%s" % (clean(c), clean(s)) for _, c, _, s, _ in moved[:3]) + " …"))
# 4. re-point the donor's bind pose at the target's own nodes ----------
dropped_pose = 0
for u, c, n, s, node in moved:
if (c, s) != (b"Pose", b"BindPose"): continue
cp = [x for x in tobj.children if sval(x.props[0]) == remap[u]][0]
keep = []
for pn in cp.children:
if pn.name != b"PoseNode": keep.append(pn); continue
ref = next((ch for ch in pn.children if ch.name == b"Node"), None)
new = ref and translate(sval(ref.props[0]), do, remap, by_name)
if new is None: dropped_pose += 1; continue
ref.props[0] = uid_prop(new); keep.append(pn)
cp.children = keep
for ch in cp.children: # NbPoseNodes must follow
if ch.name == b"Properties70": continue
if ch.name == b"NbPoseNodes":
ch.props[0] = ("I", struct.pack("<i", sum(
1 for x in cp.children if x.name == b"PoseNode")))
# 5. copy the donor's connections, translating both endpoints ---------
added = skipped = 0
for con in connections(dt):
kind, cu, pu = con[0], con[1], con[2]
if not ({cu, pu} & set(remap)): continue # nothing to do with the graft
a = translate(cu, do, remap, by_name)
b = translate(pu, do, remap, by_name)
if a is None or b is None: skipped += 1; continue
n = Node(b"C")
n.props = [("S", kind), uid_prop(a), uid_prop(b)]
if len(con) > 3: n.props.append(("S", con[3]))
tcon.children.append(n); added += 1
log.append("接入 %d 条连接(%d 条无对应端点已跳过,弃用 PoseNode %d 个)"
% (added, skipped, dropped_pose))
# 6. put the mesh back into this clip's own bind pose
if tl_target:
rebind(tt, tl_target, log)
if not had_pose and tl_target:
# the donor's BindPose records the donor's posture; once the mesh has been
# moved somewhere else it is wrong, and this clip shipped without one anyway
gone = {u for u, (c, n, s, _) in objects(tt).items() if c == b"Pose"}
if gone:
tobj.children = [ch for ch in tobj.children
if not (len(ch.props) >= 3 and sval(ch.props[0]) in gone)]
tcon.children = [ch for ch in tcon.children
if not ({sval(ch.props[1]), sval(ch.props[2])} & gone)]
log.append("丢弃供体 BindPose %d 个(本片原本没有,且它记的是供体姿势)" % len(gone))
# 7. collapse the LayeredTexture indirection so importers find the pixels
n_add, n_lay = collapse_layered(tt)
if n_lay:
log.append("压平 %d 个 LayeredTexture,改为 %d 条 Texture→Material 直连" % (n_lay, n_add))
# 8. keep Definitions counts honest -----------------------------------
defs = top(tt, b"Definitions")
if defs:
want = collections.Counter()
for u, (c, n, s, _) in objects(tt).items(): want[c] += 1
for ch in defs.children:
if ch.name != b"ObjectType": continue
k = sval(ch.props[0])
if k in want:
for cc in ch.children:
if cc.name == b"Count":
cc.props[0] = ("I", struct.pack("<i", want[k]))
for ch in defs.children:
if ch.name == b"Count":
ch.props[0] = ("I", struct.pack("<i", sum(want.values())))
if dry: return log, None
data = serialize(tt)
tmp = target_path + ".tmp"
with open(tmp, "wb") as fh: fh.write(data)
os.replace(tmp, target_path) # replaces the name; other hardlinks survive
return log, len(data)
def collapse_layered(tt):
"""Rewire `Texture -> Material` directly, dropping the `LayeredTexture` level.
This clip routes its textures `Video -> Texture -> LayeredTexture -> Material`.
That is legal FBX, but importers that only look for a texture connected straight
to a material property see an untextured mesh — the pixels load and go unused.
It is the only file in the dataset wired this way; the other 1,096 connect
`Texture -> Material` directly, which is what this reproduces.
"""
to, tcon, tobj = objects(tt), top(tt, b"Connections"), top(tt, b"Objects")
layered = {u for u, (c, n, s, _) in to.items() if c == b"LayeredTexture"}
if not layered: return 0, 0
feed = {} # LayeredTexture uid -> Texture uid
for con in connections(tt):
if con[0] == b"OO" and con[2] in layered and to.get(con[1], (b"",))[0] == b"Texture":
feed[con[2]] = con[1]
kept, added = [], 0
for ch in tcon.children:
p = [sval(x) for x in ch.props]
if not ({p[1], p[2]} & layered):
kept.append(ch); continue
if p[1] in layered and len(p) > 3 and to.get(p[2], (b"",))[0] == b"Material" \
and p[1] in feed:
n = Node(b"C")
n.props = [("S", p[0]), uid_prop(feed[p[1]]), uid_prop(p[2]), ("S", p[3])]
kept.append(n); added += 1
tcon.children = kept
tobj.children = [ch for ch in tobj.children
if not (len(ch.props) >= 3 and sval(ch.props[0]) in layered)]
return added, len(layered)
def translate(uid, do, remap, by_name):
"""A donor uid, as it should be referred to inside the target."""
if uid == 0: return 0 # scene root
if uid in remap: return remap[uid] # object we just moved
ent = do.get(uid)
if not ent: return None
cls, nm, sub, _ = ent
return by_name.get(cls, {}).get(clean(nm)) # the target's own by name
# ---------------------------------------------------------------- cli
def main(argv):
if not argv or argv[0] not in ("--selftest", "--donor", "--inspect"):
print(__doc__); return 2
mode, rest = argv[0], argv[1:]
if mode == "--selftest":
bad = 0
for p in rest:
same = serialize(parse(p)) == open(p, "rb").read()
print("%-6s %s" % ("ok" if same else "DIFF", p)); bad += not same
return 1 if bad else 0
if mode == "--inspect":
for p in rest:
i = inspect(p)
print("%-34s verts %-6d idx %-6d geom %d meshnode %d limbs %-3d skin %d cluster %-3d bindpose %d"
% (os.path.basename(p), i["verts"], i["poly_indices"], i["geometry"],
i["model_mesh"], i["limbs"], i["skins"], i["clusters"], i["bindpose"]))
return 0
bind = "donor"
if "--bind" in rest:
i = rest.index("--bind"); bind = rest[i + 1]; rest = rest[:i] + rest[i + 2:]
donor, targets = rest[0], rest[1:]
for t in targets:
for p in (donor, t):
if serialize(parse(p)) != open(p, "rb").read():
print("拒绝执行:%s 无法字节级往返" % p); return 1
before = os.path.getsize(t)
log, size = graft(donor, t, bind=bind)
print("%s ← %s" % (t, donor))
for line in log: print(" " + line)
print(" %d → %d 字节" % (before, size))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))