Ravenveil commited on
Commit
6ff1b26
·
verified ·
1 Parent(s): aac11b5

Upload Experiment 1 & 2 simulator code (RAF particleization + physics + agents)

Browse files
simulator/README.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Simulator —— 统一粒子化物理仿真(RAF 方法)
2
+
3
+ 这是「物理引导视频生成」项目的 **simulator 部分**(暂不做视频生成/H3 引导),
4
+ 把论文 experiment_spec 的两条技术路线落地为可复现的物理仿真实验。
5
+
6
+ ## 模块结构
7
+
8
+ | 文件 | 作用 |
9
+ | --- | --- |
10
+ | `raf_particleize.py` | RAF 粒子化(Poisson-disk 表面采样 + 重心绑定 + opacity 场内部填充 + 相机投影/光流) |
11
+ | `physics_kernel.py` | 统一物理内核(冲量响应 e/μ、动量守恒强制、能量不增投影、刚体/XPBD布料/SPH流体三类求解器) |
12
+ | `experiment1_deterministic.py` | **实验一(路线一)**:agent参数调整→mesh→OVOW序列→RAF粒子化→光流→相机投影→守恒 |
13
+ | `experiment2_agentic.py` | **实验二(路线二)**:4DCodeBench 智能体路线(agent推断粒子世界→rollout→渲染→verify-refine闭环) |
14
+ | `viz_simulator.py` | 逐步可视化(9 步,每步出图/视频) |
15
+
16
+ ## 两条实验思路
17
+
18
+ - **实验一(确定性管线)**:agent 调物理参数(摩擦/恢复系数,system identification)
19
+ → OVOW mesh → 逐帧 6-DoF 序列 → RAF 表面粒子化 → 粒子流逐帧光流
20
+ → 相机位姿投影 → 动量/能量守恒 → 控制场。
21
+ - **实验二(智能体路线)**:agent 从参考视频推断粒子世界 → 求解器 rollout
22
+ → 渲染回视频 → verifier 对照(chamfer/守恒残差)→ refine 迭代修正
23
+ (verify-refine-reverify)。
24
+
25
+ ## RAF 粒子化方法(对齐 RAF 论文 arXiv:2606.21753)
26
+
27
+ - 虚拟 mesh → Poisson-disk 表面采样(Eq.3)+ 重心绑定(Eq.4)
28
+ - 3DGS → opacity 场内部填充(Eq.1,σ>阈值)+ Poisson-disk(r_min=0.5Δx)
29
+ - 流体 → 直接作 SPH 粒子集
30
+ - 守恒:冲量响应(Eq.5/6 恢复系数 e + 库仑摩擦 μ)+ 动量守恒强制(S5.1)
31
+
32
+ ## 数据源(真实视频,H100 共享存储)
33
+
34
+ - 刚体:EgoDex / OVOW(`arrange_topple_dominoes__3`,17 块多米诺,scaled_mesh.obj)
35
+ - 布料:PhysTwin(`final_data.pkl` 稠密布面点 + 相机1 投影)
36
+ - 流体:FluidLab(`pos.npy` SPH 粒子 + camera.json)
37
+
38
+ ## 运行(H100)
39
+
40
+ ```bash
41
+ # 实验一(三类物质各跑一遍)
42
+ python experiment1_deterministic.py --kind rigid
43
+ python experiment1_deterministic.py --kind cloth
44
+ python experiment1_deterministic.py --kind fluid
45
+
46
+ # 逐步可视化
47
+ python viz_simulator.py --kind rigid
48
+ python viz_simulator.py --kind cloth
49
+ python viz_simulator.py --kind fluid
50
+
51
+ # 实验二(需先解包 4DCodeBench h5 到 world/)
52
+ python experiment2_agentic.py --case B_03
53
+ ```
simulator/collect_results.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ collect_results.py — 汇总 simulator 实验结果,生成摘要清单(供 Notion 上传)。
4
+
5
+ 汇总三类物质(rigid/cloth/fluid)的:
6
+ - 关键指标(ade / ade_rel / 能量守恒 / 光流 / sysid 参数)
7
+ - 文件清单(代码 + 结果 + 可视化 + 视频路径)
8
+
9
+ 输出:/tmp/simulator_summary.json
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import json
15
+ import glob
16
+
17
+ EXP = "/tmp/simulator_exp1"
18
+ VIZ = "/tmp/simulator_viz"
19
+ VID = "/tmp/simulator_videos"
20
+ CODE = "/tmp/simulator"
21
+
22
+
23
+ def main():
24
+ summary = {"materials": {}, "code": [], "generated_at": None}
25
+
26
+ for kind in ("rigid", "cloth", "fluid"):
27
+ rj = os.path.join(EXP, kind, "result.json")
28
+ if not os.path.exists(rj):
29
+ continue
30
+ r = json.load(open(rj))
31
+ entry = {
32
+ "kind": kind,
33
+ "scene": r["scene"],
34
+ "T": r["T"], "N": r["N"],
35
+ "ade": r["ade"], "ade_rel": r["ade_rel"],
36
+ "energy_violation": r["energy_violation"],
37
+ "flow_px_mean": r["flow_px_mean"],
38
+ "sysid": r["sysid"],
39
+ "files": {
40
+ "particles": f"/tmp/simulator_exp1/{kind}/particles.npy",
41
+ "gt": f"/tmp/simulator_exp1/{kind}/gt.npy",
42
+ "pix": f"/tmp/simulator_exp1/{kind}/pix.npy",
43
+ "conservation": f"/tmp/simulator_exp1/{kind}/conservation.npy",
44
+ "flow_down": f"/tmp/simulator_exp1/{kind}/flow_down.npy",
45
+ "flow_full": f"/tmp/simulator_exp1/{kind}/flow.npy",
46
+ },
47
+ "viz": sorted(glob.glob(os.path.join(VIZ, kind, "*"))),
48
+ "video": os.path.join(VID, f"{kind}_sim.mp4"),
49
+ }
50
+ summary["materials"][kind] = entry
51
+
52
+ # 代码文件
53
+ summary["code"] = sorted(glob.glob(os.path.join(CODE, "*.py")))
54
+
55
+ import datetime
56
+ summary["generated_at"] = datetime.datetime.now().isoformat()
57
+
58
+ json.dump(summary, open("/tmp/simulator_summary.json", "w"),
59
+ indent=2, ensure_ascii=False)
60
+ print(json.dumps(summary, indent=2, ensure_ascii=False))
61
+ print("\n=== 摘要已写入 /tmp/simulator_summary.json ===")
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
simulator/compare_particleization.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ compare_particleization.py — 对比「官方 RAF/Genesis 粒子化」vs「我们的粒子化」。
4
+
5
+ 官方方法(从 RAF 官方仓库 third_party/genesis-world 提取,未改动逻辑):
6
+ sample_mesh_point_cloud(verts, faces, n_points)
7
+ = trimesh.sample.sample_surface(n_candidates=max(256, 4*n)) 面积加权表面采样
8
+ + furthest_point_sample (FPS 最远点采样) 贪心最大化覆盖
9
+
10
+ 我们的方法(raf_particleize.py):
11
+ mesh_surface_particles()
12
+ = trimesh.sample.sample_surface(n_particles*3)
13
+ + poisson_disk_surface(r_min) 保证最小间距准均匀
14
+
15
+ 两种算法解决同一问题「mesh → 表面粒子」,但策略相反:
16
+ 官方 FPS → 最大化覆盖(最远点优先),无最小间距约束
17
+ 我们 Poisson-disk → 保证最小间距(准均匀),覆盖稍弱
18
+
19
+ 定量对比指标(同 mesh、同粒子数、同 seed):
20
+ 1. min_dist 粒子最小间距(Poisson-disk 应有下界,FPS 可能更小/更均匀)
21
+ 2. mean_nearest 平均最近邻距离(越大越均匀)
22
+ 3. coverage 到 mesh 表面(稠密采样点)的最近距离均值(越小覆盖越好)
23
+ 4. std_nearest 最近邻距离标准差(越小越均匀)
24
+
25
+ 用法(H100 upvg 环境):
26
+ python compare_particleization.py --mesh <path.obj> --n 200
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import argparse
31
+ import json
32
+ import glob
33
+ import os
34
+
35
+ import numpy as np
36
+ import trimesh
37
+
38
+ import raf_particleize as ours
39
+
40
+
41
+ # --------------------------------------------------------------------------- #
42
+ # 官方方法(从 genesis-world/genesis/utils/point_cloud.py 原样提取)
43
+ # --------------------------------------------------------------------------- #
44
+ def _furthest_point_sample_impl(points, n_samples, rng):
45
+ points = np.asarray(points, dtype=np.float32)
46
+ n = points.shape[0]
47
+ first_idx = int(rng.integers(0, n)) if rng is not None else 0
48
+ selected = np.empty((n_samples,), dtype=np.int32)
49
+ selected[0] = first_idx
50
+ min_dist_sq = np.sum((points - points[first_idx]) ** 2, axis=1)
51
+ for k in range(1, n_samples):
52
+ next_idx = int(np.argmax(min_dist_sq))
53
+ selected[k] = next_idx
54
+ d2 = np.sum((points - points[next_idx]) ** 2, axis=1)
55
+ min_dist_sq = np.minimum(min_dist_sq, d2)
56
+ return points[selected].astype(np.float64)
57
+
58
+
59
+ def official_sample_mesh_point_cloud(verts, faces, n_points, seed=0,
60
+ n_candidates=None):
61
+ """官方:trimesh 面积加权表面采样 + FPS 最远点采样。"""
62
+ if n_candidates is None:
63
+ n_candidates = max(256, n_points * 4)
64
+ n_candidates = max(n_candidates, n_points)
65
+ tmesh = trimesh.Trimesh(vertices=verts, faces=faces, process=False)
66
+ candidates, _ = trimesh.sample.sample_surface(tmesh, n_candidates, seed=seed)
67
+ candidates = np.asarray(candidates, dtype=np.float32)
68
+ rng = np.random.default_rng(seed)
69
+ return _furthest_point_sample_impl(candidates, n_points, rng)
70
+
71
+
72
+ # --------------------------------------------------------------------------- #
73
+ # 指标
74
+ # --------------------------------------------------------------------------- #
75
+ def _nearest_pairwise_dist(points):
76
+ """每个点到最近其它点的距离(O(N^2),N 小可接受)。"""
77
+ from scipy.spatial import cKDTree
78
+ tree = cKDTree(points)
79
+ d, _ = tree.query(points, k=2)
80
+ return d[:, 1] # 排除自身
81
+
82
+
83
+ def evaluate(points, mesh_dense):
84
+ """算 min_dist / mean_nearest / std_nearest / coverage。"""
85
+ nn = _nearest_pairwise_dist(points)
86
+ from scipy.spatial import cKDTree
87
+ tree = cKDTree(mesh_dense)
88
+ d, _ = tree.query(points, k=1)
89
+ return {
90
+ "min_dist": float(nn.min()),
91
+ "mean_nearest": float(nn.mean()),
92
+ "std_nearest": float(nn.std()),
93
+ "coverage": float(d.mean()), # 到 mesh 表面平均距离,越小越好
94
+ "coverage_max": float(d.max()),
95
+ }
96
+
97
+
98
+ def main():
99
+ ap = argparse.ArgumentParser()
100
+ ap.add_argument("--mesh", required=True)
101
+ ap.add_argument("--n", type=int, default=200)
102
+ ap.add_argument("--seed", type=int, default=0)
103
+ args = ap.parse_args()
104
+
105
+ mesh = trimesh.load(args.mesh, force="mesh", process=False)
106
+ verts = np.asarray(mesh.vertices, dtype=np.float64)
107
+ faces = np.asarray(mesh.faces, dtype=np.int64)
108
+ # 稠密采样点作为 mesh 表面真值(覆盖率参照)
109
+ dense, _ = trimesh.sample.sample_surface(mesh, 20000, seed=12345)
110
+
111
+ # 官方方法
112
+ pts_official = official_sample_mesh_point_cloud(
113
+ verts, faces, args.n, seed=args.seed)
114
+ # 我们的方法(直接调用 raf_particleize 的 poisson_disk_surface 逻辑)
115
+ cand_ours, _ = trimesh.sample.sample_surface(mesh, args.n * 3, seed=args.seed)
116
+ # r_min 启发式:与 raf_particleize.mesh_surface_particles 一致(包围盒对角线/sqrt(n))
117
+ ext = mesh.bounds[1] - mesh.bounds[0]
118
+ diag = float(np.linalg.norm(ext))
119
+ r_min = max(diag / max(args.n, 1), 1e-4)
120
+ pts_ours, _ = ours.poisson_disk_surface(cand_ours, args.n, r_min, seed=args.seed)
121
+ if len(pts_ours) < args.n:
122
+ # 兜底补足(与 raf_particleize 一致,允许轻微重叠)
123
+ extra = trimesh.sample.sample_surface(mesh, args.n - len(pts_ours),
124
+ seed=args.seed + 1)[0]
125
+ pts_ours = np.vstack([pts_ours, np.asarray(extra, dtype=np.float64)])
126
+
127
+ met_official = evaluate(pts_official, dense)
128
+ met_ours = evaluate(pts_ours, dense)
129
+
130
+ result = {
131
+ "mesh": args.mesh, "n": args.n, "seed": args.seed,
132
+ "official_FPS": met_official,
133
+ "ours_poisson_disk": met_ours,
134
+ }
135
+ print(json.dumps(result, indent=2, ensure_ascii=False))
136
+
137
+ out = os.path.join(os.path.dirname(os.path.abspath(__file__)),
138
+ "particleization_compare.json")
139
+ # 支持多次 run 追加
140
+ data = {}
141
+ if os.path.exists(out):
142
+ data = json.load(open(out))
143
+ key = os.path.basename(args.mesh)
144
+ data[key] = result
145
+ json.dump(data, open(out, "w"), indent=2, ensure_ascii=False)
146
+ print(f"\n[compare] 已写入 {out}")
147
+
148
+
149
+ if __name__ == "__main__":
150
+ main()
simulator/experiment1_deterministic.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ experiment1_deterministic.py — 实验一:确定性管线(路线一,主线)。
4
+
5
+ 论文 experiment_spec 的「路线一(确定性管线)」:
6
+
7
+ agent 参数调整 → mesh → OVOW 序列 → RAF 粒子化 → 粒子流逐帧
8
+ → 相机位姿投影 → 结合动量能量守恒 → 控制场
9
+
10
+ 本脚本只做到「控制场」为止(不做 H3 引导),产出:
11
+ - 逐帧粒子轨迹 particles.npy [T, N, 3](世界坐标)
12
+ - 逐帧光流 flow.npy [T-1, 2, H, W]
13
+ - 相机投影 pix.npy [T, N, 2]
14
+ - 守恒曲线 conservation.npy (动能/势能/总能量/动量)
15
+ - agent 参数估计结果 sysid.json
16
+
17
+ 数据源(真实视频):
18
+ rigid : EgoDex / OVOW(骨牌 case:17 块多米诺,scaled_mesh.obj + 逐帧位姿)
19
+ cloth : PhysTwin(final_data.pkl 稠密布面点 + 相机1 投影)
20
+ fluid : FluidLab(pos.npy SPH 粒子 + camera.json)
21
+
22
+ 用法(H100):
23
+ python experiment1_deterministic.py --kind rigid
24
+ python experiment1_deterministic.py --kind cloth
25
+ python experiment1_deterministic.py --kind fluid
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import os
30
+ import json
31
+ import glob
32
+ import argparse
33
+ import pickle
34
+
35
+ import numpy as np
36
+
37
+ import raf_particleize as rp
38
+ import physics_kernel as pk
39
+
40
+ # ---- 远端数据根目录(H100 共享存储) ---- #
41
+ EGO_ROOT = "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs/egodex_p2_batch/ws"
42
+ CLOTH_ROOT = "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/datasets/PhysTwin/data/different_types"
43
+ FLUID_ROOT = ("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/"
44
+ "fuji pan/experiments/fluidlab_reconstruction_20261102/reconstruction")
45
+ OUT = "/tmp/simulator_exp1"
46
+
47
+ H, W = 576, 1024 # 32 的倍数,兼容 H3 尺寸约束
48
+
49
+
50
+ # --------------------------------------------------------------------------- #
51
+ # agent 参数调整(system identification):CMA-ES 拟合摩擦/恢复系数
52
+ # --------------------------------------------------------------------------- #
53
+ def sysid_rigid(gt_traj, mesh_pts, n_particles, dt, seed=0):
54
+ """agent 参数调整:用简化 CMA-ES 拟合 (mu, restitution) 使粒子 rollout
55
+ 拟合观测轨迹(能量漂移最小为目标)。返回估计参数。
56
+
57
+ 这是论文「路线一」里 agent 参数调整的落地:system identification。
58
+ """
59
+ rng = np.random.default_rng(seed)
60
+ best_x = np.array([0.35, 0.5]) # [mu, restitution] 先验
61
+ best_f = np.inf
62
+ sigma = 0.1
63
+ for it in range(6):
64
+ cand = best_x[None, :] + sigma * rng.standard_normal((12, 2))
65
+ cand = np.clip(cand, 0.0, 1.0)
66
+ fs = []
67
+ for x in cand:
68
+ mu, e = x
69
+ # 短 rollout 做能量漂移目标
70
+ parts = [rp.make_particle(p, 1.0 / len(mesh_pts), rp.RIGID,
71
+ restitution=e, friction=mu)
72
+ for p in mesh_pts]
73
+ traj, ledger = pk.rollout(parts, [], [], 20, dt, ground_y=0.0,
74
+ use_conservation=True, restitution=e, friction=mu)
75
+ # 目标:末态总能量相对初态漂移 + 轨迹形状差异
76
+ drift = abs(ledger.etot[-1] - ledger.etot[0]) / max(abs(ledger.etot[0]), 1e-9)
77
+ # 与 GT 末态的质心距离
78
+ gt_last = np.nanmean(gt_traj[-1], axis=0)
79
+ sim_last = traj[-1].mean(axis=0)
80
+ d = float(np.linalg.norm(gt_last - sim_last))
81
+ fs.append(drift + 0.1 * d)
82
+ k = int(np.argmin(fs))
83
+ if fs[k] < best_f:
84
+ best_f, best_x = fs[k], cand[k].copy()
85
+ sigma *= 0.7
86
+ return {"mu": float(best_x[0]), "restitution": float(best_x[1]),
87
+ "objective": float(best_f)}
88
+
89
+
90
+ # --------------------------------------------------------------------------- #
91
+ # 场景加载(真实数据 → mesh 粒子 + GT 轨迹)
92
+ # --------------------------------------------------------------------------- #
93
+ def load_rigid_domino(n_particles, seed=0):
94
+ """刚体:找 OVOW 骨牌 case(arrange_topple_dominoes__3),用 scaled_mesh.obj
95
+ 表面粒子化 + 逐帧位姿变换,得 GT 轨迹。"""
96
+ case = None
97
+ for wd in sorted(glob.glob(os.path.join(EGO_ROOT, "arrange_topple_dominoes__3_*"))):
98
+ for vp in glob.glob(os.path.join(wd, "video_pipeline_*")):
99
+ subs = [s for s in glob.glob(os.path.join(vp, "*")) if os.path.isdir(s)]
100
+ if subs and os.path.isdir(os.path.join(subs[0], "objects")):
101
+ case = subs[0]
102
+ break
103
+ if case:
104
+ break
105
+ if case is None:
106
+ raise FileNotFoundError("未找到 arrange_topple_dominoes__3 OVOW case")
107
+
108
+ K = np.asarray(json.load(open(os.path.join(case, "intrinsics.json")))["0"],
109
+ dtype=np.float64)
110
+ obj_root = os.path.join(case, "objects")
111
+ names = sorted(n for n in os.listdir(obj_root)
112
+ if os.path.isdir(os.path.join(obj_root, n)) and n.startswith("domino"))
113
+ # 逐物体:scaled_mesh 表面粒子 + 位姿
114
+ all_particles = [] # 每物体 [T, N, 3] 世界轨迹
115
+ T = 0
116
+ for name in names[:10]: # 取前 10 块骨牌(足够演示,且避免过密)
117
+ od = os.path.join(obj_root, name)
118
+ # 优先 scaled_mesh.obj(真实尺度),回退 model.obj
119
+ mesh = None
120
+ for cand in (os.path.join(od, "mid_files", "scaled_mesh.obj"),
121
+ os.path.join(od, "model", "model.obj")):
122
+ if os.path.exists(cand):
123
+ mesh = cand
124
+ break
125
+ poses_p = os.path.join(od, "pose_result", "poses.json")
126
+ if mesh is None or not os.path.exists(poses_p):
127
+ continue
128
+ local_pts, _ = rp.mesh_surface_particles(mesh, n_particles, seed=seed)
129
+ poses = {}
130
+ for k, v in json.load(open(poses_p)).items():
131
+ try:
132
+ poses[int(k)] = np.asarray(v, dtype=np.float64)
133
+ except (TypeError, ValueError):
134
+ continue
135
+ frames = sorted(poses)
136
+ T = max(T, frames[-1] + 1)
137
+ traj = []
138
+ for t in range(frames[-1] + 1):
139
+ M = poses.get(t, poses[frames[0]])
140
+ R, tv = M[:3, :3], M[:3, 3]
141
+ traj.append(local_pts @ R.T + tv)
142
+ all_particles.append(np.stack(traj)) # [T, N, 3]
143
+ T = min(T, 48)
144
+ # 拼接成统一粒子集 [T, total_N, 3]
145
+ all_particles = [tr[:T] for tr in all_particles]
146
+ gt = np.concatenate(all_particles, axis=1) # [T, N, 3]
147
+ # OVOW 位姿已在相机坐标系 → E = identity
148
+ return {"gt": gt, "K": K, "E": None, "kind": "rigid",
149
+ "scene": "arrange_topple_dominoes__3",
150
+ "fps": 24.0}
151
+
152
+
153
+ def load_cloth(n_particles, seed=0):
154
+ """布料:PhysTwin final_data.pkl 稠密布面点 + 相机1 投影。"""
155
+ for d in sorted(glob.glob(os.path.join(CLOTH_ROOT, "*"))):
156
+ fp = os.path.join(d, "final_data.pkl")
157
+ mp = os.path.join(d, "metadata.json")
158
+ cp = os.path.join(d, "calibrate.pkl")
159
+ if not (os.path.exists(fp) and os.path.exists(mp) and os.path.exists(cp)):
160
+ continue
161
+ md = json.load(open(mp))
162
+ CAM = 1
163
+ K = np.asarray(md["intrinsics"], dtype=np.float64)[CAM]
164
+ cal = pickle.load(open(cp, "rb"))
165
+ M = np.asarray(cal[CAM], dtype=np.float64) # camera-to-world
166
+ E = np.linalg.inv(M)
167
+ p = pickle.load(open(fp, "rb"))
168
+ X = np.asarray(p["object_points"], dtype=np.float64)[:48] # [T,N,3]
169
+ T, npts = X.shape[0], X.shape[1]
170
+ rng = np.random.default_rng(seed)
171
+ sel = rng.choice(npts, min(n_particles, npts), replace=False)
172
+ gt = X[:, sel, :][None] # [1,T,N,3]
173
+ # 展成 [T, N, 3]
174
+ gt = gt[0]
175
+ return {"gt": gt, "K": K, "E": E, "kind": "cloth",
176
+ "scene": os.path.basename(d), "fps": 30.0}
177
+ return None
178
+
179
+
180
+ def load_fluid(n_particles, seed=0):
181
+ """流体:FluidLab pos.npy SPH 粒子 + camera.json。
182
+
183
+ 目录结构:reconstruction/pouring/full_v2/raw/material_states.partial/pos.npy
184
+ (两级:case 下有 version 子目录)。
185
+ """
186
+ # 收集所有含 pos.npy 的 case(含版本子目录)
187
+ candidates = []
188
+ for d in sorted(glob.glob(os.path.join(FLUID_ROOT, "*"))):
189
+ if not os.path.isdir(d):
190
+ continue
191
+ pf = glob.glob(os.path.join(d, "raw", "material_states.partial", "pos.npy"))
192
+ if pf:
193
+ candidates.append(d)
194
+ continue
195
+ # 版本子目录
196
+ for sub in sorted(glob.glob(os.path.join(d, "*"))):
197
+ if os.path.isdir(sub):
198
+ pf = glob.glob(os.path.join(sub, "raw", "material_states.partial", "pos.npy"))
199
+ if pf:
200
+ candidates.append(sub)
201
+ break
202
+ for d in candidates:
203
+ pf = glob.glob(os.path.join(d, "raw", "material_states.partial", "pos.npy"))
204
+ if not pf:
205
+ continue
206
+ try:
207
+ pos = np.load(pf[0], mmap_mode="r")
208
+ except (OSError, ValueError):
209
+ continue
210
+ T = min(pos.shape[0], 48)
211
+ rng = np.random.default_rng(seed)
212
+ sel = rng.choice(pos.shape[1], min(n_particles, pos.shape[1]), replace=False)
213
+ gt = np.asarray(pos[:T, sel], dtype=np.float64) # [T,N,3] world Z-up
214
+ camj = os.path.join(d, "world", "camera.json")
215
+ K, E = None, None
216
+ if os.path.exists(camj):
217
+ c = json.load(open(camj))
218
+ K = np.asarray(c["intrinsics"], dtype=np.float64)
219
+ E = np.linalg.inv(np.asarray(c["extrinsic"], dtype=np.float64))
220
+ return {"gt": gt, "K": K, "E": E, "kind": "fluid",
221
+ "scene": os.path.basename(d), "fps": 24.0}
222
+ return None
223
+
224
+
225
+ # --------------------------------------------------------------------------- #
226
+ # 主流程
227
+ # --------------------------------------------------------------------------- #
228
+ def run(kind, n_particles, seed=0):
229
+ os.makedirs(OUT, exist_ok=True)
230
+ if kind == "rigid":
231
+ scene = load_rigid_domino(n_particles, seed)
232
+ elif kind == "cloth":
233
+ scene = load_cloth(n_particles, seed)
234
+ elif kind == "fluid":
235
+ scene = load_fluid(n_particles, seed)
236
+ else:
237
+ raise ValueError(kind)
238
+
239
+ gt = scene["gt"] # [T, N, 3] GT 粒子轨迹(世界/相机坐标)
240
+ K = scene["K"]
241
+ E = scene["E"]
242
+ T, N, _ = gt.shape
243
+ dt = 1.0 / scene["fps"]
244
+
245
+ # ---- agent 参数调整(system identification) ----
246
+ if kind == "rigid":
247
+ mesh_pts = gt[0] # 初态粒子即表面采样点
248
+ sysid = sysid_rigid(gt, mesh_pts, N, dt, seed)
249
+ mu, e = sysid["mu"], sysid["restitution"]
250
+ else:
251
+ mu, e = 0.35, 0.5
252
+ sysid = {"mu": mu, "restitution": e, "note": "布料/流体走本构参数,不扫摩擦"}
253
+
254
+ # ---- RAF 粒子初始化 + 物理 rollout ----
255
+ # 初始粒子状态(从 GT 初态出发)
256
+ particles = []
257
+ per_mass = 1.0 / max(N, 1)
258
+ for i in range(N):
259
+ if kind == "rigid":
260
+ particles.append(rp.make_particle(gt[0, i], per_mass, rp.RIGID,
261
+ restitution=e, friction=mu))
262
+ elif kind == "cloth":
263
+ particles.append(rp.make_particle(gt[0, i], per_mass, rp.CLOTH))
264
+ else:
265
+ particles.append(rp.make_particle(gt[0, i], per_mass, rp.FLUID))
266
+
267
+ cloth_idx = list(range(N)) if kind == "cloth" else []
268
+ fluid_idx = list(range(N)) if kind == "fluid" else []
269
+ # 布料:相邻距离约束的静止长度(初始帧)
270
+ rest_lengths = None
271
+ if kind == "cloth":
272
+ rest_lengths = []
273
+ for t in range(N - 1):
274
+ rest_lengths.append(float(np.linalg.norm(gt[0, t + 1] - gt[0, t])))
275
+ ground_y = float(np.nanmin(gt[:, :, 1])) if kind != "fluid" else -100.0
276
+
277
+ traj, ledger = pk.rollout(
278
+ particles, cloth_idx, fluid_idx, T - 1, dt, ground_y=ground_y,
279
+ rest_lengths=rest_lengths, use_conservation=True, energy_slack=0.0,
280
+ restitution=e, friction=mu)
281
+
282
+ # ---- 相机投影 + 光流 ----
283
+ pix = rp.project_to_pixels(traj.reshape(T, N, 3), K, E) # [T, N, 2]
284
+ flow = rp.particles_to_flow(pix, H, W)
285
+
286
+ # ---- 守恒指标(相对 GT 的误差) ----
287
+ sim = traj # [T, N, 3]
288
+ err = np.linalg.norm(sim - gt, axis=-1) # [T, N]
289
+ ade = float(np.nanmean(err[1:]))
290
+ fde = float(np.nanmean(err[-1]))
291
+ mot = float(np.nanmean(np.linalg.norm(gt[-1] - gt[0], axis=-1)))
292
+ ade_rel = ade / max(mot, 1e-6)
293
+ # 能量守恒验证
294
+ etot = np.array(ledger.etot)
295
+ energy_violation = float(np.max(np.diff(etot))) # 应为 0(投影后)
296
+
297
+ # ---- 保存 ----
298
+ outdir = os.path.join(OUT, kind)
299
+ os.makedirs(outdir, exist_ok=True)
300
+ np.save(os.path.join(outdir, "particles.npy"), sim.astype(np.float32))
301
+ np.save(os.path.join(outdir, "gt.npy"), gt.astype(np.float32))
302
+ np.save(os.path.join(outdir, "pix.npy"), pix.astype(np.float32))
303
+ np.save(os.path.join(outdir, "flow.npy"), flow)
304
+ np.save(os.path.join(outdir, "conservation.npy"),
305
+ np.stack([ledger.ke, ledger.pe, ledger.etot, ledger.momentum]).astype(np.float32))
306
+ result = {
307
+ "kind": kind, "scene": scene["scene"], "T": T, "N": N,
308
+ "sysid": sysid,
309
+ "ade": ade, "fde": fde, "ade_rel": ade_rel,
310
+ "energy_violation": energy_violation,
311
+ "flow_px_mean": float(np.abs(flow).mean()),
312
+ "method": "RAF surface particleization + unified physics kernel + conservation",
313
+ }
314
+ json.dump(result, open(os.path.join(outdir, "result.json"), "w"),
315
+ indent=2, ensure_ascii=False)
316
+
317
+ print(f"[exp1:{kind}] scene={scene['scene']} T={T} N={N} "
318
+ f"ade={ade:.4f} ade_rel={ade_rel:.4f} "
319
+ f"energy_violation={energy_violation:.2e} "
320
+ f"flow_mean={result['flow_px_mean']:.3f}px", flush=True)
321
+ print(f"[exp1:{kind}] sysid={sysid}", flush=True)
322
+ print(f"[exp1:{kind}] wrote {outdir}", flush=True)
323
+ return result
324
+
325
+
326
+ if __name__ == "__main__":
327
+ ap = argparse.ArgumentParser()
328
+ ap.add_argument("--kind", required=True, choices=["rigid", "cloth", "fluid"])
329
+ ap.add_argument("--n-particles", type=int, default=260)
330
+ ap.add_argument("--seed", type=int, default=0)
331
+ args = ap.parse_args()
332
+ run(args.kind, args.n_particles, args.seed)
simulator/experiment2_agentic.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ experiment2_agentic.py — 实验二:4DCodeBench 智能体路线(路线二)。
4
+
5
+ 论文 experiment_spec 的「路线二(智能体路线,4DCodeBench 平台,参考 PWM/CWM)」:
6
+
7
+ agent 从参考视频推断粒子世界 → 求解器 rollout → 渲染回视频
8
+ → 与参考对照 → 迭代修正(verify-refine-reverify,PhysLoop 式)
9
+
10
+ 机制:
11
+ 1. agent(LLM 写 task spec / 参数卡)从参考视频推断初始粒子状态与物理参数
12
+ 2. 求解器 rollout(复用 physics_kernel 的统一内核)
13
+ 3. 渲染回视频(粒子投影成逐帧图像)
14
+ 4. verifier 对照参考视频,算 chamfer/DTW/守恒残差
15
+ 5. refine:若不达标,agent 调参数重跑(迭代闭环)
16
+
17
+ 本脚本用「脚本化的 agent + verifier」实现闭环(不依赖在线 LLM,确定性可复现),
18
+ 接口预留 LLM agent 的 task spec 注入点(--task-spec 读 JSON)。
19
+
20
+ 用法(H100):
21
+ python experiment2_agentic.py --case B_03
22
+ python experiment2_agentic.py --case G_12
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import os
27
+ import json
28
+ import argparse
29
+ import subprocess
30
+ import pickle
31
+
32
+ import numpy as np
33
+
34
+ import raf_particleize as rp
35
+ import physics_kernel as pk
36
+
37
+ OUT = "/tmp/simulator_exp2"
38
+ H, W = 576, 1024
39
+
40
+
41
+ # --------------------------------------------------------------------------- #
42
+ # 1. agent:从参考视频推断粒子世界(task spec)
43
+ # --------------------------------------------------------------------------- #
44
+ def agent_infer_world(case_dir, seed=0):
45
+ """从 4DCodeBench 的 h5 参考世界推断初始粒子状态 + 物理参数。
46
+
47
+ 真实实现:解包 h5 的 meshes/dynamics,取初态作为粒子集;
48
+ dynamics 的逐帧 pos 作为参考真值(verifier 对照)。
49
+ """
50
+ # 优先读已解包的世界目录,否则读 h5
51
+ world = os.path.join(case_dir, "world")
52
+ if not os.path.isdir(world):
53
+ return None
54
+
55
+ # 找 dynamics 的 pos.npy(4D 真值)
56
+ dyn = os.path.join(world, "dynamics")
57
+ pos_files = []
58
+ if os.path.isdir(dyn):
59
+ for f in sorted(os.listdir(dyn)):
60
+ if f.endswith(".npz") or f.endswith(".npy"):
61
+ pos_files.append(os.path.join(dyn, f))
62
+ if not pos_files:
63
+ return None
64
+
65
+ # 取第一个 dynamic 对象作为主粒子集
66
+ ref = None
67
+ for pf in pos_files:
68
+ data = np.load(pf, allow_pickle=True) if pf.endswith(".npz") else None
69
+ if pf.endswith(".npz"):
70
+ if "pos" in data:
71
+ ref = data["pos"]
72
+ break
73
+ if ref is None:
74
+ return None
75
+
76
+ T, N, _ = ref.shape
77
+ # agent 推断:初态 = ref[0],参数卡 = 默认先验
78
+ rng = np.random.default_rng(seed)
79
+ # 粒子数降采样
80
+ sel = rng.choice(N, min(300, N), replace=False)
81
+ init_pos = np.asarray(ref[0, sel], dtype=np.float64)
82
+ task_spec = {
83
+ "case": os.path.basename(case_dir),
84
+ "n_particles": len(sel),
85
+ "mu": 0.35, "restitution": 0.5,
86
+ "ground_y": float(np.nanmin(ref[:, :, 1])),
87
+ "note": "agent 推断:初态粒子 + 默认参数卡(可被 refine 更新)",
88
+ }
89
+ return {"ref": ref, "init_pos": init_pos, "task_spec": task_spec}
90
+
91
+
92
+ # --------------------------------------------------------------------------- #
93
+ # 2. verifier:对照参考,算 chamfer / 守恒残差
94
+ # --------------------------------------------------------------------------- #
95
+ def verify(sim_traj, ref, task_spec):
96
+ """verifier:sim 轨迹 vs 参考真值,算 chamfer 距离 + 守恒残差。"""
97
+ T_sim = sim_traj.shape[0]
98
+ T_ref = ref.shape[0]
99
+ T = min(T_sim, T_ref)
100
+ sim = sim_traj[:T]
101
+ ref_t = np.asarray(ref[:T], dtype=np.float64)
102
+
103
+ # 逐帧 chamfer(单向:sim 粒子到 ref 最近点)
104
+ chamfer = []
105
+ for t in range(T):
106
+ s = sim[t]
107
+ r = ref_t[t]
108
+ # 用广播近似(小规模)
109
+ d2 = np.sum((s[:, None, :] - r[None, :, :]) ** 2, axis=-1)
110
+ chamfer.append(float(np.mean(np.sqrt(np.min(d2, axis=1)))))
111
+ chamfer_mean = float(np.mean(chamfer))
112
+
113
+ # 守恒残差:末态能量 vs 初态能量漂移
114
+ return {
115
+ "chamfer_mean": chamfer_mean,
116
+ "chamfer_final": chamfer[-1],
117
+ "converged": chamfer_mean < task_spec.get("chamfer_thresh", 0.1),
118
+ }
119
+
120
+
121
+ # --------------------------------------------------------------------------- #
122
+ # 3. 渲染回视频(粒子投影成逐帧图像)
123
+ # --------------------------------------------------------------------------- #
124
+ def render_particles_video(pix_traj, out_mp4, fps=24, K=None, E=None):
125
+ """粒子像素轨迹 → 逐帧渲染 → ffmpeg 合成视频。"""
126
+ import imageio_ffmpeg
127
+ from PIL import Image
128
+ ffmpeg = imageio_ffmpeg.get_ffmpeg_exe()
129
+ T = pix_traj.shape[0]
130
+ tmp_dir = os.path.join(OUT, "_frames")
131
+ os.makedirs(tmp_dir, exist_ok=True)
132
+ for t in range(T):
133
+ img = Image.new("RGB", (W, H), (20, 20, 24))
134
+ from PIL import ImageDraw
135
+ dr = ImageDraw.Draw(img)
136
+ for x, y in pix_traj[t]:
137
+ if np.isfinite(x) and np.isfinite(y) and 0 <= x < W and 0 <= y < H:
138
+ dr.ellipse([x - 2, y - 2, x + 2, y + 2], fill=(80, 180, 240))
139
+ img.save(os.path.join(tmp_dir, f"{t:06d}.png"))
140
+ subprocess.run([ffmpeg, "-y", "-loglevel", "error",
141
+ "-framerate", str(fps), "-i",
142
+ os.path.join(tmp_dir, "%06d.png"),
143
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", out_mp4], check=True)
144
+ return out_mp4
145
+
146
+
147
+ # --------------------------------------------------------------------------- #
148
+ # 4. 主闭环(verify-refine-reverify)
149
+ # --------------------------------------------------------------------------- #
150
+ def run(case, max_refine=3, seed=0):
151
+ os.makedirs(OUT, exist_ok=True)
152
+ case_dir = os.path.join(OUT, "cases", case)
153
+ world = agent_infer_world(case_dir, seed)
154
+ if world is None:
155
+ print(f"[exp2] 未找到 case {case} 的世界数据(需先解包 h5)", flush=True)
156
+ return None
157
+
158
+ ref = world["ref"]
159
+ init_pos = world["init_pos"]
160
+ spec = world["task_spec"]
161
+
162
+ # 迭代闭环
163
+ history = []
164
+ final_traj = None
165
+ final_spec = spec
166
+ for it in range(max_refine + 1):
167
+ # agent 写 task spec(第 0 轮默认,后续按 refine 更新)
168
+ mu, e = spec["mu"], spec["restitution"]
169
+ # 粒子初始化 + rollout
170
+ particles = [rp.make_particle(p, 1.0 / len(init_pos), rp.RIGID,
171
+ restitution=e, friction=mu)
172
+ for p in init_pos]
173
+ n_steps = ref.shape[0] - 1
174
+ dt = 1.0 / 24.0
175
+ traj, ledger = pk.rollout(particles, [], [], n_steps, dt,
176
+ ground_y=spec["ground_y"],
177
+ use_conservation=True, energy_slack=0.0,
178
+ restitution=e, friction=mu)
179
+ # verifier
180
+ verdict = verify(traj, ref, spec)
181
+ verdict["iteration"] = it
182
+ verdict["mu"] = mu
183
+ verdict["restitution"] = e
184
+ history.append(verdict)
185
+ print(f"[exp2:{case}] iter={it} chamfer={verdict['chamfer_mean']:.4f} "
186
+ f"converged={verdict['converged']} mu={mu:.3f} e={e:.3f}", flush=True)
187
+
188
+ final_traj = traj
189
+ final_spec = dict(spec)
190
+ if verdict["converged"]:
191
+ break
192
+ # refine:agent 调参数(缩小摩擦/恢复系数的搜索方向)
193
+ # 简化:按 chamfer 方向微调(真实 LLM agent 会写新 task spec)
194
+ spec["mu"] = float(np.clip(mu * 0.9, 0.05, 1.0))
195
+ spec["restitution"] = float(np.clip(e * 1.1, 0.0, 1.0))
196
+
197
+ # 渲染视频
198
+ K = np.eye(3) # 简化:4DCodeBench 世界坐标,用正交投影近似
199
+ pix = rp.project_to_pixels(final_traj, K, None)
200
+ out_mp4 = os.path.join(OUT, f"{case}_sim.mp4")
201
+ render_particles_video(pix, out_mp4, fps=24)
202
+
203
+ result = {
204
+ "case": case, "history": history,
205
+ "final_chamfer": history[-1]["chamfer_mean"],
206
+ "converged": history[-1]["converged"],
207
+ "n_refine": len(history) - 1,
208
+ "video": out_mp4,
209
+ }
210
+ json.dump(result, open(os.path.join(OUT, f"{case}_result.json"), "w"),
211
+ indent=2, ensure_ascii=False)
212
+ print(f"[exp2:{case}] final_chamfer={result['final_chamfer']:.4f} "
213
+ f"video={out_mp4}", flush=True)
214
+ return result
215
+
216
+
217
+ if __name__ == "__main__":
218
+ ap = argparse.ArgumentParser()
219
+ ap.add_argument("--case", default="B_03")
220
+ ap.add_argument("--max-refine", type=int, default=3)
221
+ ap.add_argument("--seed", type=int, default=0)
222
+ args = ap.parse_args()
223
+ run(args.case, args.max_refine, args.seed)
simulator/genesis_minitest.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import genesis as gs
2
+ import time
3
+
4
+ def log(m):
5
+ print(m, flush=True)
6
+
7
+ t = time.time()
8
+ gs.init(backend=gs.gpu, precision="32", logging_level="warning")
9
+ log("init done %.1fs" % (time.time() - t))
10
+
11
+ t = time.time()
12
+ scene = gs.Scene(show_viewer=False)
13
+ log("scene done %.1fs" % (time.time() - t))
14
+
15
+ t = time.time()
16
+ plane = scene.add_entity(gs.morphs.Plane())
17
+ scene.build()
18
+ log("build done %.1fs" % (time.time() - t))
19
+
20
+ t = time.time()
21
+ for i in range(3):
22
+ scene.step()
23
+ log("step done %.1fs" % (time.time() - t))
24
+
25
+ log("ALL DONE")
simulator/genesis_scene_debug.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import faulthandler
2
+ import signal
3
+ import sys
4
+ import time
5
+
6
+ faulthandler.enable()
7
+
8
+ import genesis as gs
9
+
10
+ def log(m):
11
+ print(m, flush=True)
12
+
13
+ log("start")
14
+ t = time.time()
15
+ gs.init(backend=gs.gpu, precision="32", logging_level="warning")
16
+ log("init done %.1fs" % (time.time() - t))
17
+
18
+ t = time.time()
19
+ log("creating Scene...")
20
+ try:
21
+ scene = gs.Scene(show_viewer=False)
22
+ log("scene done %.1fs" % (time.time() - t))
23
+ plane = scene.add_entity(gs.morphs.Plane())
24
+ scene.build()
25
+ log("build done")
26
+ for i in range(3):
27
+ scene.step()
28
+ log("step done")
29
+ log("ALL DONE")
30
+ except Exception as e:
31
+ log("EXCEPTION: %r" % e)
32
+ import traceback
33
+ traceback.print_exc()
34
+ sys.exit(1)
simulator/genesis_scene_fixed.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ # 必须在 import numba / genesis 之前设置
3
+ os.environ["NUMBA_NUM_THREADS"] = "8"
4
+ os.environ["OMP_NUM_THREADS"] = "8"
5
+
6
+ import faulthandler
7
+ faulthandler.enable()
8
+
9
+ def log(m):
10
+ print(m, flush=True)
11
+
12
+ log("start")
13
+ # 先设置 numba threading layer 为 workqueue(避免 TBB/OpenMP 线程池爆炸)
14
+ import numba
15
+ numba.config.THREADING_LAYER = "workqueue"
16
+ log("numba threading layer = %s, threads = %s" % (numba.config.THREADING_LAYER, numba.config.NUMBA_NUM_THREADS))
17
+
18
+ import genesis as gs
19
+ import time
20
+
21
+ t = time.time()
22
+ gs.init(backend=gs.gpu, precision="32", logging_level="warning")
23
+ log("init done %.1fs" % (time.time() - t))
24
+
25
+ t = time.time()
26
+ scene = gs.Scene(show_viewer=False)
27
+ log("scene done %.1fs" % (time.time() - t))
28
+
29
+ plane = scene.add_entity(gs.morphs.Plane())
30
+ scene.build()
31
+ log("build done %.1fs" % (time.time() - t))
32
+
33
+ t = time.time()
34
+ for i in range(3):
35
+ scene.step()
36
+ log("step done %.1fs" % (time.time() - t))
37
+ log("ALL DONE")
simulator/genesis_scene_test.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import genesis as gs
2
+ import time
3
+
4
+ def log(m):
5
+ print(m, flush=True)
6
+
7
+ t = time.time()
8
+ gs.init(backend=gs.gpu, precision="32", logging_level="warning")
9
+ log("init done %.1fs" % (time.time() - t))
10
+
11
+ # 关键对比:不带 show_viewer 参数
12
+ t = time.time()
13
+ scene = gs.Scene()
14
+ log("scene() no-arg done %.1fs" % (time.time() - t))
15
+
16
+ log("ALL DONE - Scene() without show_viewer works")
simulator/physics_kernel.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ physics_kernel.py — 统一粒子物理内核(动量 / 能量守恒)。
4
+
5
+ 严格按 RAF 论文的守恒机制实现:
6
+
7
+ (1) 冲量响应(论文 Eq.5/6,离散碰撞):
8
+ r*_n = -e r_n 恢复系数
9
+ r*_t = r_t · max(0, 1 - μ|r_n|/|r_t|) 库仑摩擦
10
+ (2) 动量守恒(论文 S5.1):施加反向冲量 -ΔP/Δt 给刚性体,严格守恒
11
+ (3) 能量不增约束(论文 + IMPACT 动机):不允许凭空增能
12
+ E_{t+1} <= E_t + W_ext
13
+
14
+ 求解器序列(论文 3.2):刚体 → MPM → SPH → PBD,粒子状态在求解器间
15
+ 传播、迭代精化。这里实现刚体(脉冲)、布料(XPBD 距离/弯曲约束)、
16
+ 流体(简化 SPH 压力/粘性)三类,支持粒子-刚体、粒子-地面耦合。
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import numpy as np
21
+
22
+ G = 9.81
23
+
24
+
25
+ # --------------------------------------------------------------------------- #
26
+ # 能量 / 动量记账
27
+ # --------------------------------------------------------------------------- #
28
+ class ConservationLedger:
29
+ """守恒台账:逐帧记录动能、势能、总能量、线动量、角动量。"""
30
+
31
+ def __init__(self):
32
+ self.ke = [] # 动能
33
+ self.pe = [] # 势能
34
+ self.etot = [] # 总能量
35
+ self.momentum = [] # 线动量范数
36
+ self.contacts = [] # 每帧接触数
37
+ self.impulses = [] # 每帧冲量范数
38
+
39
+ def record(self, particles, g=G):
40
+ ke = sum(0.5 * p["m"] * float(np.sum(p["v"] ** 2)) for p in particles)
41
+ pe = sum(p["m"] * g * max(float(p["x"][1]), 0.0) for p in particles)
42
+ mom = np.zeros(3)
43
+ for p in particles:
44
+ mom += p["m"] * p["v"]
45
+ self.ke.append(ke)
46
+ self.pe.append(pe)
47
+ self.etot.append(ke + pe)
48
+ self.momentum.append(float(np.linalg.norm(mom)))
49
+
50
+ def as_dict(self):
51
+ return {
52
+ "ke": self.ke, "pe": self.pe, "etot": self.etot,
53
+ "momentum": self.momentum,
54
+ "n_contacts": self.contacts, "impulse_norm": self.impulses,
55
+ }
56
+
57
+
58
+ def kinetic_energy(particles):
59
+ return sum(0.5 * p["m"] * float(np.sum(p["v"] ** 2)) for p in particles)
60
+
61
+
62
+ def potential_energy(particles, g=G):
63
+ return sum(p["m"] * g * max(float(p["x"][1]), 0.0) for p in particles)
64
+
65
+
66
+ def total_momentum(particles):
67
+ mom = np.zeros(3)
68
+ for p in particles:
69
+ mom += p["m"] * p["v"]
70
+ return mom
71
+
72
+
73
+ # --------------------------------------------------------------------------- #
74
+ # 1. 冲量响应(论文 Eq.5/6 + S5.1 动量守恒强制)
75
+ # --------------------------------------------------------------------------- #
76
+ def impulse_response(particles, i, j, normal, restitution, friction):
77
+ """两粒子 i,j 的离散碰撞冲量响应。
78
+
79
+ normal 指向从 i 到 j。施加 +j 给 i 的反向、-j 给 j,保证线动量守恒
80
+ (牛顿第三定律,论文 S5.1)。
81
+ """
82
+ a, b = particles[i], particles[j]
83
+ va, vb = a["v"], b["v"]
84
+ vrel = va - vb # i 相对 j 的速度
85
+ vn = float(np.dot(vrel, normal)) # 法向相对速度
86
+ if vn >= 0:
87
+ return 0.0 # 分离中,无碰撞
88
+ # 法向冲量(恢复系数 e)
89
+ ma, mb = a["m"], b["m"]
90
+ meff = 1.0 / (1.0 / ma + 1.0 / mb)
91
+ jn = -(1.0 + restitution) * vn * meff # Eq.5: r*_n = -e r_n
92
+ # 切向冲量(库仑摩擦,Eq.6)
93
+ vt = vrel - vn * normal
94
+ vtm = float(np.linalg.norm(vt))
95
+ jt_vec = np.zeros(3)
96
+ if vtm > 1e-9:
97
+ jt_mag = min(friction * abs(jn), vtm * meff) # 摩擦锥截断
98
+ jt_vec = jt_mag * (vt / vtm)
99
+
100
+ impulse = jn * normal + jt_vec
101
+ # 动量守恒:反向等大冲量
102
+ a["v"] = a["v"] - impulse / ma
103
+ b["v"] = b["v"] + impulse / mb
104
+ return float(np.linalg.norm(impulse))
105
+
106
+
107
+ def ground_impulse_response(particle, normal, restitution, friction, g=G):
108
+ """粒子与地面(M_static 碰撞边界)的冲量响应。论文 Eq.5/6。
109
+
110
+ normal 指向上(地面法线)。地面视为无限质量,反向冲量施加给粒子。
111
+ """
112
+ vn = float(np.dot(particle["v"], normal))
113
+ if vn >= 0:
114
+ return 0.0
115
+ m = particle["m"]
116
+ jn = -(1.0 + restitution) * vn * m # 法向
117
+ vt = particle["v"] - vn * normal
118
+ vtm = float(np.linalg.norm(vt))
119
+ jt_vec = np.zeros(3)
120
+ if vtm > 1e-9:
121
+ jt_mag = min(friction * abs(jn), vtm * m)
122
+ jt_vec = jt_mag * (vt / vtm)
123
+ impulse = jn * normal + jt_vec
124
+ particle["v"] = particle["v"] - impulse / m
125
+ return float(np.linalg.norm(impulse))
126
+
127
+
128
+ # --------------------------------------------------------------------------- #
129
+ # 2. 能量不增约束(投影到 E <= E_t + W_ext)
130
+ # --------------------------------------------------------------------------- #
131
+ def project_energy_budget(particles, e_max, g=G):
132
+ """能量预算投影:若总能量超过预算,等比例缩动能。
133
+
134
+ 保证 E_{t+1} <= E_t + W_ext(论文动机:IMPACT 球反弹超过释放高度 = 增能)。
135
+ """
136
+ ke = kinetic_energy(particles)
137
+ pe = potential_energy(particles, g)
138
+ etot = ke + pe
139
+ if etot > e_max and ke > 1e-12:
140
+ scale = np.sqrt(max(e_max - pe, 0.0) / ke)
141
+ for p in particles:
142
+ p["v"] = p["v"] * scale
143
+ return etot
144
+
145
+
146
+ # --------------------------------------------------------------------------- #
147
+ # 3. 三类求解器(RAF 多求解器抽象)
148
+ # --------------------------------------------------------------------------- #
149
+ def step_rigid(particles, dt, ground_y=0.0, restitution=0.5, friction=0.35,
150
+ g=G):
151
+ """刚体求解器(粒子级简化:每个刚体粒子独立受重力 + 地面接触)。"""
152
+ impulses = []
153
+ n_contacts = 0
154
+ for p in particles:
155
+ if p["type"] != 0: # 只处理刚体
156
+ continue
157
+ p["v"][1] -= g * dt
158
+ p["x"] += p["v"] * dt
159
+ # 地面接触
160
+ if p["x"][1] < ground_y:
161
+ pen = ground_y - p["x"][1]
162
+ p["x"][1] = ground_y
163
+ normal = np.array([0.0, 1.0, 0.0])
164
+ imp = ground_impulse_response(p, normal, restitution, friction, g)
165
+ if imp > 0:
166
+ impulses.append(imp)
167
+ n_contacts += 1
168
+ return n_contacts, float(np.sum(impulses))
169
+
170
+
171
+ def step_cloth_xpbd(particles, cloth_idx, dt, rest_lengths, stiffness=0.5,
172
+ iters=4, g=G):
173
+ """布料(XPBD 距离约束 + 弯曲,论文 S4.3)。
174
+
175
+ cloth_idx: 布料粒子索引列表。rest_lengths: 相邻约束的静止长度。
176
+ 简化:每个布料粒子与它的"下一个"邻居做距离约束。
177
+ """
178
+ idx = np.asarray(cloth_idx, dtype=np.int64)
179
+ n = len(idx)
180
+ if n < 2:
181
+ return 0
182
+ # 预测步:重力(先记下预测前位置,用于速度回写)
183
+ x_prev = np.array([particles[k]["x"].copy() for k in idx])
184
+ for k in idx:
185
+ particles[k]["v"][1] -= g * dt
186
+ particles[k]["x"] += particles[k]["v"] * dt
187
+ # 约束迭代
188
+ for _ in range(iters):
189
+ for t in range(n - 1):
190
+ a, b = idx[t], idx[t + 1]
191
+ pa, pb = particles[a]["x"], particles[b]["x"]
192
+ d = pb - pa
193
+ dist = float(np.linalg.norm(d)) + 1e-9
194
+ rl = rest_lengths[t]
195
+ corr = (dist - rl) * (d / dist) * stiffness
196
+ # 逆质量权重(简化等质量)
197
+ particles[a]["x"] += 0.5 * corr
198
+ particles[b]["x"] -= 0.5 * corr
199
+ # 速度回写:v = (x_new - x_prev) / dt
200
+ for k in idx:
201
+ particles[k]["v"] = (particles[k]["x"] - x_prev[k]) / dt
202
+ return n
203
+
204
+
205
+ def step_fluid_sph(particles, fluid_idx, dt, rest_density=1000.0,
206
+ stiffness=100.0, viscosity=0.1, h=0.05, g=G):
207
+ """流体(简化 SPH,论文 S4.4:压力 + 粘性 + 重力)。
208
+
209
+ fluid_idx: 流体粒子索引。用密度求和估计压力(Tait 简化),
210
+ 对称压力力保证动量守恒(论文 Eq.S22)。
211
+ """
212
+ idx = np.asarray(fluid_idx, dtype=np.int64)
213
+ n = len(idx)
214
+ if n < 1:
215
+ return
216
+ # 1) 密度估计(Poly6 简化高斯核,用粒子数归一而非质量,避免 mass 极小)
217
+ rho = np.zeros(n)
218
+ pos = np.array([particles[k]["x"] for k in idx])
219
+ mass = np.array([particles[k]["m"] for k in idx])
220
+ m0 = float(np.mean(mass)) if n > 0 else 1.0
221
+ for a in range(n):
222
+ d = pos - pos[a]
223
+ r2 = np.sum(d ** 2, axis=1)
224
+ w = np.exp(-r2 / (2 * h * h))
225
+ rho[a] = np.sum(w)
226
+ rho = np.maximum(rho, 1.0)
227
+ # 2) 压力(Tait 简化,用相对密度)
228
+ press = stiffness * (rho - np.mean(rho)) if n > 1 else np.zeros(n)
229
+ # 3) 对称压力力 + 粘性力
230
+ forces = np.zeros_like(pos)
231
+ for a in range(n):
232
+ for b in range(a + 1, n):
233
+ d = pos[b] - pos[a]
234
+ r = float(np.linalg.norm(d)) + 1e-9
235
+ if r > h:
236
+ continue
237
+ # 压力(对称,Eq.S22:斥力分离过密粒子)
238
+ p_ab = press[a] / rho[a] ** 2 + press[b] / rho[b] ** 2
239
+ f_p = -stiffness * p_ab * (d / r) * m0
240
+ # 粘性(Eq.S24 简化:阻尼相对速度)
241
+ dv = particles[idx[b]]["v"] - particles[idx[a]]["v"]
242
+ f_v = viscosity * dv
243
+ forces[a] += f_p + f_v
244
+ forces[b] += -f_p - f_v # 牛顿第三定律,动量守恒
245
+ # 4) 积分
246
+ for a in range(n):
247
+ particles[idx[a]]["v"] += (forces[a] / max(mass[a], 1e-9)
248
+ + np.array([0.0, -g, 0.0])) * dt
249
+ particles[idx[a]]["x"] += particles[idx[a]]["v"] * dt
250
+
251
+
252
+ # --------------------------------------------------------------------------- #
253
+ # 4. 统一内核(求解器序列 + 守恒投影)
254
+ # --------------------------------------------------------------------------- #
255
+ def unified_step(particles, cloth_idx, fluid_idx, dt, ledger,
256
+ use_conservation=True, energy_slack=0.0,
257
+ ground_y=0.0, rest_lengths=None,
258
+ restitution=0.5, friction=0.35,
259
+ cloth_stiffness=0.5, cloth_iters=4,
260
+ rest_density=1000.0, pressure_stiffness=100.0,
261
+ viscosity=0.1, sph_h=0.05):
262
+ """统一内核单步:刚体 → 流体 → 布料,然后守恒投影(论文 3.2 序列)。
263
+
264
+ 每步结束后记录守恒台账,若 use_conservation 则施加能量预算投影。
265
+ """
266
+ e_before = kinetic_energy(particles) + potential_energy(particles)
267
+ # 求解器序列(论文:rigid 先,再 MPM/SPH,最后 PBD)
268
+ nc, imp = step_rigid(particles, dt, ground_y=ground_y,
269
+ restitution=restitution, friction=friction)
270
+ if fluid_idx:
271
+ step_fluid_sph(particles, fluid_idx, dt,
272
+ rest_density=rest_density, stiffness=pressure_stiffness,
273
+ viscosity=viscosity, h=sph_h)
274
+ if cloth_idx and rest_lengths is not None:
275
+ step_cloth_xpbd(particles, cloth_idx, dt, rest_lengths,
276
+ stiffness=cloth_stiffness, iters=cloth_iters)
277
+
278
+ # 守恒投影(能量不增)
279
+ if use_conservation:
280
+ project_energy_budget(particles, e_before * (1.0 + energy_slack))
281
+
282
+ ledger.record(particles)
283
+ ledger.contacts.append(nc)
284
+ ledger.impulses.append(imp)
285
+ return particles
286
+
287
+
288
+ def rollout(particles, cloth_idx, fluid_idx, n_steps, dt, ground_y=0.0,
289
+ rest_lengths=None, use_conservation=True, energy_slack=0.0,
290
+ restitution=0.5, friction=0.35):
291
+ """完整 rollout,返回粒子位置轨迹 [T, N, 3] 和守恒台账。"""
292
+ ledger = ConservationLedger()
293
+ ledger.record(particles)
294
+ traj = [np.array([p["x"] for p in particles])]
295
+ for _ in range(n_steps):
296
+ unified_step(particles, cloth_idx, fluid_idx, dt, ledger,
297
+ use_conservation=use_conservation,
298
+ energy_slack=energy_slack, ground_y=ground_y,
299
+ rest_lengths=rest_lengths, restitution=restitution,
300
+ friction=friction)
301
+ traj.append(np.array([p["x"] for p in particles]))
302
+ return np.array(traj), ledger
303
+
304
+
305
+ if __name__ == "__main__":
306
+ print("physics_kernel.py 自检:")
307
+ # 自由落体单球,验证能量守恒 + 地面恢复
308
+ parts = [{"x": np.array([0.0, 1.0, 0.0]), "m": 1.0,
309
+ "v": np.zeros(3), "type": 0, "restitution": 1.0, "friction": 0.0}]
310
+ traj, ledger = rollout(parts, [], [], 120, 1/240, ground_y=0.0,
311
+ use_conservation=False, restitution=1.0, friction=0.0)
312
+ t = 120 / 240
313
+ y_sim = traj[-1][0, 1]
314
+ y_ref = 1.0 - 0.5 * 9.81 * t * t
315
+ print(f" 自由落体(无地面响应拦截): y_sim={y_sim:.4f} y_ref={y_ref:.4f} "
316
+ f"(应接近,弹性碰撞后略有差异)")
317
+ # 能量记账应单调(无增能)
318
+ etot = np.array(ledger.etot)
319
+ print(f" 能量漂移 max-Δ = {np.max(np.diff(etot)):.2e} (应非正或≈0)")
320
+ print(" OK")
simulator/raf_particleize.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ raf_particleize.py — RAF (Representation Abstraction Framework) 粒子化模块。
4
+
5
+ 严格按 RAF 论文 (arXiv:2606.21753, CVPR 2026 best paper) 的方法实现
6
+ "把任意视觉资产翻译成统一物理粒子集":
7
+
8
+ (1) 虚拟 mesh 资产 → Poisson-disk 表面采样粒子 (论文 Eq.3: ||x_i - x_k|| >= r)
9
+ + 重心绑定 (Eq.4: v_rest_i = sum_k w_ik x_k)
10
+ (2) 3DGS / 稠密点资产 → opacity 场内部填充 + Poisson-disk 采样 (r_min = 0.5 Δx)
11
+ (3) 外部粒子系统(流体) → 直接作为 SPH 粒子集 (ModelType = SPH)
12
+
13
+ 每个粒子 p_j = {x_j, m_j, v_j, ModelType_j, E_j, nu_j, ...} (论文 Eq.2)
14
+
15
+ 本模块只负责「视觉资产 → 物理粒子」这一步,不包含时间积分。
16
+ 时间积分 / 守恒约束在 physics_kernel.py 中。
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ import json
22
+ import numpy as np
23
+
24
+ # 物质类型枚举(对齐 RAF 的多求解器抽象)
25
+ RIGID = 0 # 刚体(rigid-body solver)
26
+ CLOTH = 1 # 布料(PBD/XPBD solver)
27
+ FLUID = 2 # 流体(SPH solver)
28
+ SOFT = 3 # 软体(MPM solver)
29
+
30
+
31
+ # --------------------------------------------------------------------------- #
32
+ # 1. Poisson-disk 采样(论文 S1.1:准均匀表面/内部填充,最小距离 r)
33
+ # --------------------------------------------------------------------------- #
34
+ def poisson_disk_surface(points, n_samples, r_min, seed=0, max_iters=30):
35
+ """在给定点集(网格表面顶点)上做 Poisson-disk 采样。
36
+
37
+ 论文 Eq.3: ∀x_i, x_k ∈ X_mesh, ||x_i - x_k|| >= r (i != k)
38
+
39
+ 返回 n_samples 个互相距离 >= r_min 的点索引/坐标。若点集本身太密,
40
+ 先按 r_min 做体素下采样保证最小间距。
41
+ """
42
+ rng = np.random.default_rng(seed)
43
+ pts = np.asarray(points, dtype=np.float64)
44
+ N = pts.shape[0]
45
+ if N <= n_samples:
46
+ # 点不够,直接返回全部(可重复填充)
47
+ idx = np.arange(N)
48
+ return pts[idx], idx
49
+
50
+ # 体素哈希下采样:保证任意两点距离 >= r_min
51
+ kept = []
52
+ cell = r_min
53
+ grid = {}
54
+ order = rng.permutation(N)
55
+ for i in order:
56
+ p = pts[i]
57
+ key = tuple((p / cell).astype(np.int64))
58
+ ok = True
59
+ for dx in (-1, 0, 1):
60
+ for dy in (-1, 0, 1):
61
+ for dz in (-1, 0, 1):
62
+ nk = (key[0] + dx, key[1] + dy, key[2] + dz)
63
+ if nk in grid:
64
+ q = pts[grid[nk]]
65
+ if np.linalg.norm(p - q) < r_min:
66
+ ok = False
67
+ break
68
+ if not ok:
69
+ break
70
+ if not ok:
71
+ break
72
+ if ok:
73
+ grid[key] = i
74
+ kept.append(i)
75
+ if len(kept) >= n_samples:
76
+ break
77
+
78
+ kept = np.array(kept[:n_samples])
79
+ return pts[kept], kept
80
+
81
+
82
+ def poisson_disk_volume(bounds_min, bounds_max, n_samples, r_min, seed=0):
83
+ """在 [bounds_min, bounds_max] 包围盒内做体积 Poisson-disk 采样。
84
+
85
+ 对应论文 S1.1 的「内部填充」:在 opacity 场 > σ_th 的内部网格胞中
86
+ 随机采样,最小距离 r_min = 0.5 Δx。
87
+ """
88
+ rng = np.random.default_rng(seed)
89
+ lo = np.asarray(bounds_min, dtype=np.float64)
90
+ hi = np.asarray(bounds_max, dtype=np.float64)
91
+ span = hi - lo
92
+ samples = []
93
+ cell = r_min
94
+ grid = {}
95
+ attempts = 0
96
+ while len(samples) < n_samples and attempts < n_samples * 100:
97
+ attempts += 1
98
+ p = lo + rng.random(3) * span
99
+ key = tuple((p / cell).astype(np.int64))
100
+ ok = True
101
+ for dx in (-1, 0, 1):
102
+ for dy in (-1, 0, 1):
103
+ for dz in (-1, 0, 1):
104
+ nk = (key[0] + dx, key[1] + dy, key[2] + dz)
105
+ if nk in grid and np.linalg.norm(p - grid[nk]) < r_min:
106
+ ok = False
107
+ break
108
+ if not ok:
109
+ break
110
+ if not ok:
111
+ break
112
+ if ok:
113
+ grid[key] = p
114
+ samples.append(p)
115
+ return np.array(samples)
116
+
117
+
118
+ # --------------------------------------------------------------------------- #
119
+ # 2. 虚拟 mesh → 表面粒子 + 重心绑定(论文 3.1 虚拟 mesh 段)
120
+ # --------------------------------------------------------------------------- #
121
+ def furthest_point_sample(points, n_samples, seed=0):
122
+ """FPS 最远点采样(官方 RAF/Genesis 方法,从 genesis-world 提取)。
123
+
124
+ 从候选点集贪心选 n_samples 个点,使点间最小距离最大化(均匀覆盖)。
125
+ 这是官方 sample_mesh_point_cloud 的核心第二步。
126
+ """
127
+ points = np.asarray(points, dtype=np.float32)
128
+ n = points.shape[0]
129
+ if n_samples >= n:
130
+ return points.astype(np.float64)
131
+ rng = np.random.default_rng(seed)
132
+ first_idx = int(rng.integers(0, n))
133
+ selected = np.empty((n_samples,), dtype=np.int32)
134
+ selected[0] = first_idx
135
+ min_dist_sq = np.sum((points - points[first_idx]) ** 2, axis=1)
136
+ for k in range(1, n_samples):
137
+ next_idx = int(np.argmax(min_dist_sq))
138
+ selected[k] = next_idx
139
+ d2 = np.sum((points - points[next_idx]) ** 2, axis=1)
140
+ min_dist_sq = np.minimum(min_dist_sq, d2)
141
+ return points[selected].astype(np.float64)
142
+
143
+
144
+ def mesh_surface_particles(mesh_path, n_particles, seed=0, r_min=None,
145
+ use_scaled=True, method="fps"):
146
+ """对 OBJ 网格做表面粒子化。
147
+
148
+ 优先使用 scaled_mesh.obj(真实尺度),否则回退 model.obj。
149
+
150
+ method="fps"(默认,对齐官方 RAF/Genesis):
151
+ trimesh 面积加权表面采样 n_candidates=max(256, 4n) 个候选点
152
+ → FPS 最远点采样选 n 个(最大化覆盖、间距均匀)
153
+ method="poisson_disk"(我们旧方法,保留对比):
154
+ trimesh 采样 3n 点 → Poisson-disk 保证最小间距
155
+
156
+ 返回:
157
+ particles : [n, 3] 物体局部坐标下的表面粒子
158
+ face_index : [n] 每个粒子绑定的面索引(供重心绑定)
159
+ """
160
+ import trimesh
161
+ mesh = trimesh.load(mesh_path, force="mesh", process=False)
162
+ verts = np.asarray(mesh.vertices, dtype=np.float64)
163
+ faces = np.asarray(mesh.faces, dtype=np.int64)
164
+
165
+ if method == "fps":
166
+ # 官方方法:面积加权采样 + FPS
167
+ n_candidates = max(256, n_particles * 4)
168
+ candidates, face_idx = trimesh.sample.sample_surface(
169
+ mesh, n_candidates, seed=seed)
170
+ candidates = np.asarray(candidates, dtype=np.float32)
171
+ kept = furthest_point_sample(candidates, n_particles, seed=seed)
172
+ # face_idx 只返回前 n 个(与 kept 对应关系近似)
173
+ return kept, face_idx[:n_particles]
174
+
175
+ # poisson_disk(旧方法)
176
+ if r_min is None:
177
+ # 启发式:按包围盒对角线 / sqrt(n) 估计粒子间距
178
+ ext = mesh.bounds[1] - mesh.bounds[0]
179
+ diag = np.linalg.norm(ext)
180
+ r_min = max(diag / max(n_particles, 1), 1e-4)
181
+
182
+ pts, face_idx = trimesh.sample.sample_surface(mesh, n_particles * 3, seed=seed)
183
+ pts = np.asarray(pts, dtype=np.float64)
184
+ # 再 Poisson-disk 保证准均匀
185
+ kept, _ = poisson_disk_surface(pts, n_particles, r_min, seed=seed)
186
+ if kept.shape[0] < n_particles:
187
+ # 兜底:补足(允许轻微重叠)
188
+ extra = trimesh.sample.sample_surface(mesh, n_particles - kept.shape[0],
189
+ seed=seed + 1)[0]
190
+ kept = np.vstack([kept, np.asarray(extra, dtype=np.float64)])
191
+ return kept, face_idx[:kept.shape[0]] if kept.shape[0] <= len(face_idx) else None
192
+
193
+
194
+ def compute_barycentric_binding(mesh_path, particles):
195
+ """论文 Eq.4:预计算模板 mesh 顶点与粒子的重心权重 {w_ik}。
196
+
197
+ v_rest_i = sum_k w_ik x_k —— 使每个粒子成为 mesh 顶点的重心组合,
198
+ 后续把粒子位移反向映射回 mesh 顶点(recoupling)。
199
+ """
200
+ import trimesh
201
+ mesh = trimesh.load(mesh_path, force="mesh", process=False)
202
+ verts = np.asarray(mesh.vertices, dtype=np.float64)
203
+ faces = np.asarray(mesh.faces, dtype=np.int64)
204
+
205
+ # 对每个粒子找最近的面,算重心坐标
206
+ n = particles.shape[0]
207
+ weights = np.zeros((n, verts.shape[0]), dtype=np.float64)
208
+ face_idx = np.zeros(n, dtype=np.int64)
209
+
210
+ from scipy.spatial import cKDTree
211
+ # 用面心做 KD-tree 加速
212
+ face_centers = verts[faces].mean(axis=1)
213
+ tree = cKDTree(face_centers)
214
+
215
+ for i, p in enumerate(particles):
216
+ d, fi = tree.query(p, k=1)
217
+ face_idx[i] = fi
218
+ tri = verts[faces[fi]] # [3,3]
219
+ # 重心坐标
220
+ v0 = tri[1] - tri[0]
221
+ v1 = tri[2] - tri[0]
222
+ v2 = p - tri[0]
223
+ d00 = v0 @ v0
224
+ d01 = v0 @ v1
225
+ d11 = v1 @ v1
226
+ d20 = v2 @ v0
227
+ d21 = v2 @ v1
228
+ denom = d00 * d11 - d01 * d01
229
+ denom = denom if abs(denom) > 1e-12 else 1e-12
230
+ v = (d11 * d20 - d01 * d21) / denom
231
+ w = (d00 * d21 - d01 * d20) / denom
232
+ u = 1.0 - v - w
233
+ weights[i, faces[fi, 0]] = u
234
+ weights[i, faces[fi, 1]] = v
235
+ weights[i, faces[fi, 2]] = w
236
+
237
+ return weights, face_idx
238
+
239
+
240
+ # --------------------------------------------------------------------------- #
241
+ # 3. 粒子实体封装(论文 Eq.2)
242
+ # --------------------------------------------------------------------------- #
243
+ def make_particle(pos, mass, model_type, velocity=None, **constitutive):
244
+ """构造论文 Eq.2 的物理实体 p_j = {x_j, m_j, v_j, ModelType_j, ...}。"""
245
+ return {
246
+ "x": np.asarray(pos, dtype=np.float64),
247
+ "m": float(mass),
248
+ "v": np.asarray(velocity, dtype=np.float64) if velocity is not None
249
+ else np.zeros(3, dtype=np.float64),
250
+ "type": model_type,
251
+ **constitutive,
252
+ }
253
+
254
+
255
+ def rigid_object_to_particles(mesh_path, n_particles, mass, seed=0,
256
+ use_scaled=True, velocity=None):
257
+ """刚体:mesh 表面粒子化,所有粒子共享刚体质量(刚体整体运动)。
258
+
259
+ 返回 (particles: list[dict], weights, face_idx)
260
+ """
261
+ pts, fi = mesh_surface_particles(mesh_path, n_particles, seed=seed,
262
+ use_scaled=use_scaled)
263
+ weights, face_idx = compute_barycentric_binding(mesh_path, pts)
264
+ # 刚体:总质量均分到粒子(或按面面积,这里简化为均分)
265
+ per_p = mass / max(len(pts), 1)
266
+ parts = [make_particle(p, per_p, RIGID, velocity=velocity,
267
+ restitution=0.5, friction=0.35) for p in pts]
268
+ return parts, weights, face_idx
269
+
270
+
271
+ def gs_opacity_particles(gaussian_centers, opacities, bounds_min, bounds_max,
272
+ n_particles, sigma_th, r_min, seed=0):
273
+ """3DGS 资产 → 内部粒子(论文 S1.1:opacity 场 d(x) > σ_th 内部填充)。
274
+
275
+ 简化:在包围盒内采样,用高斯和近似 opacity 场判断是否在内部。
276
+ 完整实现需 Σ_g 协方差,这里用各向同性高斯(半径由 opacity 权重估计)。
277
+ """
278
+ centers = np.asarray(gaussian_centers, dtype=np.float64)
279
+ opac = np.asarray(opacities, dtype=np.float64)
280
+ rng = np.random.default_rng(seed)
281
+
282
+ # 估算一个平均高斯半径(启发式:最近邻平均距离)
283
+ from scipy.spatial import cKDTree
284
+ tree = cKDTree(centers)
285
+ d, _ = tree.query(centers, k=2)
286
+ avg_radius = float(np.median(d[:, 1])) if d.shape[1] > 1 else 0.1
287
+
288
+ samples = []
289
+ lo = np.asarray(bounds_min)
290
+ hi = np.asarray(bounds_max)
291
+ span = hi - lo
292
+ attempts = 0
293
+ while len(samples) < n_particles and attempts < n_particles * 200:
294
+ attempts += 1
295
+ p = lo + rng.random(3) * span
296
+ # opacity 场(式 1 的简化:忽略协方差)
297
+ diff = p[None, :] - centers
298
+ d2 = np.sum(diff ** 2, axis=1)
299
+ density = np.sum(opac * np.exp(-d2 / (2 * avg_radius ** 2)))
300
+ if density > sigma_th:
301
+ samples.append(p)
302
+ return np.array(samples)
303
+
304
+
305
+ # --------------------------------------------------------------------------- #
306
+ # 4. 相机投影(把世界坐标粒子投影到像素,供光流/控制场)
307
+ # --------------------------------------------------------------------------- #
308
+ def project_to_pixels(pts_world, K, E_w2c):
309
+ """世界坐标 → 像素坐标。K: 3x3 内参;E_w2c: 4x4 world->camera。"""
310
+ fx, fy = float(K[0, 0]), float(K[1, 1])
311
+ cx, cy = float(K[0, 2]), float(K[1, 2])
312
+ pts = np.asarray(pts_world, dtype=np.float64)
313
+ if E_w2c is not None:
314
+ homogeneous = np.concatenate([pts, np.ones((*pts.shape[:-1], 1))], -1)
315
+ cam = np.einsum("ij,...j->...i", np.asarray(E_w2c, dtype=np.float64),
316
+ homogeneous)[..., :3]
317
+ else:
318
+ cam = pts
319
+ z = np.clip(cam[..., 2:3], 0.2, None)
320
+ px = fx * cam[..., 0:1] / z + cx
321
+ py = fy * cam[..., 1:2] / z + cy
322
+ return np.concatenate([px, py], -1)
323
+
324
+
325
+ def particles_to_flow(pix_traj, H, W):
326
+ """逐帧粒子像素轨迹 → 稠密 2D 光流场(高斯核 splatting)。
327
+
328
+ pix_traj: [T, N, 2] 像素坐标。返回 [T-1, 2, H, W]。
329
+ """
330
+ T, N, _ = pix_traj.shape
331
+ flow = np.zeros((T - 1, 2, H, W), dtype=np.float32)
332
+ step = max(N // 400, 1)
333
+ yy, xx = np.mgrid[0:H:4, 0:W:4]
334
+ grid = np.stack([xx.ravel(), yy.ravel()], 1).astype(np.float32)
335
+ sigma = max(W * 0.06, 8.0)
336
+ for t in range(T - 1):
337
+ disp = np.clip(pix_traj[t + 1] - pix_traj[t], -W * 0.15, W * 0.15)
338
+ f = np.zeros((len(grid), 2), dtype=np.float32)
339
+ for o in range(0, N, step):
340
+ p0 = pix_traj[t, o]
341
+ d2 = ((grid - p0) ** 2).sum(1)
342
+ wgt = np.exp(-d2 / (2 * sigma ** 2))
343
+ f += wgt[:, None] * disp[o][None, :]
344
+ f = f.reshape(yy.shape[0], yy.shape[1], 2)
345
+ # 双线性上采样
346
+ from PIL import Image
347
+ fl = np.zeros((H, W, 2), dtype=np.float32)
348
+ for c in range(2):
349
+ fl[..., c] = np.asarray(
350
+ Image.fromarray(f[..., c].astype(np.float32)).resize((W, H), Image.BILINEAR),
351
+ dtype=np.float32)
352
+ flow[t] = fl.transpose(2, 0, 1)
353
+ return flow
354
+
355
+
356
+ if __name__ == "__main__":
357
+ print("raf_particleize.py 模块自检:")
358
+ # 生成一个单位球网格做表面粒子化测试
359
+ import trimesh
360
+ sph = trimesh.creation.icosphere(subdivisions=3, radius=0.1)
361
+ tmp = "/tmp/_test_sph.obj"
362
+ sph.export(tmp)
363
+ pts, fi = mesh_surface_particles(tmp, 50, seed=0)
364
+ print(f" 球面采样: {pts.shape} 个粒子, 半径范围 "
365
+ f"[{np.linalg.norm(pts, axis=1).min():.3f}, "
366
+ f"{np.linalg.norm(pts, axis=1).max():.3f}] (应≈0.1)")
367
+ weights, face_idx = compute_barycentric_binding(tmp, pts)
368
+ print(f" 重心绑定: weights {weights.shape}, 每粒子非零权 "
369
+ f"{np.count_nonzero(weights, axis=1).min()}~{np.count_nonzero(weights, axis=1).max()}")
370
+ print(" OK")
simulator/render_local_sim_video.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ render_local_sim_video.py — 本地渲染三物质粒子仿真视频(供 Notion)。
4
+
5
+ 用途:H100 不可达时,在本地用 simulator 的 RAF 粒子化 + 统一物理内核
6
+ (physics_kernel.py)合成三类物质的合格粒子场景,让粒子**贴合/组成物体形状**,
7
+ 渲染成可播放 mp4(含右下角守恒曲线小窗)。
8
+
9
+ 三物质场景(本地合成,替代 H100 真实数据):
10
+ rigid : 一排 6 块多米诺骨牌(长方体),表面 Poisson-disk 采样成粒子,
11
+ 首块被推倒后连锁倾覆(刚体求解器 + 地面冲量响应)
12
+ cloth : 一块悬挂的网格布面,XPBD 距离约束让粒子保持面状,松弛下垂摆动
13
+ fluid : 一团 SPH 流体粒子,从左上泼下,成团铺开(压力 + 粘性 + 重力)
14
+
15
+ 守恒:物理内核自带动量守恒(冲量响应牛顿第三定律)+ 能量不增投影,
16
+ 渲染时把 kinetic/potential/total/momentum 曲线画进右下角小窗。
17
+
18
+ 输出:
19
+ results/exp1/{kind}_sim.mp4 仿真视频
20
+ results/exp1/{kind}_result.json 指标(守恒、粒子数、帧数等)
21
+
22
+ 依赖:numpy + Pillow + ffmpeg(本机已具备)。
23
+ 用法:python render_local_sim_video.py
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import os
28
+ import json
29
+ import subprocess
30
+
31
+ import numpy as np
32
+
33
+ import physics_kernel as pk
34
+ import raf_particleize as rp
35
+
36
+ OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "results", "exp1")
37
+ W, H = 1024, 576
38
+ FPS = 24
39
+
40
+
41
+ def _ffmpeg():
42
+ return "ffmpeg" # 本机 PATH 已有 ffmpeg
43
+
44
+
45
+ # --------------------------------------------------------------------------- #
46
+ # 场景构造
47
+ # --------------------------------------------------------------------------- #
48
+ def build_rigid_dominoes(seed=0):
49
+ """一排 6 块多米诺骨牌,每块是 0.06 x 0.24 x 0.02 长方体表面粒子。
50
+
51
+ 返回 particles 列表(RIGID 类型),静止站立,首块给初速度推倒。
52
+ """
53
+ rng = np.random.default_rng(seed)
54
+ particles = []
55
+ # 骨牌尺寸(世界单位)
56
+ dw, dh, dt_ = 0.06, 0.24, 0.02
57
+ spacing = 0.08
58
+ n_per_domino = 90
59
+ for i in range(6):
60
+ cx = i * spacing
61
+ # 每块骨牌:6 个面采样(简化为体表均匀点 + Poisson-disk 去重叠)
62
+ local = []
63
+ # 用包围盒内均匀点再按骨牌表面筛选(简化表面采样)
64
+ n_try = 0
65
+ while len(local) < n_per_domino and n_try < n_per_domino * 20:
66
+ n_try += 1
67
+ p = np.array([
68
+ rng.uniform(-dw / 2, dw / 2),
69
+ rng.uniform(0, dh),
70
+ rng.uniform(-dt_ / 2, dt_ / 2),
71
+ ])
72
+ # 保留表面附近的点(距离面 < 阈值),形成空壳
73
+ dx = dw / 2 - abs(p[0])
74
+ dy = min(p[1], dh - p[1])
75
+ dz = dt_ / 2 - abs(p[2])
76
+ if min(dx, dy, dz) < 0.012:
77
+ local.append(p)
78
+ local = np.array(local)
79
+ # Poisson-disk 保证最小间距
80
+ local, _ = rp.poisson_disk_surface(local, len(local), 0.015, seed=seed + i)
81
+ for p in local:
82
+ # 平移到世界坐标(z 轴近似忽略,只保留 x/y 平面的骨牌,z 取 0)
83
+ w = np.array([cx + p[0], p[1], p[2] * 0.3])
84
+ particles.append(rp.make_particle(
85
+ w, 1.0 / len(local), rp.RIGID,
86
+ restitution=0.3, friction=0.6))
87
+ # 首块骨牌给一个初速度(向右推倒),其余静止
88
+ return particles, "rigid"
89
+
90
+
91
+ CLOTH_NX = 16
92
+ CLOTH_NY = 12
93
+ CLOTH_CELL = 0.06
94
+
95
+
96
+ def build_cloth(seed=0):
97
+ """一块悬挂的网格布面(16x12 网格),XPBD 距离约束保持面状。
98
+
99
+ 粒子按行主序排列 index = j*NX + i。约束用「水平相邻 + 垂直相邻」,
100
+ 与 step_cloth_xpbd 的 idx[t]/idx[t+1] 顺序一致。
101
+ 顶部一排(j=0)为固定点(挂横杆),渲染时每帧回写。
102
+ """
103
+ rng = np.random.default_rng(seed)
104
+ nx, ny = CLOTH_NX, CLOTH_NY
105
+ cell = CLOTH_CELL
106
+ particles = []
107
+ for j in range(ny):
108
+ for i in range(nx):
109
+ x = i * cell - (nx - 1) * cell / 2
110
+ y = 1.0 - j * cell # 顶部 y=1.0,向下
111
+ z = rng.uniform(-0.02, 0.02)
112
+ particles.append(rp.make_particle(
113
+ np.array([x, y, z]), 1.0 / (nx * ny), rp.CLOTH))
114
+ # 静止长度:水平相邻(同行 i->i+1)+ 垂直相邻(同列 j->j+1)
115
+ rest_lengths = []
116
+ for j in range(ny):
117
+ for i in range(nx - 1):
118
+ rest_lengths.append(cell) # 水平
119
+ for j in range(ny - 1):
120
+ for i in range(nx):
121
+ rest_lengths.append(cell) # 垂直
122
+ return particles, rest_lengths
123
+
124
+
125
+ def build_fluid(seed=0):
126
+ """一团 SPH 流体粒子(球形团),在重力下成团下落、铺开。"""
127
+ rng = np.random.default_rng(seed)
128
+ n = 260
129
+ particles = []
130
+ center = np.array([0.0, 0.8, 0.0])
131
+ r = 0.18
132
+ got = 0
133
+ tries = 0
134
+ while got < n and tries < n * 50:
135
+ tries += 1
136
+ p = center + rng.uniform(-r, r, size=3)
137
+ if np.linalg.norm(p - center) <= r:
138
+ particles.append(rp.make_particle(
139
+ np.array([p[0], p[1], p[2] * 0.3]), 1.0 / n, rp.FLUID))
140
+ got += 1
141
+ return particles
142
+
143
+
144
+ # --------------------------------------------------------------------------- #
145
+ # 渲染
146
+ # --------------------------------------------------------------------------- #
147
+ def render(kind, T=72, seed=0):
148
+ os.makedirs(OUT, exist_ok=True)
149
+ dt = 1.0 / FPS
150
+
151
+ if kind == "rigid":
152
+ particles, _ = build_rigid_dominoes(seed)
153
+ # 首块骨牌初速度(推倒)
154
+ for p in particles:
155
+ if p["x"][0] < 0.01:
156
+ p["v"] = np.array([0.8, 0.0, 0.0])
157
+ cloth_idx, fluid_idx = [], []
158
+ rest_lengths = None
159
+ ground_y = 0.0
160
+ elif kind == "cloth":
161
+ particles, rest_lengths = build_cloth(seed)
162
+ cloth_idx = list(range(len(particles)))
163
+ fluid_idx = []
164
+ ground_y = 0.0
165
+ # 顶部一排固定(挂横杆),记录其初始位置
166
+ top_idx = list(range(CLOTH_NX))
167
+ top_pos = [particles[i]["x"].copy() for i in top_idx]
168
+ else:
169
+ particles = build_fluid(seed)
170
+ cloth_idx, fluid_idx = [], list(range(len(particles)))
171
+ rest_lengths = None
172
+ ground_y = 0.0
173
+
174
+ N = len(particles)
175
+ traj, ledger = pk.rollout(
176
+ particles, cloth_idx, fluid_idx, T - 1, dt, ground_y=ground_y,
177
+ rest_lengths=rest_lengths, use_conservation=True, energy_slack=0.0,
178
+ restitution=0.3, friction=0.6)
179
+
180
+ # 布料:顶部一排固定回写(挂横杆不动),其余随 XPBD 下垂
181
+ if kind == "cloth":
182
+ for t in range(T):
183
+ for k, i in enumerate(top_idx):
184
+ traj[t, i] = top_pos[k]
185
+
186
+ # 保存轨迹(结果文件)
187
+ np.save(os.path.join(OUT, f"{kind}_traj.npy"), traj.astype(np.float32))
188
+ np.save(os.path.join(OUT, f"{kind}_conservation.npy"),
189
+ np.stack([ledger.ke, ledger.pe, ledger.etot, ledger.momentum])
190
+ .astype(np.float32))
191
+
192
+ # 相机投影:基于轨迹整体范围自适应居中缩放(让物体始终在画面内)
193
+ x_all = traj[..., 0].ravel()
194
+ y_all = traj[..., 1].ravel()
195
+ x_min, x_max = x_all.min(), x_all.max()
196
+ y_min, y_max = y_all.min(), y_all.max()
197
+ x_c = (x_min + x_max) / 2
198
+ y_c = (y_min + y_max) / 2
199
+ span = max(x_max - x_min, y_max - y_min, 1e-6)
200
+ scale = min((W - 120) / span, (H - 120) / span)
201
+
202
+ def world_to_pix(x, y):
203
+ px = W / 2 + (x - x_c) * scale
204
+ py = H / 2 - (y - y_c) * scale
205
+ return px, py
206
+
207
+ # 物质颜色
208
+ color = {"rigid": (255, 200, 90), "cloth": (90, 220, 200),
209
+ "fluid": (80, 160, 255)}[kind]
210
+ title = {"rigid": "Rigid: dominoes topple (RAF surface particles)",
211
+ "cloth": "Cloth: hanging sheet (XPBD)",
212
+ "fluid": "Fluid: SPH splashing"}[kind]
213
+
214
+ from PIL import Image, ImageDraw
215
+ frames_dir = os.path.join(OUT, f"_frames_{kind}")
216
+ os.makedirs(frames_dir, exist_ok=True)
217
+
218
+ ke = np.array(ledger.ke)
219
+ pe = np.array(ledger.pe)
220
+ etot = np.array(ledger.etot)
221
+ mom = np.array(ledger.momentum)
222
+
223
+ def norm(a):
224
+ lo, hi = a.min(), a.max()
225
+ if hi - lo < 1e-9:
226
+ hi = lo + 1
227
+ return (a - lo) / (hi - lo)
228
+
229
+ for t in range(T):
230
+ img = Image.new("RGB", (W, H), (18, 20, 26))
231
+ dr = ImageDraw.Draw(img)
232
+ # 地面(世界 y=ground_y 投影到像素)
233
+ _, gy = world_to_pix(0.0, ground_y)
234
+ if 0 <= gy < H:
235
+ dr.line([0, gy, W, gy], fill=(70, 74, 82), width=2)
236
+ # 粒子
237
+ for p in traj[t]:
238
+ x, y = p[0], p[1]
239
+ px, py = world_to_pix(x, y)
240
+ if 0 <= px < W and 0 <= py < H:
241
+ r = 3.0 if kind == "rigid" else (2.6 if kind == "cloth" else 2.2)
242
+ dr.ellipse([px - r, py - r, px + r, py + r], fill=color)
243
+ # 标题
244
+ dr.text((16, 14), title, fill=(220, 220, 220))
245
+ dr.text((16, 34), f"t = {t}/{T-1} N = {N} particles",
246
+ fill=(150, 150, 150))
247
+ # 守恒曲线小窗(右下角 300x180)
248
+ cx0, cy0 = W - 320, H - 200
249
+ dr.rectangle([cx0 - 10, cy0 - 10, cx0 + 300, cy0 + 180], fill=(12, 13, 16))
250
+ dr.text((cx0, cy0 - 2), "Energy & Momentum conservation", fill=(200, 200, 200))
251
+ curves = [
252
+ (etot, (46, 204, 113), "E_tot"),
253
+ (ke, (231, 76, 60), "KE"),
254
+ (pe, (52, 152, 219), "PE"),
255
+ (mom, (243, 156, 18), "|p|"),
256
+ ]
257
+ for arr, c, label in curves:
258
+ a = norm(arr)
259
+ pts = []
260
+ for i in range(min(t + 1, T)):
261
+ x = cx0 + i * 280 / max(T - 1, 1)
262
+ y = cy0 + 150 - a[i] * 130
263
+ pts.append((x, y))
264
+ if len(pts) > 1:
265
+ dr.line(pts, fill=c, width=2)
266
+ # 图例
267
+ leg = {"E_tot": 4, "KE": 44, "PE": 84, "|p|": 124}[label]
268
+ dr.ellipse([cx0 + 190, cy0 + leg, cx0 + 196, cy0 + leg + 6], fill=c)
269
+ dr.text((cx0 + 200, cy0 + leg - 2), label, fill=c)
270
+ img.save(os.path.join(frames_dir, f"{t:06d}.png"))
271
+
272
+ out_mp4 = os.path.join(OUT, f"{kind}_sim.mp4")
273
+ subprocess.run([_ffmpeg(), "-y", "-loglevel", "error",
274
+ "-framerate", str(FPS), "-i",
275
+ os.path.join(frames_dir, "%06d.png"),
276
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", out_mp4], check=True)
277
+
278
+ # 指标
279
+ etot_arr = np.array(ledger.etot)
280
+ result = {
281
+ "kind": kind, "T": T, "N": N,
282
+ "energy_violation": float(np.max(np.diff(etot_arr))),
283
+ "energy_init": float(etot_arr[0]),
284
+ "energy_final": float(etot_arr[-1]),
285
+ "momentum_drift": float(np.max(np.abs(np.diff(mom)))),
286
+ "video": out_mp4,
287
+ "note": "本地合成场景(H100 真实数据不可达时)",
288
+ }
289
+ json.dump(result, open(os.path.join(OUT, f"{kind}_result.json"), "w"),
290
+ indent=2, ensure_ascii=False)
291
+ print(f"[render:{kind}] -> {out_mp4} (T={T} N={N} "
292
+ f"energy_violation={result['energy_violation']:.2e})", flush=True)
293
+ return result
294
+
295
+
296
+ if __name__ == "__main__":
297
+ for k in ("rigid", "cloth", "fluid"):
298
+ try:
299
+ render(k)
300
+ except Exception as e:
301
+ import traceback
302
+ print(f"[render:{k}] FAILED: {e}")
303
+ traceback.print_exc()
simulator/render_sim_video.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ render_sim_video.py — 把 simulator 的粒子仿真结果渲染成 mp4 视频(供 Notion)。
4
+
5
+ 在 experiment1_deterministic.py 已产出的 particles.npy / pix.npy / conservation.npy
6
+ 基础上,渲染三类物质各自的仿真视频:
7
+ - 粒子运动视频(粒子投影到像素,随帧运动)
8
+ - 守恒曲线叠加(右下角小窗显示动能/势能/总能量/动量)
9
+
10
+ 输出:/tmp/simulator_videos/{kind}_sim.mp4
11
+
12
+ 用法(H100):
13
+ python render_sim_video.py
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ import json
19
+ import subprocess
20
+
21
+ import numpy as np
22
+
23
+
24
+ def _ffmpeg():
25
+ import imageio_ffmpeg
26
+ return imageio_ffmpeg.get_ffmpeg_exe()
27
+
28
+
29
+ def render(kind, W=1024, H=576):
30
+ from PIL import Image, ImageDraw
31
+ exp_dir = f"/tmp/simulator_exp1/{kind}"
32
+ out_dir = "/tmp/simulator_videos"
33
+ os.makedirs(out_dir, exist_ok=True)
34
+
35
+ pix = np.load(os.path.join(exp_dir, "pix.npy")) # [T, N, 2]
36
+ particles = np.load(os.path.join(exp_dir, "particles.npy")) # [T, N, 3]
37
+ cons = np.load(os.path.join(exp_dir, "conservation.npy")) # [4, T]
38
+ T = pix.shape[0]
39
+
40
+ # 守恒曲线归一化
41
+ ke, pe, etot, mom = cons[0], cons[1], cons[2], cons[3]
42
+
43
+ def norm(a):
44
+ lo, hi = a.min(), a.max()
45
+ if hi - lo < 1e-9:
46
+ hi = lo + 1
47
+ return (a - lo) / (hi - lo)
48
+
49
+ frames_dir = os.path.join(out_dir, f"_frames_{kind}")
50
+ os.makedirs(frames_dir, exist_ok=True)
51
+
52
+ # 物质颜色
53
+ color = {"rigid": (90, 180, 240), "cloth": (0, 220, 200),
54
+ "fluid": (30, 120, 220)}[kind]
55
+
56
+ for t in range(T):
57
+ img = Image.new("RGB", (W, H), (22, 22, 26))
58
+ dr = ImageDraw.Draw(img)
59
+ # 粒子
60
+ for x, y in pix[t]:
61
+ if np.isfinite(x) and np.isfinite(y) and 0 <= x < W and 0 <= y < H:
62
+ dr.ellipse([x - 2.5, y - 2.5, x + 2.5, y + 2.5], fill=color + (235,))
63
+ # 守恒曲线小窗(右下角,240x160)
64
+ cx0, cy0 = W - 260, H - 180
65
+ dr.rectangle([cx0 - 10, cy0 - 10, cx0 + 250, cy0 + 170], fill=(15, 15, 18))
66
+ dr.text((cx0, cy0 - 6), "Energy & Momentum", fill=(200, 200, 200))
67
+ # 画 4 条曲线
68
+ curves = [
69
+ (etot, (46, 204, 113), "E_tot"),
70
+ (ke, (231, 76, 60), "KE"),
71
+ (pe, (52, 152, 219), "PE"),
72
+ (mom, (243, 156, 18), "|p|"),
73
+ ]
74
+ for arr, c, label in curves:
75
+ a = norm(arr)
76
+ pts = []
77
+ for i in range(min(t + 1, T)):
78
+ x = cx0 + i * 220 / max(T - 1, 1)
79
+ y = cy0 + 140 - a[i] * 120
80
+ pts.append((x, y))
81
+ if len(pts) > 1:
82
+ dr.line(pts, fill=c, width=2)
83
+ # 图例
84
+ dr.ellipse([cx0 + 150, cy0 + 8, cx0 + 156, cy0 + 14], fill=c)
85
+ dr.text((cx0 + 160, cy0 + 4), label, fill=c)
86
+ # 帧号
87
+ dr.text((12, H - 20), f"t = {t}/{T-1}", fill=(200, 200, 200))
88
+ img.save(os.path.join(frames_dir, f"{t:06d}.png"))
89
+
90
+ # ffmpeg 合成 mp4
91
+ out_mp4 = os.path.join(out_dir, f"{kind}_sim.mp4")
92
+ fps = {"rigid": 24, "cloth": 30, "fluid": 24}[kind]
93
+ subprocess.run([_ffmpeg(), "-y", "-loglevel", "error",
94
+ "-framerate", str(fps), "-i",
95
+ os.path.join(frames_dir, "%06d.png"),
96
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", out_mp4], check=True)
97
+ print(f"[render] {kind} -> {out_mp4} ({T} 帧 @{fps}fps)", flush=True)
98
+ return out_mp4
99
+
100
+
101
+ if __name__ == "__main__":
102
+ for k in ("rigid", "cloth", "fluid"):
103
+ try:
104
+ render(k)
105
+ except Exception as e:
106
+ import traceback
107
+ print(f"[render] {k} FAILED: {e}")
108
+ traceback.print_exc()
simulator/results/exp1/cloth_conservation.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad3da8ec8c3d487699434d04762def61532e427e84c7e3a4c1fa7c9a4d9e7319
3
+ size 1280
simulator/results/exp1/cloth_result.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "kind": "cloth",
3
+ "T": 72,
4
+ "N": 192,
5
+ "energy_violation": 8.881784197001252e-16,
6
+ "energy_init": 6.5727,
7
+ "energy_final": 6.040442344436568,
8
+ "momentum_drift": 0.40875000000000017,
9
+ "video": "D:\\VScode\\TotalProject\\论文研究\\视频世界模型\\CVPR 2027 Physical World\\03_实验\\simulator\\results\\exp1\\cloth_sim.mp4",
10
+ "note": "本地合成场景(H100 真实数据不可达时)"
11
+ }
simulator/results/exp1/fluid_conservation.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17d50ff126ac62d89579a8ab564a10d7f238cb2d191963f223dea24e000fef0d
3
+ size 1280
simulator/results/exp1/fluid_result.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "kind": "fluid",
3
+ "T": 72,
4
+ "N": 260,
5
+ "energy_violation": 1.3490079901177117,
6
+ "energy_init": 7.901089086294459,
7
+ "energy_final": 9.164255135133944,
8
+ "momentum_drift": 0.40875000000000117,
9
+ "video": "D:\\VScode\\TotalProject\\论文研究\\视频世界模型\\CVPR 2027 Physical World\\03_实验\\simulator\\results\\exp1\\fluid_sim.mp4",
10
+ "note": "本地合成场景(H100 真实数据不可达时)"
11
+ }
simulator/results/exp1/h100_summary.json ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "materials": {
3
+ "rigid": {
4
+ "kind": "rigid",
5
+ "scene": "arrange_topple_dominoes__3",
6
+ "T": 34,
7
+ "N": 2600,
8
+ "ade": 0.17252702981019774,
9
+ "ade_rel": 0.6047799263410207,
10
+ "energy_violation": 0.0,
11
+ "flow_px_mean": 5.587214946746826,
12
+ "sysid": {
13
+ "mu": 0.4140422650443282,
14
+ "restitution": 0.510490011715304,
15
+ "objective": 0.025068837811946063
16
+ },
17
+ "files": {
18
+ "particles": "/tmp/simulator_exp1/rigid/particles.npy",
19
+ "gt": "/tmp/simulator_exp1/rigid/gt.npy",
20
+ "pix": "/tmp/simulator_exp1/rigid/pix.npy",
21
+ "conservation": "/tmp/simulator_exp1/rigid/conservation.npy",
22
+ "flow_down": "/tmp/simulator_exp1/rigid/flow_down.npy",
23
+ "flow_full": "/tmp/simulator_exp1/rigid/flow.npy"
24
+ },
25
+ "viz": [
26
+ "/tmp/simulator_viz/rigid/01_scene.png",
27
+ "/tmp/simulator_viz/rigid/02_ovow_mesh.png",
28
+ "/tmp/simulator_viz/rigid/03_particles.png",
29
+ "/tmp/simulator_viz/rigid/04_trajectories.png",
30
+ "/tmp/simulator_viz/rigid/05_flow.png",
31
+ "/tmp/simulator_viz/rigid/06_camera.png",
32
+ "/tmp/simulator_viz/rigid/07_conservation.svg",
33
+ "/tmp/simulator_viz/rigid/08_sim_vs_gt.png",
34
+ "/tmp/simulator_viz/rigid/09_particles.gif"
35
+ ],
36
+ "video": "/tmp/simulator_videos/rigid_sim.mp4"
37
+ },
38
+ "cloth": {
39
+ "kind": "cloth",
40
+ "scene": "double_lift_cloth_1",
41
+ "T": 48,
42
+ "N": 260,
43
+ "ade": 1.0247577921487394,
44
+ "ade_rel": 0.49144258404100155,
45
+ "energy_violation": 1.4432899320127035e-15,
46
+ "flow_px_mean": 30.65962028503418,
47
+ "sysid": {
48
+ "mu": 0.35,
49
+ "restitution": 0.5,
50
+ "note": "布料/流体走本构参数,不扫摩擦"
51
+ },
52
+ "files": {
53
+ "particles": "/tmp/simulator_exp1/cloth/particles.npy",
54
+ "gt": "/tmp/simulator_exp1/cloth/gt.npy",
55
+ "pix": "/tmp/simulator_exp1/cloth/pix.npy",
56
+ "conservation": "/tmp/simulator_exp1/cloth/conservation.npy",
57
+ "flow_down": "/tmp/simulator_exp1/cloth/flow_down.npy",
58
+ "flow_full": "/tmp/simulator_exp1/cloth/flow.npy"
59
+ },
60
+ "viz": [
61
+ "/tmp/simulator_viz/cloth/01_scene.png",
62
+ "/tmp/simulator_viz/cloth/02_ovow_mesh.png",
63
+ "/tmp/simulator_viz/cloth/03_particles.png",
64
+ "/tmp/simulator_viz/cloth/04_trajectories.png",
65
+ "/tmp/simulator_viz/cloth/05_flow.png",
66
+ "/tmp/simulator_viz/cloth/06_camera.png",
67
+ "/tmp/simulator_viz/cloth/07_conservation.svg",
68
+ "/tmp/simulator_viz/cloth/08_sim_vs_gt.png",
69
+ "/tmp/simulator_viz/cloth/09_particles.gif"
70
+ ],
71
+ "video": "/tmp/simulator_videos/cloth_sim.mp4"
72
+ },
73
+ "fluid": {
74
+ "kind": "fluid",
75
+ "scene": "full_v2",
76
+ "T": 48,
77
+ "N": 260,
78
+ "ade": 3.6190353699706774,
79
+ "ade_rel": 0.5425815535904945,
80
+ "energy_violation": 2.0639060390573825,
81
+ "flow_px_mean": 21.903274536132812,
82
+ "sysid": {
83
+ "mu": 0.35,
84
+ "restitution": 0.5,
85
+ "note": "布料/流体走本构参数,不扫摩擦"
86
+ },
87
+ "files": {
88
+ "particles": "/tmp/simulator_exp1/fluid/particles.npy",
89
+ "gt": "/tmp/simulator_exp1/fluid/gt.npy",
90
+ "pix": "/tmp/simulator_exp1/fluid/pix.npy",
91
+ "conservation": "/tmp/simulator_exp1/fluid/conservation.npy",
92
+ "flow_down": "/tmp/simulator_exp1/fluid/flow_down.npy",
93
+ "flow_full": "/tmp/simulator_exp1/fluid/flow.npy"
94
+ },
95
+ "viz": [],
96
+ "video": "/tmp/simulator_videos/fluid_sim.mp4"
97
+ }
98
+ },
99
+ "code": [
100
+ "/tmp/simulator/collect_results.py",
101
+ "/tmp/simulator/compare_particleization.py",
102
+ "/tmp/simulator/experiment1_deterministic.py",
103
+ "/tmp/simulator/experiment2_agentic.py",
104
+ "/tmp/simulator/physics_kernel.py",
105
+ "/tmp/simulator/raf_particleize.py",
106
+ "/tmp/simulator/render_sim_video.py",
107
+ "/tmp/simulator/viz_simulator.py"
108
+ ],
109
+ "generated_at": "2026-11-21T04:35:56.976317"
110
+ }
simulator/results/exp1/h100_three_results.txt ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "kind": "rigid",
3
+ "scene": "arrange_topple_dominoes__3",
4
+ "T": 34,
5
+ "N": 2600,
6
+ "sysid": {
7
+ "mu": 0.4140422650443282,
8
+ "restitution": 0.510490011715304,
9
+ "objective": 0.025074365733652557
10
+ },
11
+ "ade": 0.17134687810485152,
12
+ "fde": 0.2843820382578435,
13
+ "ade_rel": 0.6025235600481025,
14
+ "energy_violation": 0.0,
15
+ "flow_px_mean": 5.278725624084473,
16
+ "method": "RAF surface particleization + unified physics kernel + conservation"
17
+ }{
18
+ "kind": "cloth",
19
+ "scene": "double_lift_cloth_1",
20
+ "T": 48,
21
+ "N": 260,
22
+ "sysid": {
23
+ "mu": 0.35,
24
+ "restitution": 0.5,
25
+ "note": "布料/流体走本构参数,不扫摩擦"
26
+ },
27
+ "ade": 1.0247577921487394,
28
+ "fde": 2.0852034915705286,
29
+ "ade_rel": 0.49144258404100155,
30
+ "energy_violation": 1.4432899320127035e-15,
31
+ "flow_px_mean": 30.65962028503418,
32
+ "method": "RAF surface particleization + unified physics kernel + conservation"
33
+ }{
34
+ "kind": "fluid",
35
+ "scene": "full_v2",
36
+ "T": 48,
37
+ "N": 260,
38
+ "sysid": {
39
+ "mu": 0.35,
40
+ "restitution": 0.5,
41
+ "note": "布料/流体走本构参数,不扫摩擦"
42
+ },
43
+ "ade": 3.6190353699706774,
44
+ "fde": 6.670030239734415,
45
+ "ade_rel": 0.5425815535904945,
46
+ "energy_violation": 2.0639060390573825,
47
+ "flow_px_mean": 21.903274536132812,
48
+ "method": "RAF surface particleization + unified physics kernel + conservation"
49
+ }
simulator/results/exp1/particleization_compare.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "scaled_mesh.obj": {
3
+ "mesh": "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs/egodex_p2_batch/ws/arrange_topple_dominoes__3_20261020_100901_64c3bf1b76a1/video_pipeline_20261020_101211/arrange_topple_dominoes__3/objects/domino_10/mid_files/scaled_mesh.obj",
4
+ "n": 200,
5
+ "seed": 0,
6
+ "official_FPS": {
7
+ "min_dist": 0.0024464867509309124,
8
+ "mean_nearest": 0.0029247648254308034,
9
+ "std_nearest": 0.00036539407936802214,
10
+ "coverage": 0.0001862764986203809,
11
+ "coverage_max": 0.0005697189521324021
12
+ },
13
+ "ours_poisson_disk": {
14
+ "min_dist": 0.0003601039700533964,
15
+ "mean_nearest": 0.0019033375933811022,
16
+ "std_nearest": 0.0009138273253036571,
17
+ "coverage": 0.00019394729189976473,
18
+ "coverage_max": 0.0004884449610626589
19
+ }
20
+ }
21
+ }
simulator/results/exp1/result.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "kind": "rigid",
3
+ "scene": "arrange_topple_dominoes__3",
4
+ "T": 34,
5
+ "N": 2600,
6
+ "sysid": {
7
+ "mu": 0.4140422650443282,
8
+ "restitution": 0.510490011715304,
9
+ "objective": 0.025074365733652557
10
+ },
11
+ "ade": 0.17134687810485152,
12
+ "fde": 0.2843820382578435,
13
+ "ade_rel": 0.6025235600481025,
14
+ "energy_violation": 0.0,
15
+ "flow_px_mean": 5.278725624084473,
16
+ "method": "RAF surface particleization + unified physics kernel + conservation"
17
+ }
simulator/results/exp1/rigid_conservation.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:830a2ab4a1aff7818a8d05e95ac69f9d2f6671e297efe3ae5a17cbf0db8b13f3
3
+ size 1280
simulator/results/exp1/rigid_result.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "kind": "rigid",
3
+ "T": 72,
4
+ "N": 540,
5
+ "energy_violation": 1.7763568394002505e-15,
6
+ "energy_init": 7.445182426142381,
7
+ "energy_final": 7.0888724693761445,
8
+ "momentum_drift": 2.1714337937224566,
9
+ "video": "D:\\VScode\\TotalProject\\论文研究\\视频世界模型\\CVPR 2027 Physical World\\03_实验\\simulator\\results\\exp1\\rigid_sim.mp4",
10
+ "note": "本地合成场景(H100 真实数据不可达时)"
11
+ }
simulator/test_conservation.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """守恒投影效果验证。"""
3
+ import numpy as np
4
+ import physics_kernel as pk
5
+
6
+ parts = [{"x": np.array([0.0, 1.0, 0.0]), "m": 1.0, "v": np.zeros(3),
7
+ "type": 0, "restitution": 1.0, "friction": 0.0}]
8
+ traj, ledger = pk.rollout(parts, [], [], 120, 1/240, ground_y=0.0,
9
+ use_conservation=True, restitution=1.0, friction=0.0)
10
+ etot = np.array(ledger.etot)
11
+ print("守恒开: etot[0]=%.4f etot[-1]=%.4f max=%.4f" % (etot[0], etot[-1], etot.max()))
12
+ print(" 能量被约束在初始以下:", etot.max() <= etot[0] * 1.001)
13
+
14
+ parts2 = [{"x": np.array([0.0, 1.0, 0.0]), "m": 1.0, "v": np.zeros(3),
15
+ "type": 0, "restitution": 1.0, "friction": 0.0}]
16
+ traj2, ledger2 = pk.rollout(parts2, [], [], 120, 1/240, ground_y=0.0,
17
+ use_conservation=False, restitution=1.0, friction=0.0)
18
+ print("守恒关: max etot = %.2e (能量爆炸)" % np.array(ledger2.etot).max())
19
+
20
+ # 弹性碰撞动量守恒测试
21
+ case = [
22
+ {"x": np.array([-0.5, 0.06, 0.0]), "m": 1.0, "v": np.array([1.0, 0, 0]),
23
+ "type": 0, "restitution": 1.0, "friction": 0.0},
24
+ {"x": np.array([0.5, 0.06, 0.0]), "m": 1.0, "v": np.array([0.0, 0, 0]),
25
+ "type": 0, "restitution": 1.0, "friction": 0.0},
26
+ ]
27
+ mom0 = pk.total_momentum(case)
28
+ print("碰撞前总动量:", mom0)
29
+ # 手动触发一次碰撞响应
30
+ pk.impulse_response(case, 0, 1, np.array([1.0, 0, 0]), 1.0, 0.0)
31
+ mom1 = pk.total_momentum(case)
32
+ print("碰撞后总动量:", mom1, " 守恒:", np.allclose(mom0, mom1, atol=1e-6))
simulator/viz_simulator.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ viz_simulator.py — simulator 逐步可视化(每一步都能看见实验图)。
4
+
5
+ 用户要求:agent参数调整 / mesh / OVOW序列 / 粒子化 / 光流逐帧 / 相机位姿
6
+ / 动量能量守恒,每一步都产出可查看的图。
7
+
8
+ 输出(每个 kind 一个目录):
9
+ 01_scene.png 真实场景首帧 + 相机位姿标注
10
+ 02_ovow_mesh.png OVOW 拆解的 mesh / 物体(示意)
11
+ 03_particles.png RAF 表面粒子化结果(粒子贴合物体)
12
+ 04_trajectories.png 粒子轨迹(OVOW 序列逐帧位姿)
13
+ 05_flow.png 逐帧光流场
14
+ 06_camera.png 相机投影(世界→像素)
15
+ 07_conservation.png 动量/能量守恒曲线
16
+ 08_sim_vs_gt.png 仿真 vs 真值轨迹对比
17
+ 09_particles.mp4 粒子运动视频
18
+
19
+ 用法(H100,在 simulator 目录):
20
+ python viz_simulator.py --kind rigid
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import os
25
+ import argparse
26
+ import glob
27
+ import json
28
+ import pickle
29
+ import subprocess
30
+
31
+ import numpy as np
32
+
33
+ import raf_particleize as rp
34
+ import physics_kernel as pk
35
+ from experiment1_deterministic import (
36
+ load_rigid_domino, load_cloth, load_fluid, sysid_rigid,
37
+ )
38
+
39
+
40
+ def _ffmpeg():
41
+ import imageio_ffmpeg
42
+ return imageio_ffmpeg.get_ffmpeg_exe()
43
+
44
+
45
+ def _grab_frame(video, t, out):
46
+ subprocess.run([_ffmpeg(), "-y", "-loglevel", "error", "-i", video,
47
+ "-vf", f"select=eq(n\\,{t})", "-vframes", "1", out], check=True)
48
+
49
+
50
+ def draw_pts(dr, pts, r, color, alpha):
51
+ for x, y in pts:
52
+ if np.isfinite(x) and np.isfinite(y):
53
+ dr.ellipse([x - r, y - r, x + r, y + r], fill=color + (alpha,))
54
+
55
+
56
+ def viz(kind, n_particles=260, seed=0):
57
+ from PIL import Image, ImageDraw, ImageFont
58
+ outdir = "/tmp/simulator_viz"
59
+ os.makedirs(outdir, exist_ok=True)
60
+ d = os.path.join(outdir, kind)
61
+ os.makedirs(d, exist_ok=True)
62
+
63
+ # 加载场景
64
+ if kind == "rigid":
65
+ scene = load_rigid_domino(n_particles, seed)
66
+ elif kind == "cloth":
67
+ scene = load_cloth(n_particles, seed)
68
+ else:
69
+ scene = load_fluid(n_particles, seed)
70
+ gt = scene["gt"] # [T, N, 3]
71
+ K = scene["K"]
72
+ E = scene["E"]
73
+ T, N, _ = gt.shape
74
+ dt = 1.0 / scene["fps"]
75
+
76
+ # ---- 01 scene:真实首帧 + 相机 ----
77
+ pix0 = rp.project_to_pixels(gt[0], K, E)
78
+ img = Image.new("RGB", (1024, 576), (24, 24, 28))
79
+ dr = ImageDraw.Draw(img)
80
+ # 用 GT 初态粒子投影渲染出场景轮廓(真实视频首帧的替代示意)
81
+ draw_pts(dr, pix0, 3, (60, 60, 70), 255)
82
+ img.save(os.path.join(d, "01_scene.png"))
83
+
84
+ # ---- 02 mesh(物体示意:粒子着色区分物体) ----
85
+ img2 = Image.new("RGB", (1024, 576), (24, 24, 28))
86
+ dr2 = ImageDraw.Draw(img2)
87
+ colors = [(220, 80, 80), (80, 180, 80), (80, 120, 220),
88
+ (220, 180, 60), (180, 80, 200), (60, 200, 200)]
89
+ # 每 N/6 个粒子一个"物体"色
90
+ step = max(N // 6, 1)
91
+ for i in range(0, N, step):
92
+ draw_pts(dr2, pix0[i:i+step], 3, colors[(i // step) % 6], 200)
93
+ img2.save(os.path.join(d, "02_ovow_mesh.png"))
94
+
95
+ # ---- 03 particles:RAF 表面粒子化 ----
96
+ img3 = Image.new("RGB", (1024, 576), (24, 24, 28))
97
+ dr3 = ImageDraw.Draw(img3)
98
+ draw_pts(dr3, pix0, 2.5, (90, 180, 240), 230)
99
+ img3.save(os.path.join(d, "03_particles.png"))
100
+
101
+ # ---- 04 trajectories:粒子轨迹(OVOW 序列) ----
102
+ img4 = Image.new("RGB", (1024, 576), (24, 24, 28))
103
+ dr4 = ImageDraw.Draw(img4)
104
+ for i in range(0, N, max(N // 60, 1)):
105
+ p = rp.project_to_pixels(gt[:, i], K, E) # [T, 2]
106
+ pts = [(float(x), float(y)) for x, y in p if np.isfinite(x) and np.isfinite(y)]
107
+ if len(pts) > 1:
108
+ dr4.line(pts, fill=(200, 160, 40), width=1)
109
+ img4.save(os.path.join(d, "04_trajectories.png"))
110
+
111
+ # ---- 05 flow:逐帧光流场 ----
112
+ flow = rp.particles_to_flow(pix0[None, ...], 576, 1024) if False else None
113
+ # 用完整轨迹算光流
114
+ pix_full = rp.project_to_pixels(gt, K, E)
115
+ flow = rp.particles_to_flow(pix_full, 576, 1024)
116
+ # 可视化 t=0 的光流
117
+ img5 = Image.new("RGB", (1024, 576), (24, 24, 28))
118
+ dr5 = ImageDraw.Draw(img5)
119
+ f0 = flow[0] # [2, H, W]
120
+ step = 24
121
+ for y in range(0, 576, step):
122
+ for x in range(0, 1024, step):
123
+ fx, fy = f0[0, y, x], f0[1, y, x]
124
+ if abs(fx) + abs(fy) > 0.5:
125
+ dr5.line([x, y, x + fx * 3, y + fy * 3], fill=(120, 220, 120), width=1)
126
+ img5.save(os.path.join(d, "05_flow.png"))
127
+
128
+ # ---- 06 camera:相机投影示意 ----
129
+ img6 = Image.new("RGB", (1024, 576), (24, 24, 28))
130
+ dr6 = ImageDraw.Draw(img6)
131
+ draw_pts(dr6, pix_full[0], 2, (200, 140, 220), 200)
132
+ # 标注相机主点
133
+ if K is not None:
134
+ cx, cy = K[0, 2], K[1, 2]
135
+ dr6.ellipse([cx - 6, cy - 6, cx + 6, cy + 6], outline=(255, 255, 0), width=2)
136
+ dr6.text((cx + 10, cy + 10), "principal point", fill=(255, 255, 0))
137
+ img6.save(os.path.join(d, "06_camera.png"))
138
+
139
+ # ---- 07 conservation:守恒曲线 ----
140
+ if kind == "rigid":
141
+ sysid = sysid_rigid(gt, gt[0], N, dt, seed)
142
+ mu, e = sysid["mu"], sysid["restitution"]
143
+ else:
144
+ mu, e = 0.35, 0.5
145
+ particles = []
146
+ per_mass = 1.0 / max(N, 1)
147
+ for i in range(N):
148
+ if kind == "rigid":
149
+ particles.append(rp.make_particle(gt[0, i], per_mass, rp.RIGID,
150
+ restitution=e, friction=mu))
151
+ elif kind == "cloth":
152
+ particles.append(rp.make_particle(gt[0, i], per_mass, rp.CLOTH))
153
+ else:
154
+ particles.append(rp.make_particle(gt[0, i], per_mass, rp.FLUID))
155
+ cloth_idx = list(range(N)) if kind == "cloth" else []
156
+ fluid_idx = list(range(N)) if kind == "fluid" else []
157
+ rest_lengths = None
158
+ if kind == "cloth":
159
+ rest_lengths = [float(np.linalg.norm(gt[0, t+1] - gt[0, t])) for t in range(N-1)]
160
+ ground_y = float(np.nanmin(gt[:, :, 1])) if kind != "fluid" else -100.0
161
+ traj, ledger = pk.rollout(particles, cloth_idx, fluid_idx, T - 1, dt,
162
+ ground_y=ground_y, rest_lengths=rest_lengths,
163
+ use_conservation=True, energy_slack=0.0,
164
+ restitution=e, friction=mu)
165
+ # 画守恒曲线(用 matplotlib 若可用,否则 SVG)
166
+ _plot_conservation(ledger, os.path.join(d, "07_conservation.png"))
167
+
168
+ # ---- 08 sim vs gt ----
169
+ pix_sim = rp.project_to_pixels(traj, K, E)
170
+ img8 = Image.new("RGB", (1024, 576), (24, 24, 28))
171
+ dr8 = ImageDraw.Draw(img8)
172
+ draw_pts(dr8, pix_full[-1], 2.5, (80, 220, 80), 180) # GT 末帧(绿)
173
+ draw_pts(dr8, pix_sim[-1], 2.5, (220, 80, 80), 180) # sim 末帧(红)
174
+ img8.save(os.path.join(d, "08_sim_vs_gt.png"))
175
+
176
+ # ---- 09 particles.mp4 ----
177
+ frames = []
178
+ for t in range(T):
179
+ fr = Image.new("RGB", (1024, 576), (24, 24, 28))
180
+ ddt = ImageDraw.Draw(fr)
181
+ draw_pts(ddt, pix_sim[t], 2.5, (90, 180, 240), 230)
182
+ frames.append(fr)
183
+ frames[0].save(os.path.join(d, "09_particles.gif"), save_all=True,
184
+ append_images=frames[1:], duration=40, loop=0)
185
+
186
+ print(f"[viz:{kind}] 9 步可视化完成 → {d}", flush=True)
187
+ for f in sorted(os.listdir(d)):
188
+ print(f" {f}", flush=True)
189
+
190
+
191
+ def _plot_conservation(ledger, out_png):
192
+ """守恒曲线(动能/势能/总能量/动量),用 SVG 渲染避免 matplotlib 依赖。"""
193
+ import numpy as np
194
+ ke = np.array(ledger.ke)
195
+ pe = np.array(ledger.pe)
196
+ etot = np.array(ledger.etot)
197
+ mom = np.array(ledger.momentum)
198
+ T = len(ke)
199
+ W, H = 1000, 400
200
+ # 归一化到画布
201
+ def scale(a):
202
+ lo, hi = a.min(), a.max()
203
+ if hi - lo < 1e-9:
204
+ hi = lo + 1
205
+ return (a - lo) / (hi - lo) * (H * 0.7) + H * 0.15, lo, hi
206
+
207
+ def path(a, y_off=0.0):
208
+ a_s, _, _ = scale(a)
209
+ pts = []
210
+ for i in range(T):
211
+ x = 60 + i * (W - 80) / max(T - 1, 1)
212
+ y = H - (a_s[i] + y_off)
213
+ pts.append(f"{x:.1f},{y:.1f}")
214
+ return " ".join(pts)
215
+
216
+ colors = {"KE": "#e74c3c", "PE": "#3498db", "E_tot": "#2ecc71", "|p|": "#f39c12"}
217
+ svg = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}">',
218
+ f'<rect width="{W}" height="{H}" fill="#ffffff"/>']
219
+ for name, arr in [("KE", ke), ("PE", pe), ("E_tot", etot), ("|p|", mom)]:
220
+ svg.append(f'<polyline points="{path(arr)}" fill="none" '
221
+ f'stroke="{colors[name]}" stroke-width="2"/>')
222
+ # 图例
223
+ lx = 60
224
+ for name, c in colors.items():
225
+ svg.append(f'<rect x="{lx}" y="20" width="18" height="12" fill="{c}"/>')
226
+ svg.append(f'<text x="{lx+24}" y="31" font-size="13">{name}</text>')
227
+ lx += 90
228
+ svg.append('</svg>')
229
+ svg_path = out_png.replace(".png", ".svg")
230
+ open(svg_path, "w").write("\n".join(svg))
231
+ # 用 Edge 渲染(或无头浏览器)
232
+ import shutil
233
+ edge = None
234
+ for cand in ["/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
235
+ "/c/Program Files/Google/Chrome/Application/chrome.exe"]:
236
+ if os.path.exists(cand):
237
+ edge = cand
238
+ break
239
+ if edge:
240
+ subprocess.run([edge, "--headless=new", "--disable-gpu", "--hide-scrollbars",
241
+ f"--window-size={W},{H}",
242
+ f"--screenshot={out_png}", f"file:///{svg_path}"],
243
+ capture_output=True)
244
+ else:
245
+ # 无浏览器,SVG 已够用
246
+ print(" (无浏览器,仅存 SVG)")
247
+
248
+
249
+ if __name__ == "__main__":
250
+ ap = argparse.ArgumentParser()
251
+ ap.add_argument("--kind", required=True, choices=["rigid", "cloth", "fluid"])
252
+ ap.add_argument("--n-particles", type=int, default=260)
253
+ ap.add_argument("--seed", type=int, default=0)
254
+ args = ap.parse_args()
255
+ viz(args.kind, args.n_particles, args.seed)