filtered-lowpoly-rig / bake_normalize.py
udbbdh's picture
Super-squash branch 'main' using huggingface_hub
8b6d23b
Raw
History Blame Contribute Delete
20.7 kB
#!/usr/bin/env python
"""Bake the wrapper-node normalization of filtered_lowpoly_rig/meshes into
vertex data, writing self-normalized GLBs to meshes_norm/.
Input files are known products of filter_meshes.py: single scene root
"__normalized_root__" with uniform scale s + translation t (no rotation).
We remove the wrapper and bake W = T(t)*S(s) so that spec-correct world-space
output is EXACTLY unchanged while raw accessor data becomes normalized:
node translations *= s (old roots += t) => G' = W * G * D^-1
skinned positions p'' = (W*C) p, C = G_j0*IBM_j0 (any invertible C is
exact): IBM' = D * IBM * C^-1 * W^-1
static non-skinned positions p'' = (W*G_node) p, mesh moved to an identity
root (skipped for meshes on joint/animated nodes: those keep p*=s so they
still follow their node)
animation translation outputs *= s (+t on old roots; CUBICSPLINE tangents
*= s only)
normals by inverse-transpose, tangents by linear part, morph deltas by
linear part; POSITION min/max recomputed.
Per-file fallback scheme A (M = D everywhere, nothing moved) when accessors
are shared across conflicting groups or IBMs are absent/unreadable.
Quantized/sparse POSITION: file copied unchanged with wrapper kept.
Every output is verified: skinning-evaluated world vertices before vs after,
compared per (mesh, primitive).
"""
import json
import os
import struct
import sys
import time
from multiprocessing import Pool
from pathlib import Path
import numpy as np
SRC_DIR = Path("/root/zhaotianhao/filtered_lowpoly_rig/meshes")
DST_DIR = Path("/root/zhaotianhao/filtered_lowpoly_rig/meshes_norm")
REPORT = Path("/root/zhaotianhao/filtered_lowpoly_rig/bake_report.jsonl")
JSON_CHUNK = 0x4E4F534A
BIN_CHUNK = 0x004E4942
FLOAT = 5126
WRAPPER_NAMES = {"__normalized_root__", "__normalize_root__"}
VERIFY_TOL = 5e-3
def read_glb(path):
raw = open(path, "rb").read()
if raw[:4] != b"glTF":
raise ValueError("bad magic")
off = 12
gltf = None
chunks = []
while off + 8 <= len(raw):
cl, ct = struct.unpack_from("<II", raw, off)
payload = raw[off + 8: off + 8 + cl]
if ct == JSON_CHUNK and gltf is None:
gltf = json.loads(payload)
chunks.append([ct, None])
else:
chunks.append([ct, bytearray(payload)])
off += 8 + cl
return gltf, chunks
def write_glb(path, gltf, chunks):
jb = json.dumps(gltf, separators=(",", ":")).encode()
jb += b" " * ((4 - len(jb) % 4) % 4)
body = b""
for ct, payload in chunks:
if ct == JSON_CHUNK and payload is None:
payload = jb
payload = bytes(payload)
if len(payload) % 4:
payload += (b"\x00" if ct == BIN_CHUNK else b" ") * (4 - len(payload) % 4)
body += struct.pack("<II", len(payload), ct) + payload
blob = struct.pack("<4sII", b"glTF", 2, 12 + len(body)) + body
tmp = str(path) + ".part"
with open(tmp, "wb") as f:
f.write(blob)
os.replace(tmp, path)
NCOMP = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT4": 16}
def acc_view(gltf, bin_ba, ai):
acc = gltf["accessors"][ai]
if acc.get("componentType") != FLOAT or "sparse" in acc or "bufferView" not in acc:
return None
n = NCOMP.get(acc.get("type"))
if n is None:
return None
bv = gltf["bufferViews"][acc["bufferView"]]
if bv.get("buffer", 0) != 0:
return None
stride = bv.get("byteStride") or 4 * n
off = bv.get("byteOffset", 0) + acc.get("byteOffset", 0)
count = acc["count"]
if off + (count - 1) * stride + 4 * n > len(bin_ba):
return None
return np.ndarray((count, n), dtype="<f4", buffer=memoryview(bin_ba),
offset=off, strides=(stride, 4))
def node_matrix(node):
if "matrix" in node:
return np.array(node["matrix"], dtype=np.float64).reshape(4, 4).T
m = np.eye(4)
if "rotation" in node:
x, y, z, w = node["rotation"]
nq = x * x + y * y + z * z + w * w
if nq > 1e-12:
f = 2.0 / nq
m[:3, :3] = np.array([
[1 - (y * y + z * z) * f, (x * y - w * z) * f, (x * z + w * y) * f],
[(x * y + w * z) * f, 1 - (x * x + z * z) * f, (y * z - w * x) * f],
[(x * z - w * y) * f, (y * z + w * x) * f, 1 - (x * x + y * y) * f]])
if "scale" in node:
m[:3, :3] = m[:3, :3] * np.asarray(node["scale"], dtype=np.float64)
if "translation" in node:
m[:3, 3] = node["translation"]
return m
def globals_from(gltf, roots):
out = {}
stack = [(r, np.eye(4)) for r in roots]
while stack:
ni, pm = stack.pop()
if ni in out:
continue
g = pm @ node_matrix(gltf["nodes"][ni])
out[ni] = g
for c in gltf["nodes"][ni].get("children", []):
stack.append((c, g))
return out
def scale_node_translation(node, s, add=None):
if "matrix" in node:
mm = list(node["matrix"])
for k in (12, 13, 14):
mm[k] = mm[k] * s
if add is not None:
mm[12] += add[0]; mm[13] += add[1]; mm[14] += add[2]
node["matrix"] = mm
else:
t = [v * s for v in node.get("translation", [0.0, 0.0, 0.0])]
if add is not None:
t = [t[0] + add[0], t[1] + add[1], t[2] + add[2]]
if any(abs(v) > 1e-12 for v in t) or "translation" in node or add is not None:
node["translation"] = t
def world_verts(gltf, bin_ba, roots):
"""Spec-correct world vertices keyed by (mesh, prim). None if unsupported."""
G = globals_from(gltf, roots)
out = {}
for ni in sorted(G):
g = G[ni]
nd = gltf["nodes"][ni]
mi = nd.get("mesh")
if mi is None:
continue
si = nd.get("skin")
for pk, prim in enumerate(gltf["meshes"][mi].get("primitives", [])):
key = (mi, pk)
if key in out:
continue
pa = prim.get("attributes", {}).get("POSITION")
if pa is None:
continue
P = acc_view(gltf, bin_ba, pa)
if P is None:
return None
P = P[:, :3].astype(np.float64)
if si is None:
out[key] = P @ g[:3, :3].T + g[:3, 3]
continue
skin = gltf["skins"][si]
joints = skin["joints"]
ibm_ai = skin.get("inverseBindMatrices")
if ibm_ai is None:
IBM = np.tile(np.eye(4), (len(joints), 1, 1))
else:
raw = acc_view(gltf, bin_ba, ibm_ai)
if raw is None:
return None
IBM = raw.astype(np.float64).reshape(-1, 4, 4).transpose(0, 2, 1)
JM = np.stack([G.get(j, np.eye(4)) @ IBM[k]
for k, j in enumerate(joints)])
ja = prim["attributes"].get("JOINTS_0")
wa = prim["attributes"].get("WEIGHTS_0")
if ja is None or wa is None:
out[key] = P @ g[:3, :3].T + g[:3, 3]
continue
jacc = gltf["accessors"][ja]
jbv = gltf["bufferViews"][jacc["bufferView"]]
dt = {5121: np.uint8, 5123: np.uint16, 5125: np.uint32}.get(
jacc["componentType"])
if dt is None:
return None
isz = np.dtype(dt).itemsize
stride = jbv.get("byteStride") or 4 * isz
off = jbv.get("byteOffset", 0) + jacc.get("byteOffset", 0)
J = np.ndarray((jacc["count"], 4), dtype=dt, buffer=memoryview(bin_ba),
offset=off, strides=(stride, isz)).astype(np.int64)
Wt = acc_view(gltf, bin_ba, wa)
if Wt is None:
return None
Wt = Wt.astype(np.float64)
Wn = Wt / np.maximum(Wt.sum(1, keepdims=True), 1e-9)
J = np.clip(J, 0, len(joints) - 1)
M = (JM[J] * Wn[..., None, None]).sum(1)
hp = np.concatenate([P, np.ones((len(P), 1))], 1)
out[key] = np.einsum("nij,nj->ni", M, hp)[:, :3]
return out
def bake_one(name):
src = SRC_DIR / name
dst = DST_DIR / name
rec = {"file": name}
try:
gltf, chunks = read_glb(src)
bin_ba = next((p for ct, p in chunks if ct == BIN_CHUNK), None)
nodes = gltf["nodes"]
scene = gltf["scenes"][gltf.get("scene", 0)]
sroots = scene.get("nodes", [])
if len(sroots) != 1 or nodes[sroots[0]].get("name") not in WRAPPER_NAMES:
rec.update(status="error", reason="no_wrapper"); return rec
wi = sroots[0]
wrap = nodes[wi]
s = float(wrap.get("scale", [1, 1, 1])[0])
t = np.array(wrap.get("translation", [0, 0, 0]), dtype=np.float64)
old_roots = list(wrap.get("children", []))
W = np.eye(4); W[:3, :3] *= s; W[:3, 3] = t
D = np.eye(4); D[:3, :3] *= s
Dinv = np.eye(4); Dinv[:3, :3] /= s
Winv = np.linalg.inv(W)
v_before = world_verts(gltf, bin_ba, [wi])
G = globals_from(gltf, old_roots)
accessors = gltf["accessors"]
joints_all = set()
for sk in gltf.get("skins", []):
joints_all.update(sk.get("joints", []))
anim_nodes = set()
for anim in gltf.get("animations", []):
for ch in anim.get("channels", []):
tgt = ch.get("target", {})
if tgt.get("path") in ("translation", "rotation", "scale"):
anim_nodes.add(tgt.get("node"))
# nodes whose world transform can change at runtime
dyn = set()
stack = [(r, False) for r in old_roots]
while stack:
ni, flag = stack.pop()
flag = flag or ni in anim_nodes or ni in joints_all
if flag:
dyn.add(ni)
for c in nodes[ni].get("children", []):
stack.append((c, flag))
full_ok = bin_ba is not None
mesh_owner = {} # mesh -> (node, skin, G, movable)
for ni in sorted(G):
nd = nodes[ni]
mi = nd.get("mesh")
if mi is None:
continue
movable = ni not in dyn
if mi in mesh_owner:
p_ni, p_si, p_g, p_mv = mesh_owner[mi]
if p_si != nd.get("skin") or not np.allclose(p_g, G[ni], atol=1e-6):
full_ok = False
mesh_owner[mi] = (p_ni, p_si, p_g, p_mv and movable)
else:
mesh_owner[mi] = (ni, nd.get("skin"), G[ni], movable)
skin_C = {}
if full_ok:
for si, skin in enumerate(gltf.get("skins", [])):
ibm_ai = skin.get("inverseBindMatrices")
raw = acc_view(gltf, bin_ba, ibm_ai) if ibm_ai is not None else None
if raw is None:
full_ok = False; break
j0 = skin["joints"][0]
IBM0 = raw[0].astype(np.float64).reshape(4, 4).T
C = G.get(j0, np.eye(4)) @ IBM0
if not np.all(np.isfinite(C)) or abs(np.linalg.det(C)) < 1e-12:
C = np.eye(4)
skin_C[si] = C
def group_key(mi):
ni, si, g, movable = mesh_owner[mi]
if si is not None:
return ("s", si)
return ("n", ni) if movable else ("d",)
if full_ok:
acc_grp = {}
for mi in mesh_owner:
key = group_key(mi)
for prim in gltf["meshes"][mi].get("primitives", []):
sets = [prim.get("attributes", {})] + prim.get("targets", [])
for aset in sets:
for an in ("POSITION", "NORMAL", "TANGENT"):
ai = aset.get(an)
if ai is None:
continue
if acc_grp.get(ai, key) != key:
full_ok = False
acc_grp[ai] = key
pa = prim.get("attributes", {}).get("POSITION")
if pa is not None and acc_view(gltf, bin_ba, pa) is None:
rec.update(status="kept_wrapper",
reason="unbakeable_positions")
write_glb(dst, gltf, chunks)
return rec
scheme = "full" if full_ok else "A"
# ---- 1. node translations ----
for ni in G:
scale_node_translation(nodes[ni], s,
add=t.tolist() if ni in old_roots else None)
# ---- 2. vertex data ----
done_acc = set()
for mi, (ni, si, g, movable) in mesh_owner.items():
if scheme == "full":
if si is not None:
M = W @ skin_C[si]
elif movable:
M = W @ g
else:
M = D
else:
M = D
L = M[:3, :3]
if abs(np.linalg.det(L)) < 1e-15:
# degenerate node transform: keep mesh in place, scale only
M = D
L = M[:3, :3]
mesh_owner[mi] = (ni, si, g, False)
Mt = M[:3, 3]
it = np.linalg.inv(L).T
for prim in gltf["meshes"][mi].get("primitives", []):
attrs = prim.get("attributes", {})
sets = [(attrs, False)] + [(tg, True) for tg in prim.get("targets", [])]
for aset, is_delta in sets:
for an in ("POSITION", "NORMAL", "TANGENT"):
ai = aset.get(an)
if ai is None or ai in done_acc:
continue
done_acc.add(ai)
V = acc_view(gltf, bin_ba, ai)
if V is None:
continue
if an == "POSITION":
X = V[:, :3].astype(np.float64) @ L.T
if not is_delta:
X = X + Mt
V[:, :3] = X.astype(np.float32)
acc = accessors[ai]
acc["min"] = np.min(V[:, :3], 0).astype(float).tolist()
acc["max"] = np.max(V[:, :3], 0).astype(float).tolist()
elif scheme == "full":
R3 = it if an == "NORMAL" else L
X = V[:, :3].astype(np.float64) @ R3.T
nn = np.linalg.norm(X, axis=1, keepdims=True)
V[:, :3] = (X / np.maximum(nn, 1e-12)).astype(np.float32)
# ---- 3. IBMs ----
for si, skin in enumerate(gltf.get("skins", [])):
ibm_ai = skin.get("inverseBindMatrices")
if ibm_ai is None:
if scheme == "full":
rec.update(status="error", reason="ibm_missing_full"); return rec
continue
raw = acc_view(gltf, bin_ba, ibm_ai)
if raw is None:
rec.update(status="error", reason="ibm_unreadable"); return rec
R = (np.linalg.inv(skin_C[si]) @ Winv) if scheme == "full" else Dinv
for k in range(len(raw)):
ib = raw[k].astype(np.float64).reshape(4, 4).T
raw[k] = (D @ ib @ R).T.reshape(16).astype(np.float32)
# ---- 4. animation translation outputs ----
anim_shared = False
out_rule = {}
for anim in gltf.get("animations", []):
samplers = anim.get("samplers", [])
for ch in anim.get("channels", []):
tgt = ch.get("target", {})
if tgt.get("path") != "translation":
continue
sm = samplers[ch["sampler"]]
rule = (tgt.get("node") in old_roots,
sm.get("interpolation") == "CUBICSPLINE")
oa = sm["output"]
if out_rule.get(oa, rule) != rule:
anim_shared = True
out_rule[oa] = rule
for oa, (is_root, cubic) in out_rule.items():
V = acc_view(gltf, bin_ba, oa)
if V is None:
continue
V[:] = V[:] * s
if is_root:
if cubic:
V[1::3, :3] += t.astype(np.float32)
else:
V[:, :3] += t.astype(np.float32)
# ---- 5. restructure scene ----
new_roots = list(old_roots)
if scheme == "full":
parent = {}
for ni in G:
for c in nodes[ni].get("children", []):
parent[c] = ni
newG = globals_from(gltf, old_roots)
for mi, (ni, si, g, movable) in mesh_owner.items():
if si is None and movable:
for nj in G:
if nodes[nj].get("mesh") == mi:
nodes[nj].pop("mesh", None)
nodes.append({"name": "baked_mesh_%d" % mi, "mesh": mi})
new_roots.append(len(nodes) - 1)
elif (si is not None and not nodes[ni].get("children")
and ni not in joints_all and ni not in anim_nodes):
pg = newG.get(parent.get(ni), np.eye(4)) if ni in parent \
else np.eye(4)
try:
inv = np.linalg.inv(pg)
except np.linalg.LinAlgError:
continue
nd = nodes[ni]
for k in ("matrix", "translation", "rotation", "scale"):
nd.pop(k, None)
if not np.allclose(inv, np.eye(4), atol=1e-9):
nd["matrix"] = inv.T.reshape(16).tolist()
scene["nodes"] = new_roots
wrap.pop("children", None)
wrap.pop("scale", None)
wrap.pop("translation", None)
if wi == len(nodes) - 1:
nodes.pop()
# ---- verify ----
v_after = world_verts(gltf, bin_ba, new_roots)
err = None
if v_before is not None and v_after is not None:
errs = [float(np.abs(v_before[k] - v_after[k]).max())
for k in v_before if k in v_after
and v_before[k].shape == v_after[k].shape]
if len(errs) != len(v_before) or len(v_before) != len(v_after):
rec.update(status="error", reason="verify_key_mismatch"); return rec
err = max(errs) if errs else 0.0
if err > VERIFY_TOL:
rec.update(status="error", reason="verify_failed", max_err=err)
return rec
lo = hi = None
if v_after:
allv = np.concatenate(list(v_after.values()), 0)
lo, hi = float(allv.min()), float(allv.max())
write_glb(dst, gltf, chunks)
rec.update(status="ok", scheme=scheme, max_err=err,
anim_shared=anim_shared, world_min=lo, world_max=hi)
return rec
except Exception as e: # noqa: BLE001
rec.update(status="error", reason="exc:%s:%s" % (type(e).__name__, e))
return rec
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--workers", type=int, default=16)
args = ap.parse_args()
DST_DIR.mkdir(parents=True, exist_ok=True)
names = sorted(os.listdir(SRC_DIR))
done = set(os.listdir(DST_DIR))
todo = [n for n in names if n not in done and n.endswith(".glb")]
if args.limit:
todo = todo[: args.limit]
print("[bake] %d total, %d todo" % (len(names), len(todo)), flush=True)
stats = {}
t0 = time.time()
with open(REPORT, "a") as rep, Pool(args.workers) as pool:
for i, rec in enumerate(pool.imap_unordered(bake_one, todo, chunksize=8), 1):
key = rec["status"] + (":" + rec.get("reason", "") if rec["status"] == "error"
else ":" + rec.get("scheme", rec.get("reason", "")))
stats[key] = stats.get(key, 0) + 1
if rec["status"] != "ok" or i % 2000 == 0:
rep.write(json.dumps(rec) + "\n")
rep.flush()
if i % 2000 == 0:
print("[bake] %d/%d (%.0f/s) %s" % (
i, len(todo), i / max(time.time() - t0, 1e-9), stats), flush=True)
print("[bake] DONE %s" % stats, flush=True)
if __name__ == "__main__":
sys.exit(main())