#!/usr/bin/env python3 """Index ../animation/ and map every source clip onto it. `animation/` is the dataset: one FBX per distinct motion, each holding exactly one take. Everything reported about the library is measured there, so this script writes the two tables that describe it — animation.csv one row per clip in animation/ species.csv one row per species, aggregated from animation.csv animation_frames.json clip -> frame count animation_bones.json species -> its joint names — and fills two columns in `clips.csv` that say, for every file in `Truebone_Z-OO/`, which animation clip carries its motion and why it is not itself in the set: animation_file the clip in animation/ that holds this motion status linked | mirror | duplicate | combined | combined_only | static | orphan A source clip is `linked` when animation/ holds that exact file, `mirror` when it is the BVH export of a clip already there, `duplicate` when the source shipped the same motion twice under two names, `combined` for a group's `ALL` file, `static` when it carries no motion at all (every T-pose, plus model-only exports), and `orphan` for a rig that belongs to no group. `combined_only` marks the one motion the library ships with no standalone FBX of its own — `Lynx/Idle4`, which exists as a BVH and as a take inside `LynxALL.fbx` and nowhere else. Cutting it out would mean re-exporting it, and a round trip through an editor rebuilds the rest pose from the first frame, so the clip would no longer share its species' skeleton. It stays where the source put it. Source clips are matched to animation clips by name first, then by content: same species and the same length to within a frame, confirmed curve by curve for FBX. That second pass is what pairs the BVH exports, whose names do not always agree with their FBX twins (`__BearRun.bvh` against `BEAR-BearRun.fbx`). """ import collections, csv, json, os, sys HERE = os.path.dirname(os.path.abspath(__file__)) SCRIPTS = os.path.dirname(HERE) ROOT = os.path.dirname(SCRIPTS) sys.path[:0] = [HERE, os.path.join(SCRIPTS, "probes")] from fbx_probe import probe as fbx_probe from fbx_takes import probe as takes_probe from fbx_stacks import takes_with_motion from fbx_curves import same_motion import normalize as N ANIM = os.path.join(ROOT, "animation") ANIM_COLS = ["file", "species", "action", "take", "num_takes", "num_actions", "num_joints", "root_joint", "frames", "fps", "duration_sec", "fbx_version", "bytes", "num_source_files"] SPECIES_COLS = ["species", "num_clips", "num_joints", "rig_variants", "root_joint", "total_frames", "total_duration_sec", "mean_duration_sec", "num_textures", "source_fbx", "source_bvh", "has_combined_all", "has_tpose"] def index_animation(clip_joints): rows = [] for f in sorted(os.listdir(ANIM)): if not f.endswith(".fbx"): continue p = os.path.join(ANIM, f) species, action = os.path.splitext(f)[0].split("-", 1) x, t = fbx_probe(p), takes_probe(p) clip_joints[f] = x["joints"] rows.append({ "file": "animation/" + f, "species": species, "action": action, "take": t["takes"][0][0] if t["takes"] else "", "num_takes": t["num_takes"], "num_actions": takes_with_motion(p), "num_joints": x["num_joints"], "root_joint": x["root_joint"], "frames": x["keyframes"], "fps": x["fps"], "duration_sec": x["duration_sec"], "fbx_version": x["fbx_version"], "bytes": os.path.getsize(p), "num_source_files": 0, }) return rows def normalized_names(clips): """(species, action) for every source row, under the naming rules of normalize.py.""" rows = sorted(clips, key=lambda r: r["file"]) alias = N.infer_aliases(rows) prelim = [N.norm_action(os.path.splitext(os.path.basename(r["file"]))[0], r["group"], alias, r["format"]) for r in rows] canon = N.canonical_case(prelim) return {r["file"]: (N.norm_species(r["group"]), N.mixamo_style(canon[a.lower()])) for r, a in zip(rows, prelim)} def main(): clip_joints = {} anim = index_animation(clip_joints) by_name = {(r["species"], r["action"]): r for r in anim} by_species = collections.defaultdict(list) for r in anim: by_species[r["species"]].append(r) clips = list(csv.DictReader(open(os.path.join(ROOT, "clips.csv")))) names = normalized_names(clips) # build_dataset.py leaves fps/duration/root empty for FBX rows because its # first pass reads headers only. Fill them here, where the key times are # decoded anyway. for r in clips: if r["format"] != "fbx" or r["fps"]: continue try: x = fbx_probe(os.path.join(ROOT, r["file"])) except Exception: continue r["fps"] = x["fps"] or "" r["duration_sec"] = x["duration_sec"] or "" r["root_joint"] = x["root_joint"] unmatched = [] for r in clips: sp, act = names[r["file"]] r["animation_file"], r["status"] = "", "" # The exact file animation/ holds. `normalized_name` is not always # `-.fbx`: three clips carry a `_2` suffix so that two # names differing only in case can coexist on this filesystem. if r.get("normalized_name"): target = "animation/" + r["normalized_name"] if os.path.exists(os.path.join(ROOT, target)): r["animation_file"], r["status"] = target, "linked" continue if r["file"] in N.EXCLUDE_SOURCES: r["status"] = "orphan"; continue # Order matters: 21 groups ship a bind-pose model named after the species # alone, which normalizes to `ALL` but holds no take at all. # A T-pose is a rest pose whatever its curves say — one of them drifts by # a degree over its 60 frames, which is motion by measurement and nothing # by intent — so the name decides here, not `has_motion`. if r["has_motion"] != "true" or act == "TPOSE": r["status"] = "static"; continue if act == "ALL": r["status"] = "combined"; continue # Same motion under another name, or the BVH twin of an FBX already in the # set: same species, same length to within a frame. Several candidates are # ranked by how close the action names are, and an FBX match is confirmed # curve by curve before it is accepted. want = int(r["frames"] or 0) cands = [a for a in by_species.get(sp, []) if abs(a["frames"] - want) <= 1] if (sp, act) in by_name: cands = [by_name[(sp, act)]] + [c for c in cands if c is not by_name[(sp, act)]] hit = "" for c in cands: if r["format"] == "fbx": ok, _ = same_motion(os.path.join(ROOT, r["file"]), os.path.join(ROOT, c["file"])) if not ok: continue hit = c["file"]; break if hit: r["animation_file"] = hit r["status"] = "mirror" if r["format"] == "bvh" else "duplicate" else: r["status"] = "combined_only" unmatched.append((r["file"], sp, act, want)) counts = collections.Counter(r["animation_file"] for r in clips if r["animation_file"]) for a in anim: a["num_source_files"] = counts.get(a["file"], 0) tex, src_fbx, src_bvh, tpose, comb = (collections.Counter() for _ in range(5)) for r in clips: sp, act = names[r["file"]] (src_fbx if r["format"] == "fbx" else src_bvh)[sp] += 1 if act == "TPOSE": tpose[sp] += 1 if r["status"] == "combined": comb[sp] += 1 for dp, dn, fn in os.walk(os.path.join(ROOT, "Truebone_Z-OO")): for f in fn: if os.path.splitext(f)[1].lower() in (".jpg", ".jpeg", ".png", ".tga"): tex[N.norm_species(os.path.relpath(dp, os.path.join(ROOT, "Truebone_Z-OO")).split(os.sep)[0])] += 1 species = [] for sp in sorted(by_species): cs = by_species[sp] dur = sum(c["duration_sec"] for c in cs) joints = sorted({c["num_joints"] for c in cs}) roots = sorted({c["root_joint"] for c in cs}) variants = len({tuple(clip_joints[c["file"].split("/")[-1]]) for c in cs}) species.append({ "species": sp, "num_clips": len(cs), "rig_variants": variants, "num_joints": joints[0] if len(joints) == 1 else "|".join(map(str, joints)), "root_joint": roots[0] if len(roots) == 1 else "|".join(roots), "total_frames": sum(c["frames"] for c in cs), "total_duration_sec": round(dur, 3), "mean_duration_sec": round(dur / len(cs), 3), "num_textures": tex.get(sp, 0), "source_fbx": src_fbx.get(sp, 0), "source_bvh": src_bvh.get(sp, 0), "has_combined_all": str(comb.get(sp, 0) > 0).lower(), "has_tpose": str(tpose.get(sp, 0) > 0).lower(), }) def write(name, cols, rows): with open(os.path.join(ROOT, name), "w", newline="", encoding="utf-8") as fh: w = csv.DictWriter(fh, fieldnames=cols, extrasaction="ignore") w.writeheader(); w.writerows(rows) print("%-16s -> %d rows" % (name, len(rows))) # The two per-clip sidecars, shaped like the Mixamo set's: a flat map from # filename to one value, sorted by key. frames = {r["file"].split("/")[-1]: r["frames"] for r in anim} # A species' joint list is the one its clips most often have — a real rig, not # a pooled vocabulary. Pooling looked tidier but produced a list that matched # no actual file: `Monkey` clips carry 88 joints each and the union ran to 91, # because every clip names the container node of the mesh variant it was # exported with (`Monkey_A01` against `Monkey_B02`). seen = collections.defaultdict(collections.Counter) for r in anim: seen[r["species"]][tuple(clip_joints[r["file"].split("/")[-1]])] += 1 bones = {sp: list(c.most_common(1)[0][0]) for sp, c in seen.items()} def dump(name, obj): with open(os.path.join(ROOT, name), "w", encoding="utf-8") as fh: json.dump(obj, fh, indent=1, ensure_ascii=False) print("%-22s -> %d keys" % (name, len(obj))) dump("animation_frames.json", {k: frames[k] for k in sorted(frames)}) dump("animation_bones.json", {k: sorted(bones[k]) for k in sorted(bones)}) write("animation.csv", ANIM_COLS, anim) write("species.csv", SPECIES_COLS, species) cols = [c for c in clips[0] if c not in ("animation_file", "status")] + ["animation_file", "status"] write("clips.csv", cols, clips) st = collections.Counter(r["status"] for r in clips) print("\nstatus:", dict(st)) print("animation clips with no source row:", sum(1 for a in anim if a["num_source_files"] == 0), [a["file"] for a in anim if a["num_source_files"] == 0]) print("source clips with motion and no clip of their own:", len(unmatched)) for u in unmatched[:20]: print(" ", u) if __name__ == "__main__": main()