동작 원리
- 입력움직일 물체와 닿을 면
.usda · 강체 · 충돌체 · 물리 재질강체는 움직일 물체입니다. 충돌체는 엔진이 물체끼리 닿는 면을 찾는 데 씁니다.
- 처리물리 엔진으로 한 단계 계산
중력 → 접촉 → 다음 위치중력이 물체를 아래로 당깁니다. 닿았을 때 얼마나 미끄러지고 튀는지는 마찰과 반발 값에 달려 있습니다.
- 출력화면과 위치 기록 확인
뷰포트 · capture.json · 위치 배열어디에 멈추고 얼마나 미끄러졌는지 화면에서 보고 파일에 남은 좌표로 비교합니다.
화면에 보이는 모양과 물체가 닿는 모양
메시는 화면에 그릴 표면, 충돌체는 물리 엔진이 거리와 접촉을 계산하는 형상입니다. 단순한 상자 충돌체를 쓰면 계산이 가벼워지지만 실제 물체와 위치나 크기가 어긋날 수 있습니다. 강체를 적용한 물체의 상태에는 위치·방향·속도 등이 들어 있습니다. 엔진은 한 스텝 동안 중력으로 상태를 바꾼 뒤, 접촉이 발견되면 물체가 겹쳐 들어가지 않도록 접촉 반응을 계산합니다. 마찰은 접촉면을 따라 미끄러지는 움직임에, 반발계수는 닿은 뒤 튀어 오르는 움직임에 영향을 줍니다. Isaac Sim 물리 구성 요소
두 높이의 차이는 어떤 데이터에 나타나나요?
| 충돌체 설정 | 실행 기록의 값 | 화면에서 볼 것 |
|---|---|---|
| 보이는 상판과 정렬 | aligned ≈ 0.80 m |
탐침이 보이는 상판에 닿습니다. |
| 충돌체만 12cm 위로 이동 | raised ≈ 0.92 m |
탐침이 상판 위 공중에서 멈춘 것처럼 보입니다. |
| 상판 충돌체 비활성화 | disabled ≈ 0 m |
탐침이 상판을 지나 바닥까지 내려갑니다. |
위 값은 각 탐침 밑면의 최종 월드 Z 좌표입니다. 마찰 실험에서는 멈출 때까지의 이동 거리, 반발 실험에서는 첫 접촉 이후의 최대 중심 높이를 비교합니다. 같은 장면을 PhysX와 Newton에 넣는 별도 실험은 120Hz에서 240스텝을 진행하므로 비교 구간은 2초입니다. 마지막 높이가 비슷해도 다른 축의 위치는 달라질 수 있습니다. 비교에 사용한 초기 조건
처음이면 실습 파일부터 받기
GPU 실습은 Isaac Sim을 실행할 머신에서 터미널을 엽니다. CPU 실습은 지금 쓰는 컴퓨터에서 해도 됩니다. 아래 명령은 한 줄씩 입력하고 Enter를 누르세요. 여러 줄짜리 명령 블록은 통째로 복사해도 됩니다.
cd "$HOME"
git clone https://github.com/james-joobs/awesome-nvidia-physical-ai.git
cd awesome-nvidia-physical-ai
pwd
홈 폴더에 받는 예입니다. 이미 내려받았다면 git clone은 건너뛰고 내 실습 폴더로 이동합니다. 새 터미널을 열 때마다 pwd의 출력 끝이 awesome-nvidia-physical-ai인지 확인하세요. 그래야 labs/로 시작하는 파일을 찾을 수 있습니다.
따라 하기
준비물 · Isaac Sim 6.1과 이 레포의 장면 폴더를 준비합니다. Isaac Sim에서 USD 여는 법을 먼저 볼 수 있습니다.
1. 창에서 충돌체 비교하기
- Isaac Sim에서 File → Open으로
labs/physics/scenes/simready-live.usda를 엽니다. 옆의simready-before.usda와simready-after.usda는 장면이 참조하는 파일이니 같은 폴더에 둡니다. - 뷰포트의 카메라 메뉴에서 FilmCamera를 고른 뒤 Play를 누릅니다. 두 물체가 같은 높이에 멈추는지 보세요.
- Stop을 눌러 초기 상태로 돌아갑니다.
collider-live.usda를 열면 충돌체를 올렸을 때와 껐을 때도 비교할 수 있습니다.
2. 좌표를 파일로 저장하기
Linux X11에서 영상을 남기려면 Isaac Lab Python 환경이 활성화된 터미널에서 이 레포로 이동합니다. command -v ffmpeg에 경로가 나오는지 확인한 뒤 아래 명령을 붙여 넣습니다. --takes simready offset은 방금 본 두 장면만 고릅니다.
python labs/physics/capture_gui.py labs/physics/scenes ./runs/physics "$(command -v ffmpeg)" \
--plan labs/physics/takes.json --takes simready offset --viz kit
뉴턴과 PhysX의 계산을 숫자로 비교하려면 공통 설정 scene.json을 읽는 PhysX·Newton 스크립트를 각 엔진의 Python 환경에서 실행합니다. 두 스크립트는 결과 폴더 경로를 인자로 받고 위치 배열을 저장합니다. SimReady 검증 · PhysX · Newton XPBD
테스트 결과
SimReady 구슬의 최종 중심 높이는 14cm 차이 났습니다. 충돌체가 맞는 경우, 12cm 올린 경우, 충돌체를 끈 경우에 물체 바닥은 각각 약 0.80m, 0.92m, 0m에서 멈췄습니다. 마찰이 커지면 이동 거리가 57.0cm에서 25.5cm, 11.4cm로 줄었고 반발계수가 커지면 첫 반동이 높아졌습니다. capture.json과 물리 샘플을 촬영 당시 측정값과 비교할 수 있습니다.
실행 영상과 기록
실습 소스 코드
takes.json
GitHub에서 파일 보기[
["simready", "simready-live", "FilmCamera", 0, 1, 7.4],
["offset", "collider-live", "FilmCamera", 0, 1, 7],
["friction", "friction-live", "FilmCamera", 0, 1, 6],
["bounce", "bounce-live", "FilmCamera", 0, 1, 7],
["solver-replay", "physics-solvers", "FilmCamera", 0, 1, 7]
]
capture_gui.py
GitHub에서 파일 보기"""Play the USD takes in the Isaac Sim GUI and capture its actual window."""
import argparse
import json
import os
from importlib.metadata import version
from pathlib import Path
import subprocess
import time
import traceback
from isaaclab.app import AppLauncher
TAKES = [
("01-alarm-wide", "runaway-alarm", "FilmCamera", 0.0, 1.0, 9.0),
("02-alarm-fall", "runaway-alarm", "FallCamera", 1.90, .78, 5.5),
("03-drawer-wide", "snack-guard", "FilmCamera", 0.0, 1.0, 7.0),
("04-drawer-close", "snack-guard", "DrawerCamera", .65, .8, 5.0),
("05-desk-cleanup", "desk-cleanup", "FilmCamera", 0.0, .90, 7.0),
("06-collider-offset", "collider-offset", "FilmCamera", 0.0, 1.0, 7.0),
("07-physx-newton", "physics-solvers", "FilmCamera", 0.0, 1.0, 7.0),
("08-collider-live", "collider-live", "FilmCamera", 0.0, 1.0, 7.0),
]
def window_id():
deadline = time.monotonic() + 12
while time.monotonic() < deadline:
tree = subprocess.check_output(["xwininfo", "-root", "-tree"], text=True)
for row in tree.splitlines():
if '"Isaac Lab ' in row and 'mutter-x11-frames' not in row:
return str(int(row.split()[0], 16))
app.update()
raise RuntimeError("Could not find Isaac Sim's native Kit window")
def pump(seconds):
end = time.monotonic() + seconds
while time.monotonic() < end:
app.update()
def summarize_live(stage_name, samples):
if stage_name == "simready-live":
positions = [xyz[2] for xyz in samples[-1]["positions_m"]]
assert abs(positions[0] - .844) < .016 and abs(positions[1] - .984) < .016, positions
return {"probe_center_z_m": positions, "height_difference_m": positions[1] - positions[0]}
if stage_name == "friction-live":
initials = [-.80] * 3
travel = [samples[-1]["positions_m"][i][0] - initials[i] for i in range(3)]
assert travel[0] > travel[1] + .10 > travel[2] + .17 and travel[2] > .035, travel
return {"coefficients": [.16, .35, .75], "distances_m": travel}
peak = []
for index in range(3):
heights = [sample["positions_m"][index][2] for sample in samples]
first = next(i for i, z in enumerate(heights) if z < .945)
peak.append(max(heights[first + 2:]))
assert peak[1] > peak[0] + .09 and peak[2] > peak[1] + .18, peak
return {"coefficient_of_restitution": [0, .55, .85], "peak_center_z_m_after_initial_contact": peak}
def capture(name, stage_name, camera, begin, speed, duration, window, context, timeline, args):
from omni.kit.viewport.utility import get_active_viewport
desired = str(args.scenes.resolve() / f"{stage_name}.usda")
stage = context.get_stage()
if stage and stage.GetRootLayer().realPath == desired and stage_name.endswith("-live"):
timeline.stop()
timeline.commit()
context.close_stage()
app.update()
stage = None
if not stage or stage.GetRootLayer().realPath != desired:
assert context.open_stage(desired), desired
camera_path = f"/World/{camera}"
deadline = time.monotonic() + 15
while time.monotonic() < deadline:
app.update()
stage = context.get_stage()
if stage and stage.GetRootLayer().realPath == desired and stage.GetPrimAtPath(camera_path):
break
else:
raise RuntimeError(f"Camera {camera_path} never loaded from {desired}")
get_active_viewport().camera_path = camera_path
timeline.pause()
timeline.set_current_time(begin)
timeline.commit()
pump(1.30)
last = stage.GetEndTimeCode() / stage.GetTimeCodesPerSecond()
live = stage_name.endswith("-live")
started_physics = False
live_samples = []
inspector = None
if live:
from omni.physx import get_physx_interface
inspector = get_physx_interface()
print(f"TAKE_START {name} camera={camera_path} duration={duration:.2f}s", flush=True)
output = args.output / f"{name}.mp4"
with (args.output / f"{name}.capture.log").open("w") as log:
recorder = subprocess.Popen([
str(args.ffmpeg), "-nostdin", "-hide_banner", "-loglevel", "warning", "-y",
"-f", "x11grab", "-draw_mouse", "0", "-framerate", "30",
"-window_id", window, "-i", f"{os.environ['DISPLAY']}.0", "-t", str(duration),
"-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2", "-c:v", "libx264", "-preset", "ultrafast",
"-crf", "17", "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(output),
], stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
started = time.monotonic()
updates = 0
while recorder.poll() is None:
wall = time.monotonic() - started
if wall > duration + 12:
recorder.terminate()
recorder.wait(timeout=8)
raise RuntimeError(f"Screen recorder timed out during {name}")
if live:
if not started_physics and wall >= .72:
timeline.set_looping(False)
timeline.play()
timeline.commit()
started_physics = True
else:
offset = max(0, wall - .48)
timeline.set_current_time(min(last, begin + offset * speed))
timeline.commit()
app.update()
updates += 1
if inspector and started_physics and stage_name != "collider-live" and updates % 2 == 0:
count = 2 if stage_name == "simready-live" else 3
positions = [inspector.get_rigidbody_transformation(f"/World/Trial_{i}/Body") for i in range(count)]
if all(value["ret_val"] for value in positions):
live_samples.append({"time_s": timeline.get_current_time(),
"positions_m": [list(value["position"]) for value in positions]})
assert recorder.returncode == 0 and output.stat().st_size > 50_000, name
actual = timeline.get_current_time()
live_results = None
if stage_name == "collider-live":
live_results = {}
for case, expected in (("aligned", .80), ("raised", .92), ("disabled", 0)):
pose = inspector.get_rigidbody_transformation(f"/World/ColliderCase_{case}/Part")
assert pose["ret_val"], case
bottom = float(pose["position"][2]) - .06
assert abs(bottom - expected) < .02, (case, bottom, expected)
live_results[case] = bottom
elif live:
assert len(live_samples) > 30
live_results = summarize_live(stage_name, live_samples)
(args.output / f"{name}.physics.json").write_text(json.dumps({
"scene": stage_name, "summary": live_results, "samples": live_samples,
}, indent=2) + "\n")
if live:
timeline.pause()
timeline.commit()
print(f"LIVE_PHYSX {live_results}", flush=True)
print(f"TAKE_DONE {name} timeline_end={actual:.3f} updates={updates}", flush=True)
return {"file": output.name, "scene": stage_name, "camera": camera_path,
"playback_speed": speed, "playback_start_s": begin, "playback_end_s": actual, "app_updates": updates,
"live_physx_final_bottom_m": live_results if stage_name == "collider-live" else None,
"live_physx": live_results if stage_name != "collider-live" else None}
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("scenes", type=Path)
parser.add_argument("output", type=Path)
parser.add_argument("ffmpeg", type=Path)
parser.add_argument("--takes", nargs="+")
parser.add_argument("--plan", type=Path, help="JSON take list for a different set of scenes")
AppLauncher.add_app_launcher_args(parser)
args = parser.parse_args()
args.enable_cameras = True
args.output.mkdir(parents=True, exist_ok=True)
launcher = AppLauncher(args)
app = launcher.app
failed = False
try:
import carb
import omni.timeline
import omni.usd
settings = carb.settings.get_settings()
settings.set_bool("/rtx/hydra/readTransformsFromFabricInRenderDelegate", False)
settings.set_bool("/persistent/app/viewport/Viewport/Viewport0/scene/cameras/visible", False)
context = omni.usd.get_context()
timeline = omni.timeline.get_timeline_interface()
window = window_id()
plan = json.loads(args.plan.read_text()) if args.plan else TAKES
selected = [take for take in plan if not args.takes or take[0] in args.takes]
assert selected and (not args.takes or len(selected) == len(set(args.takes)))
metadata = []
for take in selected:
metadata.append(capture(*take, window, context, timeline, args))
(args.output / "capture.json").write_text(json.dumps({
"application": "Isaac Sim GUI (launched by Isaac Lab)", "isaacsim_version": version("isaacsim"),
"recording": "X11 capture of the native application window", "takes": metadata,
}, indent=2) + "\n")
except Exception:
failed = True
traceback.print_exc()
finally:
if failed:
# SimulationApp's fast shutdown can otherwise hide an exception's exit code.
(args.output / "capture-failed").touch()
app.close()
scene.json
GitHub에서 파일 보기{
"gravity": 9.81,
"step_hz": 120,
"frames": 240,
"box_half_extent": 0.086,
"box_density": 450.0,
"friction": 0.55,
"table_pos": [0.0, 0.0, 0.78],
"table_half_extents": [0.60, 0.30, 0.02],
"floor_pos": [0.0, 0.0, -0.025],
"floor_half_extents": [4.0, 4.0, 0.025],
"boxes": [
[-0.13, 0.0, 0.886], [-0.077, 0.0, 1.063],
[-0.021, -0.004, 1.240], [0.039, 0.0, 1.417],
[0.096, 0.005, 1.594], [0.149, 0.01, 1.771]
]
}
run_physx.py
GitHub에서 파일 보기import argparse
import json
from pathlib import Path
from isaacsim import SimulationApp
parser = argparse.ArgumentParser(description="Run the shared box-stack scene using PhysX.")
parser.add_argument("output", type=Path)
output = parser.parse_args().output
output.mkdir(parents=True, exist_ok=True)
app = SimulationApp({"headless": True, "fast_shutdown": True})
import carb
import numpy as np
from omni.physx import get_physx_interface, get_physx_simulation_interface
from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics, UsdShade, UsdUtils
spec = json.loads(Path(__file__).with_name("scene.json").read_text())
carb.settings.get_settings().set_bool("/physics/updateToUsd", True)
stage = Usd.Stage.CreateInMemory()
UsdGeom.SetStageMetersPerUnit(stage, 1.0)
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
UsdGeom.Xform.Define(stage, "/World")
scene = UsdPhysics.Scene.Define(stage, "/World/Physics")
scene.CreateGravityMagnitudeAttr(spec["gravity"])
scene.CreateGravityDirectionAttr(Gf.Vec3f(0, 0, -1))
material = UsdShade.Material.Define(stage, "/World/Contact")
material_api = UsdPhysics.MaterialAPI.Apply(material.GetPrim())
material_api.CreateStaticFrictionAttr(spec["friction"])
material_api.CreateDynamicFrictionAttr(spec["friction"])
material_api.CreateRestitutionAttr(0.0)
def box(name, pos, half_extents, dynamic=False):
path = f"/World/{name}"
body = UsdGeom.Xform.Define(stage, path)
body.AddTranslateOp().Set(Gf.Vec3d(*pos))
collider = UsdGeom.Cube.Define(stage, f"{path}/Shape")
collider.CreateSizeAttr(2.0)
collider.AddScaleOp().Set(Gf.Vec3f(*half_extents))
UsdPhysics.CollisionAPI.Apply(collider.GetPrim())
UsdShade.MaterialBindingAPI.Apply(collider.GetPrim()).Bind(material, materialPurpose="physics")
if dynamic:
UsdPhysics.RigidBodyAPI.Apply(body.GetPrim())
UsdPhysics.MassAPI.Apply(body.GetPrim()).CreateDensityAttr(spec["box_density"])
return path
for part in ("table", "floor"):
box(part, spec[f"{part}_pos"], spec[f"{part}_half_extents"])
half = spec["box_half_extent"]
paths = [box(f"Box{i}", pos, [half] * 3, True) for i, pos in enumerate(spec["boxes"])]
cache = UsdUtils.StageCache.Get()
stage_id = cache.Insert(stage).ToLongInt()
direct = get_physx_simulation_interface()
query = get_physx_interface()
direct.attach_stage(stage_id)
try:
poses = [[[float(x) for x in pos] + [0.0, 0.0, 0.0, 1.0] for pos in spec["boxes"]]]
for frame in range(spec["frames"]):
dt = 1 / spec["step_hz"]
direct.simulate(dt, frame * dt)
direct.fetch_results()
current = []
for path in paths:
pose = query.get_rigidbody_transformation(path)
if not pose["ret_val"]:
raise RuntimeError(f"PhysX returned no pose for {path}")
current.append(list(pose["position"]) + list(pose["rotation"]))
poses.append(current)
if frame in (0, 119, 239):
print(f"PHYSX | step {frame + 1} | top-body z = {current[-1][2]:.4f} m", flush=True)
finally:
direct.detach_stage()
cache.Erase(stage)
poses = np.array(poses, dtype=np.float32)
assert np.isfinite(poses).all()
assert np.max(np.abs(poses[-1, :, :3] - poses[0, :, :3])) > 0.1
np.save(output / "physx-poses.npy", poses)
print(f"PHYSX_DONE Isaac Sim 6.2 | {poses.shape}", flush=True)
app.close()
run_newton.py
GitHub에서 파일 보기import argparse
import json
from pathlib import Path
import newton
import numpy as np
import warp as wp
root = Path(__file__).parent
parser = argparse.ArgumentParser(description="Run the shared box-stack scene using Newton XPBD.")
parser.add_argument("output", type=Path)
output = parser.parse_args().output
output.mkdir(parents=True, exist_ok=True)
spec = json.loads((root / "scene.json").read_text())
builder = newton.ModelBuilder(gravity=(0.0, 0.0, -spec["gravity"]))
shape = newton.ModelBuilder.ShapeConfig(density=spec["box_density"], mu=spec["friction"], restitution=0.0)
def body_transform(pos):
return wp.transform(wp.vec3(*pos), wp.quat_identity())
for part in ("table", "floor"):
x, y, z = spec[f"{part}_half_extents"]
builder.add_shape_box(-1, xform=body_transform(spec[f"{part}_pos"]), hx=x, hy=y, hz=z, cfg=shape)
half = spec["box_half_extent"]
for pos in spec["boxes"]:
body = builder.add_body(xform=body_transform(pos))
builder.add_shape_box(body, hx=half, hy=half, hz=half, cfg=shape)
model = builder.finalize(device="cuda:0")
solver = newton.solvers.SolverXPBD(model, iterations=8)
pipeline = newton.CollisionPipeline(model)
contacts = pipeline.contacts()
state = model.state()
next_state = model.state()
control = model.control()
newton.eval_fk(model, model.joint_q, model.joint_qd, state)
poses = [state.body_q.numpy().copy()]
for frame in range(spec["frames"]):
state.clear_forces()
pipeline.collide(state, contacts)
solver.step(state, next_state, control, contacts, 1 / spec["step_hz"])
state, next_state = next_state, state
poses.append(state.body_q.numpy())
if frame in (0, 119, 239):
print(f"NEWTON XPBD | step {frame + 1} | top-body z = {poses[-1][-1][2]:.4f} m", flush=True)
poses = np.asarray(poses)
assert np.isfinite(poses).all()
assert np.max(np.abs(poses[0, :, :3] - np.asarray(spec["boxes"]))) < 1e-5
assert np.max(np.abs(poses[-1, :, :3] - poses[0, :, :3])) > 0.1
np.save(output / "newton-poses.npy", poses)
print(f"NEWTON_DONE {newton.__version__} | {poses.shape} | {model.device}", flush=True)
