#!/usr/bin/env python # -*- coding: utf-8 -*- """ Filter rigged low-poly meshes from multiple datasets. A .glb is kept only if ALL of: - valid glTF 2.0 binary - has skins with joints, and at least one scene-reachable node binds mesh+skin - total vertex count of scene-reachable meshes < 10000 Kept meshes are normalized into [-0.5, 0.5]^3 by inserting a wrapper root node (uniform scale + translation) into the scene graph. This preserves skeleton / skin / animation data exactly (a re-export through trimesh would drop them). Dedup: exact file sha256 + geometry hash over POSITION/JOINTS_0/WEIGHTS_0 buffer bytes. Sources are opened read-only; all output goes under OUT_ROOT. Resumable: paths already listed in processed.log are skipped on restart. Run: python filter_meshes.py [--limit-per-source N] """ import argparse import hashlib import itertools import json import os import struct import sys import time from collections import Counter from multiprocessing import Pool from pathlib import Path import numpy as np # highest priority first: when duplicates exist, the earlier source wins SOURCES = [ ("dataset_rig", "/root/zhaotianhao/dataset_rig"), ("canoverse", "/root/youjiaZhang/topotex_data_CanoVerse/raw"), ("objaverse_xl", "/root/dataset/dataset.2/objaverse-xl/hf-objaverse-v1/glbs"), ] OUT_ROOT = Path("/root/zhaotianhao/filtered_lowpoly_rig") MESH_DIR = OUT_ROOT / "meshes" TMP_DIR = OUT_ROOT / "tmp" MANIFEST = OUT_ROOT / "manifest.jsonl" PROCESSED = OUT_ROOT / "processed.log" STATS = OUT_ROOT / "stats.json" MAX_VERTS = 10000 # strict: keep only n_verts < MAX_VERTS NORM_HALF = 0.5 # normalize longest axis into [-NORM_HALF, NORM_HALF] MAX_FILE_BYTES = 300 << 20 # skip pathological files WORKERS = 24 MESH_EXTS = {".glb", ".gltf", ".vrm", ".fbx", ".obj", ".dae", ".ply", ".stl"} CHUNK_JSON = 0x4E4F534A CHUNK_BIN = 0x004E4942 def _quat_to_mat(x, y, z, w): n = x * x + y * y + z * z + w * w if n < 1e-12: return np.eye(3) s = 2.0 / n xx, yy, zz = x * x * s, y * y * s, z * z * s xy, xz, yz = x * y * s, x * z * s, y * z * s wx, wy, wz = w * x * s, w * y * s, w * z * s return np.array([ [1 - (yy + zz), xy - wz, xz + wy], [xy + wz, 1 - (xx + zz), yz - wx], [xz - wy, yz + wx, 1 - (xx + yy)], ]) 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 "scale" in node: m[:3, :3] = np.diag(node["scale"]) if "rotation" in node: x, y, z, w = node["rotation"] m[:3, :3] = _quat_to_mat(x, y, z, w) @ m[:3, :3] if "translation" in node: m[:3, 3] = node["translation"] return m def _reject(rec, reason, **extra): rec.update(status="reject", reason=reason, **extra) return rec def process_one(task): tag, path = task rec = {"src": path, "tag": tag} try: return _process_one(tag, path, rec) except Exception as e: # noqa: BLE001 - any parse failure is a data reject return _reject(rec, "error:%s" % type(e).__name__) def _process_one(tag, path, rec): ext = os.path.splitext(path)[1].lower() if ext != ".glb": # .obj cannot embed skin/skeleton; .fbx would need blender (unavailable) return _reject(rec, "non_glb:%s" % ext.lstrip(".")) size = os.path.getsize(path) if size > MAX_FILE_BYTES: return _reject(rec, "too_large") fhash = hashlib.sha256() with open(path, "rb") as f: hdr = f.read(12) if len(hdr) < 12 or hdr[:4] != b"glTF": return _reject(rec, "bad_magic") version, _total = struct.unpack("= MAX_VERTS: return _reject(rec, "too_many_verts", n_verts=n_verts) # ---------- world bbox from accessor min/max ---------- mn = np.full(3, np.inf) mx = np.full(3, -np.inf) for ni, wm in mesh_nodes: mi = nodes[ni]["mesh"] if not (0 <= mi < len(meshes)): continue for prim in meshes[mi].get("primitives") or []: pa = (prim.get("attributes") or {}).get("POSITION") if pa is None or not (0 <= pa < len(accessors)): continue acc = accessors[pa] amn, amx = acc.get("min"), acc.get("max") if not amn or not amx or len(amn) < 3 or len(amx) < 3: return _reject(rec, "missing_bounds") cs = np.array(list(itertools.product( (amn[0], amx[0]), (amn[1], amx[1]), (amn[2], amx[2])))) cs4 = np.hstack([cs, np.ones((8, 1))]) w = (wm @ cs4.T).T[:, :3] mn = np.minimum(mn, w.min(axis=0)) mx = np.maximum(mx, w.max(axis=0)) extent = mx - mn max_extent = float(np.max(extent)) if not np.isfinite(max_extent) or max_extent <= 1e-9: return _reject(rec, "degenerate_bbox") scale = (2.0 * NORM_HALF) / max_extent center = (mn + mx) / 2.0 # ---------- read remaining chunks, hash file ---------- fhash.update(hdr) fhash.update(ch) fhash.update(raw_json) rest = [] while True: h = f.read(8) if len(h) < 8: break fhash.update(h) cl, ct = struct.unpack("