asset-index / tool /python /hulls.py
anxuanng's picture
Asset index: 37,668 rows from Megascans listings, Poly Haven, ambientCG, Kenney, Quaternius, Smithsonian; optimizer tool
3e8a75e verified
Raw History Blame Contribute Delete
3.32 kB
"""Writes one convex hull collider per object: collision/<id>/<id>_collision.glb, plain glTF, no compression.
Usage: hulls.py <jobs.json> <raw_folder> <collision_folder> [--max-points 64]
The hull is taken over every mesh of the raw GLB in world space, then cut down to at most --max-points vertices by
farthest-point picking and hulled again, so PhysX, Unity (255 vertex cap), Rapier and Jolt take it as one convex
collider. The node carries extras.collision = {"shape": "convex_mesh", "points": n}. Prints one JSON line per object.
Run with python -I; needs trimesh, scipy and numpy.
"""
import json
import sys
from pathlib import Path
import numpy as np
import trimesh
FLAT_THRESHOLD_METRES = 1e-4
SLAB_METRES = 0.01
def farthest_points(points, count):
if len(points) <= count:
return points
chosen = [int(np.argmax(np.linalg.norm(points - points.mean(axis=0), axis=1)))]
distances = np.linalg.norm(points - points[chosen[0]], axis=1)
while len(chosen) < count:
next_index = int(np.argmax(distances))
chosen.append(next_index)
distances = np.minimum(distances, np.linalg.norm(points - points[next_index], axis=1))
return points[chosen]
def hull_for(raw_path, max_points):
scene = trimesh.load(raw_path, force="scene")
meshes = scene.dump(concatenate=False) if isinstance(scene, trimesh.Scene) else [scene]
points = np.concatenate([mesh.vertices for mesh in meshes if len(mesh.vertices)])
extents = points.max(axis=0) - points.min(axis=0)
thin_axis = int(np.argmin(extents))
if extents[thin_axis] < FLAT_THRESHOLD_METRES:
# A flat object (a scanned surface or decal plane) has no volume to hull: give it a slab below its face.
offset = np.zeros(3)
offset[thin_axis] = -SLAB_METRES
points = np.concatenate([points, points + offset])
hull = trimesh.convex.convex_hull(points)
reduced = trimesh.convex.convex_hull(farthest_points(np.asarray(hull.vertices), max_points))
return reduced
def main():
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
jobs_path, raw_folder, collision_folder = sys.argv[1], Path(sys.argv[2]), Path(sys.argv[3])
max_points = int(sys.argv[sys.argv.index("--max-points") + 1]) if "--max-points" in sys.argv else 64
for item in json.loads(Path(jobs_path).read_text(encoding="utf-8")):
output_path = collision_folder / item["id"] / f"{item['id']}_collision.glb"
try:
hull = hull_for(raw_folder / f"{item['id']}.glb", max_points)
output_path.parent.mkdir(parents=True, exist_ok=True)
scene = trimesh.Scene()
scene.add_geometry(hull, node_name=f"{item['id']}_collision", geom_name=f"{item['id']}_hull")
scene.metadata["extras"] = {"collision": {"shape": "convex_mesh", "points": int(len(hull.vertices))}}
scene.export(output_path)
record = {"id": item["id"], "ok": True, "bytes": output_path.stat().st_size, "points": int(len(hull.vertices)), "volume_m3": float(hull.volume)}
except Exception as error: # one broken mesh must not stop the rest
record = {"id": item["id"], "ok": False, "reason": f"{type(error).__name__}: {str(error)[:300]}"}
print(json.dumps(record), flush=True)
if __name__ == "__main__":
main()