Download 4dcodebench/resim/resim_blender.py from AIGeeksGroup/PhysicalWM: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/datasets/AIGeeksGroup/PhysicalWM/resolve/main/4dcodebench/resim/resim_blender.py
- Command line
-
hf download hf://datasets/AIGeeksGroup/PhysicalWM/4dcodebench/resim/resim_blender.py
-
curl -L -o resim_blender.py https://huggingface.co/datasets/AIGeeksGroup/PhysicalWM/resolve/main/4dcodebench/resim/resim_blender.py
11.3 kB
| #!/usr/bin/env python | |
| """Re-simulate a 4DCodeBench rigid-body world in Blender with a chosen parameter card. | |
| Run inside Blender (background): | |
| blender --background --python resim_blender.py -- \ | |
| --world work/B_03/world --out work/B_03/out_p1 --kinematic Ball \ | |
| --friction 0.5 --restitution 0.05 --mass 1.5 --samples 32 | |
| Split (verified on B_03): | |
| * static meshes -> passive rigid bodies, exact geometry, collision as-is | |
| * the --kinematic group -> passive+kinematic body replaying the baked trajectory | |
| (the driver; identical impact conditions in every preset) | |
| * every other dynamics group -> active rigid body spawned at its frame-0 pose with | |
| the parameter card (this is what we sweep) | |
| Output: <out>/sim.mp4, <out>/simtraj.npz (per-object mean-vertex positions, (F,3)) | |
| """ | |
| import argparse | |
| import json | |
| import sys | |
| from math import radians | |
| from pathlib import Path | |
| import bpy | |
| import numpy as np | |
| from mathutils import Matrix, Vector | |
| def parse_args(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--world", required=True) | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--preset", default="p") | |
| ap.add_argument("--kinematic", default=None, help="dynamics group name to replay as driver") | |
| ap.add_argument("--friction", type=float, default=0.5) | |
| ap.add_argument("--restitution", type=float, default=0.05) | |
| ap.add_argument("--mass", type=float, default=1.5) | |
| ap.add_argument("--lin_damp", type=float, default=0.04) | |
| ap.add_argument("--ang_damp", type=float, default=0.04) | |
| ap.add_argument("--samples", type=int, default=32) | |
| ap.add_argument("--substeps", type=int, default=20) | |
| ap.add_argument("--iters", type=int, default=20) | |
| ap.add_argument("--device", default="gpu", choices=["gpu", "cpu"]) | |
| return ap.parse_args(sys.argv[sys.argv.index("--") + 1:]) | |
| def rigid_tf(A, B): | |
| """Least-squares rigid transform mapping A -> B (both (N,3)).""" | |
| ca, cb = A.mean(0), B.mean(0) | |
| H = (A - ca).T @ (B - cb) | |
| U, _, Vt = np.linalg.svd(H) | |
| D = np.diag([1.0, 1.0, float(np.sign(np.linalg.det(Vt.T @ U.T)))]) | |
| R = Vt.T @ D @ U.T | |
| return R, cb - R @ ca | |
| def add_mesh(name, verts, faces, mat=None): | |
| me = bpy.data.meshes.new(name) | |
| me.from_pydata([tuple(float(x) for x in v) for v in verts], [], | |
| [tuple(int(x) for x in f) for f in faces]) | |
| me.update() | |
| ob = bpy.data.objects.new(name, me) | |
| bpy.context.scene.collection.objects.link(ob) | |
| if mat is not None: | |
| ob.data.materials.append(mat) | |
| return ob | |
| def add_rb(ob, rbtype, shape, mass=1.0, friction=0.5, restitution=0.5, | |
| lin_damp=0.04, ang_damp=0.04, kinematic=False, margin=0.001): | |
| # deselect everything first: the operator acts on ALL selected objects | |
| for other in bpy.context.selected_objects: | |
| other.select_set(False) | |
| bpy.context.view_layer.objects.active = ob | |
| ob.select_set(True) | |
| try: | |
| bpy.ops.rigidbody.objects_add(type=rbtype) | |
| except RuntimeError: | |
| with bpy.context.temp_override(active_object=ob, object=ob, | |
| selected_objects=[ob], | |
| selected_editable_objects=[ob]): | |
| bpy.ops.rigidbody.objects_add(type=rbtype) | |
| rb = ob.rigid_body | |
| rb.collision_shape = shape | |
| rb.mass = mass | |
| rb.friction = friction | |
| rb.restitution = restitution | |
| rb.linear_damping = lin_damp | |
| rb.angular_damping = ang_damp | |
| rb.use_margin = True | |
| rb.collision_margin = margin | |
| rb.kinematic = kinematic | |
| return rb | |
| def mat_simple(name, rgb): | |
| m = bpy.data.materials.new(name) | |
| m.use_nodes = True | |
| bsdf = m.node_tree.nodes["Principled BSDF"] | |
| bsdf.inputs["Base Color"].default_value = (*rgb, 1.0) | |
| bsdf.inputs["Roughness"].default_value = 0.6 | |
| return m | |
| def setup_cycles(scene, samples, use_gpu): | |
| scene.render.engine = "CYCLES" | |
| if use_gpu: | |
| prefs = bpy.context.preferences.addons["cycles"].preferences | |
| for ctype in ("OPTIX", "CUDA"): | |
| try: | |
| prefs.compute_device_type = ctype | |
| prefs.get_devices() | |
| devs = [d for d in prefs.devices if d.type == ctype] | |
| if devs: | |
| for d in prefs.devices: | |
| d.use = d.type == ctype | |
| scene.cycles.device = "GPU" | |
| print(f"[cycles] using {ctype}: {[d.name for d in devs]}") | |
| return | |
| except Exception as e: | |
| print(f"[cycles] {ctype} failed: {e}") | |
| print("[cycles] no GPU backend, falling back to CPU") | |
| scene.cycles.device = "CPU" | |
| def main(): | |
| args = parse_args() | |
| world = Path(args.world) | |
| out = Path(args.out) | |
| out.mkdir(parents=True, exist_ok=True) | |
| spec = json.loads((world / "spec.json").read_text()) | |
| cam = json.loads((world / "camera.json").read_text()) | |
| K = np.array(cam["intrinsics"], float) | |
| E = np.array(cam["extrinsic"], float) | |
| F = int(spec["F"]) | |
| W, H = spec["video"]["width"], spec["video"]["height"] | |
| fps = float(spec["video"]["fps"]) | |
| # ---------- clean scene ---------- | |
| scene = bpy.context.scene | |
| for ob in list(bpy.data.objects): | |
| bpy.data.objects.remove(ob, do_unlink=True) | |
| mats = {"ball": mat_simple("m_ball", (0.10, 0.25, 0.75)), | |
| "pin": mat_simple("m_pin", (0.92, 0.92, 0.90)), | |
| "deck": mat_simple("m_deck", (0.25, 0.15, 0.10)), | |
| "static": mat_simple("m_static", (0.55, 0.55, 0.58))} | |
| # ---------- rigid body world ---------- | |
| if scene.rigidbody_world is None: | |
| bpy.ops.rigidbody.world_add() | |
| rbw = scene.rigidbody_world | |
| rbw.substeps_per_frame = args.substeps | |
| rbw.solver_iterations = args.iters | |
| rbw.point_cache.frame_start = 1 | |
| rbw.point_cache.frame_end = F | |
| scene.gravity = (0.0, 0.0, -9.81) | |
| dyn = {} | |
| for name in spec["dynamics"]: | |
| z = np.load(world / "dyn" / f"{name}.npz") | |
| dyn[name] = {"pos": z["pos"], "ids": z["ids"].tolist()} | |
| kin_name = args.kinematic or next(iter(dyn)) | |
| active_names = [n for n in dyn if n != kin_name] | |
| static_ids = [int(m) for m, v in spec["meshes"].items() if v["static"]] | |
| # ---------- static geometry ---------- | |
| for mid in static_ids: | |
| z = np.load(world / "mesh" / f"{mid}.npz") | |
| mat = mats["deck"] if z["vertices"].shape[1] <= 4 else mats["static"] | |
| ob = add_mesh(f"static_{mid}", z["vertices"][0], z["faces"][0], mat) | |
| add_rb(ob, "PASSIVE", "MESH", margin=0.001) | |
| # ---------- kinematic driver (replay baked trajectory) ---------- | |
| driver_pos = dyn[kin_name]["pos"] # (F,N,3) | |
| drv_ids = dyn[kin_name]["ids"] | |
| z = np.load(world / "mesh" / f"{drv_ids[0]}.npz") | |
| drv_ob = add_mesh(kin_name, z["vertices"][0], z["faces"][0], mats["ball"]) | |
| drv_verts0 = z["vertices"][0].astype(np.float64) | |
| for t in range(F): | |
| R, tt = rigid_tf(driver_pos[0].astype(np.float64), driver_pos[t].astype(np.float64)) | |
| drv_ob.location = Vector(tt) | |
| drv_ob.rotation_euler = Matrix(R).to_euler() | |
| drv_ob.keyframe_insert("location", frame=t + 1) | |
| drv_ob.keyframe_insert("rotation_euler", frame=t + 1) | |
| for fc in drv_ob.animation_data.action.fcurves: | |
| for kp in fc.keyframe_points: | |
| kp.interpolation = "LINEAR" | |
| add_rb(drv_ob, "PASSIVE", "CONVEX_HULL", kinematic=True, margin=0.002) | |
| # ---------- active bodies (parameter card) ---------- | |
| actives = {} | |
| for name in active_names: | |
| ids = dyn[name]["ids"] | |
| z = np.load(world / "mesh" / f"{ids[0]}.npz") | |
| ob = add_mesh(name, z["vertices"][0], z["faces"][0], mats["pin"]) | |
| add_rb(ob, "ACTIVE", "CONVEX_HULL", mass=args.mass, friction=args.friction, | |
| restitution=args.restitution, lin_damp=args.lin_damp, | |
| ang_damp=args.ang_damp, margin=0.001) | |
| actives[name] = (ob, z["vertices"][0].astype(np.float64)) | |
| # ---------- camera ---------- | |
| print("[rb-check] " + ", ".join( | |
| f"{o.name}:{o.rigid_body.type}{'/K' if o.rigid_body.kinematic else ''}" | |
| for o in bpy.data.objects if o.rigid_body)) | |
| cam_data = bpy.data.cameras.new("cam") | |
| cam_data.sensor_fit = "HORIZONTAL" | |
| cam_data.sensor_width = 36.0 | |
| cam_data.lens = float(K[0, 0]) * 36.0 / W | |
| cam_ob = bpy.data.objects.new("cam", cam_data) | |
| bpy.context.scene.collection.objects.link(cam_ob) | |
| D = Matrix.Diagonal((1.0, -1.0, -1.0, 1.0)) # cam axes (x right, y down, z fwd) -> Blender (-Z fwd) | |
| cam_ob.matrix_world = Matrix(E) @ D | |
| scene.camera = cam_ob | |
| # camera sanity: project driver COM at frame 0 both ways | |
| p0 = Vector(driver_pos[0].mean(0)) | |
| import bpy_extras | |
| uv = bpy_extras.object_utils.world_to_camera_view(scene, cam_ob, p0) | |
| pc = E[:3, :3].T @ (np.asarray(p0) - E[:3, 3]) | |
| proj = K @ pc | |
| u_px, v_px = float(proj[0]) / float(pc[2]), float(proj[1]) / float(pc[2]) | |
| print(f"[cam-check] blender uv=({uv.x:.3f},{uv.y:.3f}) numpy px=({u_px:.1f},{v_px:.1f})/" | |
| f"({W},{H}) expect uv≈({u_px/W:.3f},{1-v_px/H:.3f})") | |
| # ---------- lights ---------- | |
| world = bpy.data.worlds.new("w") | |
| world.use_nodes = True | |
| world.node_tree.nodes["Background"].inputs["Color"].default_value = (0.85, 0.85, 0.85, 1) | |
| world.node_tree.nodes["Background"].inputs["Strength"].default_value = 1.1 | |
| scene.world = world | |
| sun = bpy.data.lights.new("sun", type="SUN") | |
| sun.energy = 3.0 | |
| sun_ob = bpy.data.objects.new("sun", sun) | |
| bpy.context.scene.collection.objects.link(sun_ob) | |
| sun_ob.rotation_euler = (radians(50), 0, radians(30)) | |
| # ---------- bake ---------- | |
| scene.frame_start = 1 | |
| scene.frame_end = F | |
| scene.frame_set(1) | |
| bpy.ops.ptcache.free_bake_all() | |
| bpy.ops.ptcache.bake_all(bake=True) | |
| print("[bake] done") | |
| # ---------- record trajectories ---------- | |
| traj = {kin_name: np.zeros((F, 3), np.float32)} | |
| for name, (ob, v0) in actives.items(): | |
| traj[name] = np.zeros((F, 3), np.float32) | |
| for t in range(1, F + 1): | |
| scene.frame_set(t) | |
| bpy.context.view_layer.update() | |
| M = np.array(drv_ob.matrix_world) | |
| traj[kin_name][t - 1] = (M[:3, :3] @ drv_verts0.T).T.mean(0) | |
| for name, (ob, v0) in actives.items(): | |
| M = np.array(ob.matrix_world) | |
| traj[name][t - 1] = (M[:3, :3] @ v0.T).T.mean(0) | |
| np.savez_compressed(out / "simtraj.npz", **traj) | |
| print(f"[traj] saved {list(traj)}") | |
| # ---------- render ---------- | |
| scene.render.resolution_x = W | |
| scene.render.resolution_y = H | |
| scene.render.fps = int(round(fps)) | |
| scene.render.fps_base = 1.0 | |
| scene.cycles.samples = args.samples | |
| scene.cycles.use_denoising = True | |
| scene.cycles.max_bounces = 4 | |
| setup_cycles(scene, args.samples, args.device == "gpu") | |
| scene.render.image_settings.file_format = "FFMPEG" | |
| scene.render.ffmpeg.format = "MPEG4" | |
| scene.render.ffmpeg.codec = "H264" | |
| scene.render.ffmpeg.constant_rate_factor = "HIGH" | |
| scene.render.ffmpeg.audio_codec = "NONE" | |
| scene.render.filepath = str(out / "sim.mp4") | |
| bpy.ops.render.render(animation=True) | |
| print(f"[render] wrote {out/'sim.mp4'}") | |
| if __name__ == "__main__": | |
| main() | |