생성한 공간에 로봇을 넣으려면 무엇이 필요할까요?
- 입력좌표계와 크기 기준 정하기
WorldGen RGB·거리 → 정점 8만 개의 텍스처 메시바닥을 평면으로 맞추고 카메라 높이를 1.5m로 가정합니다. 실제 크기를 측정한 값은 아닙니다.
- 처리부딪히는 형상 확인
정적 추정 메시 / 5×4m 바닥 / 추가 시험 상자큐브 낙하와 광선 충돌을 비교합니다. 주행에는 따로 작성한 충돌체를 사용합니다.
- 출력물리 결과를 읽어 다음 제어 명령 계산
자세·경유점 → v, ω → 바퀴 드라이브 → PhysX 자세미리 정한 경유점을 따라갑니다. 실제 GUI에서 관절·접촉을 계산하며 녹화했습니다.
앞에서 만든 실험실은 RGB와 추정 거리로 표현한 표면입니다. 이번에는 이 표면을 Isaac Sim 6.2로 가져와 크기 기준을 정하고, 충돌을 검사한 뒤 이동 로봇을 주행시킵니다. 생성한 메시는 공간의 겉모습을 담당하고, 따로 설정한 충돌체가 접촉을 계산합니다.
1. 좌표계와 크기 기준부터 맞춥니다
WorldGen 거리의 최댓값 20은 정규화 값입니다. 실제 20m라는 뜻이 아닙니다. prepare.py는 카메라 가까이에서 바닥으로 보이는 점을 골라 평면을 반복해서 맞추고, 0.025 원본 단위보다 많이 벗어난 점을 제외합니다. 구한 위쪽 법선은 WorldGen 좌표에서 약 [0.00942, -0.99985, -0.01474]입니다. 이 방향을 Isaac Sim의 +Z 방향에 맞추고, 평면이 Z=0에 오도록 옮깁니다.
그다음 원본 카메라가 바닥에서 1.5m 높이에 있다고 가정합니다. 평면까지의 추정 거리가 0.789658 원본 단위이므로, 원본 1단위를 1.899556m로 환산합니다. 같은 변환을 모든 정점에 적용하고, USD 장면을 metersPerUnit=1, Z-up으로 설정합니다. 화면의 1m 막대와 폭 0.55m인 로봇 몸체는 이렇게 정한 시뮬레이션 크기의 기준입니다. 생성된 방의 실제 크기를 알아낸 것은 아닙니다.
원본 점 [x, y, z]
→ 바닥 평면의 기준점을 빼기
→ 추정한 위쪽 방향을 +Z로 회전
→ 1.899556배 확대
→ 미터 기준으로 정한 Isaac Sim 좌표
사용한 바닥 점들의 평면 오차는 변환 후 RMS 16.0mm입니다. 평면에 얼마나 잘 맞는지를 나타내며 실제 형상 정확도는 아닙니다. 변환한 전체 공간은 X 방향으로 약 44m에 걸쳐 있고, 먼 곳의 왜곡은 남아 있습니다. 이번 로봇 예제에서 확인한 범위는 원래 시점 부근에 따로 만든 5×4m 시험 바닥입니다.
준비한 배열은 points: float32[80000,3], indices: int32[158802,3], uv: float32[80000,2]입니다. points는 정한 미터 기준의 위치이고, indices의 한 행은 삼각형을 이루는 정점 세 개를 가리킵니다. UV 좌표는 파노라마의 어디에서 색을 가져올지 정합니다.
2. 보이는 표면과 부딪히는 표면을 구분합니다
렌더용 메시는 원본 거리 배열을 4픽셀 간격으로 뽑은 정점 80,000개, 삼각형 158,802개입니다. 여기에 파노라마 UV 텍스처를 입힙니다. 평면 배경 이미지가 아니라 실제 깊이가 있는 3D 메시이며, 파노라마 이음새에는 작은 틈이 남습니다. 이번 물리 표현에는 Gaussian splat을 직접 사용하지 않습니다.
세 가지 물리 설정을 실제로 비교했습니다.
| 설정 | 낙하하는 큐브를 받치는 것 | 확인할 내용 |
|---|---|---|
| 렌더용 표면만 배치 | 없음 | 바닥이 보여도 충돌체는 따로 필요함 |
| 가져온 메시를 정적 충돌체로 설정 | 굴곡이 있는 추정 표면 | 접촉은 되지만 형상은 여전히 추정값임 |
| 바닥 충돌체를 따로 작성 | 윗면이 Z=0인 평평한 상자 | 같은 조건으로 로봇을 시험할 기준면 |
비교 실험에서는 가져온 메시에 정적 삼각형 메시 충돌체를 적용할 수 있습니다. 방 전체를 동적 convex hull 하나로 만들면 내부의 빈 공간을 보존할 수 없습니다. 주행 실험에서는 렌더용 메시의 충돌을 끄고 바닥과 추가로 만든 주황색 시험 상자를 사용합니다. 상자는 0.45×0.80×0.60m이며, 생성 이미지에서 자동으로 찾아낸 물체가 아닙니다. 다른 가구의 충돌체는 검증하지 않았습니다. NVIDIA 충돌체 기초

3. 바퀴 명령이 실제 움직임으로 이어집니다
로봇은 USD 강체와 회전 관절로 직접 구성한 간단한 차동구동 AMR입니다. Jetbot이나 GR00T 정책을 쓴 예제는 아닙니다. 몸체 질량은 8kg, 구동 바퀴는 각각 0.3kg이며 바퀴 반지름은 0.11m, 두 바퀴 사이 거리는 0.52m입니다. 뒤쪽의 마찰이 작은 받침이 균형을 잡습니다.
현재 몸체 위치·방향 + 다음 경유점
→ 목표 방향과의 차이
→ 전진 속도 v(m/s), 회전 속도 ω(rad/s)
→ 왼쪽·오른쪽 바퀴의 각속도(rad/s)
→ USD 관절 드라이브의 목표 속도(도/s)
→ PhysX가 관절·마찰·충돌 계산
→ 실제 몸체 자세를 읽어 다음 명령 계산
직진 명령 v=0.32m/s, ω=0이면 두 바퀴 모두 약 2.91rad/s, 즉 166.7도/s를 목표로 회전합니다. 두 바퀴의 속도에 차이를 주면 방향이 바뀝니다. 제어기는 시뮬레이터에서 읽은 자세로 미리 정한 경유점을 따라갑니다. 카메라 영상을 보거나, 정책을 학습하거나, 스스로 경로를 찾는 것은 아닙니다. 코드가 몸체를 목표 좌표로 직접 옮기는 대신 시뮬레이터가 바퀴 접촉으로 생기는 움직임을 계산합니다. NVIDIA 차동구동 설명
점선은 직진하다 막힌 실행이고, 초록색은 접촉 후 회복 주행입니다. 선은 실제 몸체 중심의 기록입니다. 중심이 X=-0.50m에 멈추면 0.275m 앞에 있는 몸체 앞면이 상자의 X=-0.225m 면에 닿습니다.
처음이면 실습 파일부터 받기
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/로 시작하는 파일을 찾을 수 있습니다.
장면을 가져와 로봇을 움직여 봅니다
1. 머신을 확인하고 준비된 장면을 복사합니다
NVIDIA GPU가 있는 Linux 머신과 Isaac Sim 6.2 컨테이너 실행 환경이 필요합니다. nvidia-smi나 Docker GPU 설정이 낯설다면 NVIDIA Linux 환경 설정부터 확인하세요. 아래 명령은 저장소 최상위 폴더에서 입력합니다.
nvidia-smi
mkdir -p runs/worldgen-isaac
cp -R labs/worldgen-isaac/assets runs/worldgen-isaac/assets

준비된 USD 장면 받기(ZIP). Isaac Sim 6.2에서 combined/scene.usdc를 열고, 옆에 assets/ 폴더도 그대로 두세요.
동봉한 장면은 직접 생성한 WorldGen 실험실의 축소 결과입니다. 이 장면을 실행할 때는 FLUX 접근 승인이나 모델 가중치가 필요하지 않습니다. 직접 생성한 결과에서 다시 만들고 싶다면 별도의 WorldGen Python으로 변환합니다.
runs/worldgen-runtime/.venv/bin/python labs/worldgen-isaac/prepare.py \
--source runs/worldgen/robot-lab --output runs/worldgen-isaac/assets \
--camera-height 1.5 --stride 4
--camera-height는 크기를 정할 때 쓰는 가정입니다. 기준을 바꾸려면 값을 명확히 정하고 메시를 다시 만드세요. 이미지 확장 실습의 카메라 행렬로 이 방의 실제 크기를 복원하는 것은 아닙니다.
2. 주행 전에 바닥부터 확인합니다
NVIDIA Omniverse 약관에 동의했다면 터미널에서 ACCEPT_EULA=Y를 설정합니다. 본인이 약관에 동의했다는 뜻이며 스크립트가 명시적으로 요구합니다. 같은 터미널에서 결과를 저장할 폴더도 지정합니다.
export ACCEPT_EULA=Y
export WORLDGEN_DATA_ROOT="$PWD/runs/worldgen-isaac"
bash labs/worldgen-isaac/run.sh probes --headless
한 변이 10cm인 큐브 네 개의 중심이 Z=0.05m 근처에 멈추면 됩니다. runs/worldgen-isaac/probes/result.json에 실제 자세, 장면 단위, 아래쪽으로 쏜 광선의 충돌 결과가 기록됩니다. 나머지 설정도 서로 다른 출력 폴더로 실행해 비교하세요.
bash labs/worldgen-isaac/run.sh probes --headless --no-floor \
--output /work/no-floor
bash labs/worldgen-isaac/run.sh probes --headless --no-floor --raw-collider \
--output /work/raw-mesh
/work는 컨테이너 안에서 WORLDGEN_DATA_ROOT를 가리킵니다. Linux 루트에 직접 만들 폴더가 아닙니다. 충돌체가 없으면 큐브가 보이는 바닥을 통과합니다. 가져온 메시를 정적 충돌체로 쓰면 평평한 바닥 충돌체와 다른 높이에서 기울어져 멈춥니다. 평평한 바닥 충돌체는 이를 비교할 기준이 됩니다.
3. 직진과 우회 주행을 비교합니다
bash labs/worldgen-isaac/run.sh combined
# Separate comparison runs:
bash labs/worldgen-isaac/run.sh blocked
bash labs/worldgen-isaac/run.sh detour
대표 영상은 combined 실행입니다. 4초 동안 전진 명령을 주고 1.6초 후진한 뒤 경유점 주행으로 바꿉니다. 이 전환 시점은 미리 정했으며 학습한 검출기가 결정하지 않습니다. 실제 멈춤·접촉·회복 동작은 PhysX가 계산합니다. 전체 실행은 약 24.3초의 시뮬레이션 시간 후 목표에 도착했습니다.
각 명령은 실제 Isaac Sim GUI를 열어 실험 하나를 실행하고 결과를 저장한 뒤 종료합니다. blocked는 계속 전진 명령을 주지만 충돌 때문에 몸체가 X=-0.50m 부근에서 멈춥니다. detour는 자세 피드백으로 [-0.85,0] → [-0.85,-0.95] → [0.85,-0.95] → [1.3,0]을 따라갑니다. 마지막 목표의 허용 오차는 0.12m입니다. 같은 물리 환경에서 제어 방법을 바꾼 비교이며 AI 정책의 성능 비교는 아닙니다.
--collision-view를 붙이면 생성한 렌더용 메시를 숨기고 바닥·상자의 물리 형상을 볼 수 있습니다. 각 결과의 scene.usdc에는 실행 전 장면 구성이 저장되며 녹화한 궤적은 들어 있지 않습니다. 따로 연 Isaac Sim에서 File → Open으로 이 파일을 확인할 수 있습니다. 텍스처를 읽을 수 있도록 형제 폴더인 assets/도 함께 두세요. USD만 열고 Play를 누르면 설정된 물체의 물리 시뮬레이션이 실행됩니다. 경유점 제어기는 run.sh로 실행해야 작동합니다.
4. 실제 GUI 화면을 녹화합니다
X11 데스크톱과 x11grab을 지원하는 ffmpeg, xwininfo가 필요합니다.
mkdir -p runs/worldgen-recording
cp -R labs/worldgen-isaac/assets runs/worldgen-recording/assets
python3 labs/worldgen-isaac/record_gui.py \
--work "$PWD/runs/worldgen-recording" --scenario combined --ffmpeg /path/to/ffmpeg
새로 녹화할 때는 새 출력 폴더를 사용하세요. 도우미는 시뮬레이터 준비를 기다린 뒤 실제 창을 녹화하고 제어 루프를 시작합니다. native-gui.mp4, 창 정보 window.txt, 로그와 물리 궤적을 함께 남깁니다. 공개한 뷰포트 영상은 이 실제 GUI 화면을 잘라 만든 것입니다. 렌더링 속도에 따라 물리 시간보다 실제 재생 시간이 길어질 수 있으므로 두 시간을 구분해서 확인하세요.
6.2 예제는 SimulationManager.step()과 RenderingManager.render()로 물리 스텝과 화면 그리기를 분리합니다. GPU GUI 구성에는 공식 문서의 프레임별 렌더링 호환 플래그 --/rtx/hydra/supportMultiTickRate=false를 적용했습니다. 여러 주기의 카메라·LiDAR 촬영을 검증한 구성은 아닙니다. 처음 셰이더·뷰포트를 준비할 때 1~2분이 걸릴 수 있습니다. 실제 뷰포트 프레임이 저장된 뒤에 녹화를 시작합니다. NVIDIA multi-tick 설정
공간의 겉모습은 파노라마를 OmniPBR로 표시하고, 구워진 색이 잘 보이도록 발광 표시값을 조정했습니다. 실제 조명이나 반사율을 복원·보정한 재질은 아닙니다. 제어에 기록한 자세 형식은 [position_xyz, quaternion_xyzw]이며, 바퀴 속도 명령의 기준점은 몸체 좌표보다 0.10m 앞에 있는 차축 중앙입니다.
GPU 없이 결과를 검사합니다
python3 labs/worldgen-isaac/check.py
동봉한 크기 설정, 낙하 실험, 충돌 광선, 실제 장애물 접촉, 우회 주행의 도착 위치, 코드와 공개 영상의 해시를 확인합니다. 아래 영상에서 소스와 전체 실행 기록으로 이어갈 수 있습니다. 직접 실행한 새 결과는 다음처럼 검사합니다.
python3 labs/worldgen-isaac/check.py --run runs/worldgen-isaac/detour
장면을 가져왔다고 검증된 디지털 트윈이 완성되는 것은 아닙니다. 이 실습은 생성한 시각 환경에, 동작을 확인한 국소 물리 구성을 더하는 과정입니다. 크기는 가정했고, 표면은 추정값이며, 충돌체는 시험 구역에만 설정했습니다. 로봇은 단순한 상태 피드백으로 움직입니다. WorldGen 생성 실습 · Isaac Sim 원리 · 영상·입력 출처.
실행 영상과 기록
실습 소스 코드
prepare.py
GitHub에서 파일 보기"""Calibrate WorldGen's arbitrary scale and prepare a small textured USD mesh input.
CPU-only. The anchor is an explicit assumption, not recovered metric geometry.
"""
import argparse,hashlib,json
from pathlib import Path
import numpy as np
from PIL import Image
def prepare(source, output, camera_height=1.5, stride=4):
output.mkdir(parents=True,exist_ok=True)
depth=np.load(source/'distance.npy');h,w=depth.shape
rgb=Image.open(source/'panorama.png').convert('RGB')
assert rgb.size==(w,h) and np.isfinite(depth).all() and depth.min()>0
phi,theta=np.meshgrid((np.arange(w)+.5)/w*2*np.pi-np.pi,(np.arange(h)+.5)/h*np.pi-np.pi/2)
rays=np.stack([np.cos(theta)*np.sin(phi),np.sin(theta),np.cos(theta)*np.cos(phi)],-1)
points=rays*depth[...,None]
candidate=points[(theta>.8)&(theta<1.35)&(depth<3)][::8]
# Near-camera lower hemisphere supplies a repeatable, visible floor patch.
selected=np.ones(len(candidate),dtype=bool)
for _ in range(5):
q=candidate[selected]
A=np.column_stack([q[:,0],q[:,2],np.ones(len(q))])
a,b,c=np.linalg.lstsq(A,q[:,1],rcond=None)[0]
residual=candidate[:,1]-(a*candidate[:,0]+b*candidate[:,2]+c)
selected=np.abs(residual)<.025
up=np.array([a,-1.,b]);up/=np.linalg.norm(up)
d=c/np.linalg.norm([a,-1,b])
scale=camera_height/d
right=np.array([1.,0,0]);right-=up*right.dot(up);right/=np.linalg.norm(right)
forward=np.cross(up,right)
R=np.stack([right,forward,up])
origin=-d*up
world=(points-origin)@R.T*scale
ys=np.arange(0,h,stride);xs=np.arange(0,w,stride)
small=world[np.ix_(ys,xs)]
sy,sx=small.shape[:2]
# Preserve the panorama seam. Each UV is at the center of its source pixel.
yy,xx=np.meshgrid(ys,xs,indexing='ij')
uv=np.stack([(xx+.5)/w,1-(yy+.5)/h],-1)
ids=np.arange(sy*sx).reshape(sy,sx)
tl=ids[:-1,:-1];tr=ids[:-1,1:];bl=ids[1:,:-1];br=ids[1:,1:]
faces=np.concatenate([np.stack([tl,bl,tr],-1).reshape(-1,3),np.stack([tr,bl,br],-1).reshape(-1,3)])
# The unwrapped seam remains an explicit small gap instead of an incorrect UV bridge.
np.savez_compressed(output/'room-mesh.npz',points=small.reshape(-1,3).astype('f4'),indices=faces.astype('i4'),uv=uv.reshape(-1,2).astype('f4'))
rgb.save(output/'panorama.jpg',quality=94)
residual_m=((candidate-origin)@up*scale)[selected]
manifest={'source':'WorldGen robot-lab, seed 42; generated 2026-11-20',
'source_sha256':{n:hashlib.sha256((source/n).read_bytes()).hexdigest() for n in ['distance.npy','panorama.png']},
'metric_scale':'assumed camera-to-floor height; not a measured scale recovery',
'assumed_camera_height_m':camera_height,'meters_per_worldgen_unit':float(scale),
'source_floor_plane':{'normal':up.tolist(),'offset':float(d),'inliers':int(selected.sum()),'candidates':len(candidate),'threshold_source_units':.025},
'source_to_isaac':{'rotation_rows':R.tolist(),'source_origin':origin.tolist(),'formula':'p_isaac = scale * R @ (p_source - source_origin); Z up, metersPerUnit=1'},
'floor_inlier_rms_m':float(np.sqrt(np.mean(residual_m**2))),
'full_bounds_m':[world.reshape(-1,3).min(0).tolist(),world.reshape(-1,3).max(0).tolist()],
'render_mesh':{'stride':stride,'vertices':len(small.reshape(-1,3)),'triangles':len(faces),'collision_enabled':False,'small_uv_seam_gap':True},
'physics_proxy':{'floor_center':[0,0,-.05],'floor_size':[5,4,.1],
'obstacle_center':[0,0,.3],'obstacle_size':[.45,.8,.6],
'scope':'authored test floor and added crate only; not automatically inferred furniture collisions'},
'robot':{'type':'authored differential-drive AMR','body_size':[.55,.40,.18],'wheel_radius_m':.11,'wheel_base_m':.52,'mass_chassis_kg':8},
'route':{'start':[-1.3,0,.24],'goal':[1.3,0],'detour_waypoints':[[-.85,0],[-.85,-.95],[.85,-.95],[1.3,0]]}}
(output/'calibration.json').write_text(json.dumps(manifest,indent=2)+'\n')
print(json.dumps({'scale':scale,'floor_rms_m':manifest['floor_inlier_rms_m'],'mesh':manifest['render_mesh']}))
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--source',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
p.add_argument('--camera-height',type=float,default=1.5);p.add_argument('--stride',type=int,default=4)
a=p.parse_args();prepare(a.source,a.output,a.camera_height,a.stride)
run.sh
GitHub에서 파일 보기#!/usr/bin/env bash
# Start an isolated Isaac Sim 6.2 container. ACCEPT_EULA must be supplied by the user.
set -euo pipefail
: "${ACCEPT_EULA:?Set ACCEPT_EULA=Y only after accepting the NVIDIA Omniverse agreement.}"
[[ "$ACCEPT_EULA" == Y ]] || { echo "ACCEPT_EULA must be Y after your own acceptance." >&2; exit 1; }
worldgen_lab_root="$(cd "$(dirname "$0")" && pwd)"
worldgen_data_root="${WORLDGEN_DATA_ROOT:-$worldgen_lab_root}"
mkdir -p "$worldgen_data_root/cache"
worldgen_scenario="${1:-detour}"
shift || true
worldgen_xauth="${XAUTHORITY:-/run/user/$(id -u)/gdm/Xauthority}"
worldgen_display="${DISPLAY:-:1}"
worldgen_desktop_args=()
worldgen_headless=false
for worldgen_arg in "$@"; do
[[ "$worldgen_arg" == --headless ]] && worldgen_headless=true
done
if ! "$worldgen_headless"; then
[[ -f "$worldgen_xauth" ]] || { echo "Set XAUTHORITY to your X11 desktop authority file for GUI use." >&2; exit 1; }
worldgen_desktop_args=(-e "DISPLAY=$worldgen_display" -e XAUTHORITY=/tmp/isaac-xauthority
-v "$worldgen_xauth:/tmp/isaac-xauthority:ro" -v /tmp/.X11-unix:/tmp/.X11-unix:rw)
fi
exec docker run --rm --user 0:0 --gpus all --shm-size=2g \
-e ACCEPT_EULA="$ACCEPT_EULA" -e PRIVACY_CONSENT=N -e NVIDIA_DRIVER_CAPABILITIES=all \
"${worldgen_desktop_args[@]}" \
-v "$worldgen_data_root/cache:/root/.cache:rw" \
-v "$worldgen_lab_root:/lab:ro" -v "$worldgen_data_root:/work:rw" \
--entrypoint /isaac-sim/python.sh nvcr.io/nvidia/isaac-sim:6.2.0 \
/lab/run.py --assets /work/assets --output "/work/$worldgen_scenario" --scenario "$worldgen_scenario" \
--allow-root --/omni/client/omniverse/use_omnihub=false --/renderer/multiGpu/enabled=false --/rtx/hydra/supportMultiTickRate=false "$@"
run.py
GitHub에서 파일 보기"""Import the calibrated WorldGen visual mesh and simulate a real wheeled AMR.
Run inside Isaac Sim 6.2, outside the WorldGen Python environment.
The visual shell is not a collider. The test floor and crate are explicit proxies.
"""
import argparse,json,math,os,time,traceback
from pathlib import Path
from importlib.metadata import version, PackageNotFoundError
p=argparse.ArgumentParser()
p.add_argument('--assets',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
p.add_argument('--scenario',choices=['probes','blocked','detour','combined'],default='detour')
p.add_argument('--room-emission',type=float,default=400.);p.add_argument('--headless',action='store_true');p.add_argument('--collision-view',action='store_true')
p.add_argument('--raw-collider',action='store_true');p.add_argument('--no-floor',action='store_true');p.add_argument('--record-handshake',action='store_true')
a,kit_args=p.parse_known_args();a.assets=a.assets.resolve();a.output=a.output.resolve();a.output.mkdir(parents=True,exist_ok=True)
(a.output/'FAILED').unlink(missing_ok=True)
from isaacsim import SimulationApp
app=SimulationApp({'headless':a.headless,'width':1280,'height':720,'window_width':1440,'window_height':900,
'renderer':'RaytracedLighting','anti_aliasing':2,'fast_shutdown':True})
failed=True
try:
import numpy as np
import carb,omni.usd,omni.physx
from pxr import Gf,Sdf,UsdGeom,UsdShade,UsdLux,UsdPhysics,PhysxSchema,PhysicsSchemaTools
from isaacsim.core.simulation_manager import SimulationManager
import isaacsim.core.experimental.utils.stage as stage_utils
from isaacsim.core.rendering_manager import RenderingManager, ViewportManager
from omni.kit.viewport.utility import get_active_viewport
settings=carb.settings.get_settings()
settings.set_bool('/physics/updateToUsd',True)
settings.set_bool('/rtx/hydra/readTransformsFromFabricInRenderDelegate',False)
settings.set_bool('/persistent/app/viewport/Viewport/Viewport0/scene/cameras/visible',False)
stage_utils.create_new_stage()
class SimulationLoop:
@property
def current_time(self):return SimulationManager.get_simulation_time()
def initialize(self):
SimulationManager.setup_simulation(dt=1/60)
SimulationManager.initialize_physics()
RenderingManager.set_dt(1/60)
def step(self,render=True):
SimulationManager.step()
if render:RenderingManager.render()
simulation=SimulationLoop()
stage=omni.usd.get_context().get_stage();UsdGeom.SetStageUpAxis(stage,'Z');UsdGeom.SetStageMetersPerUnit(stage,1.)
root=UsdGeom.Xform.Define(stage,'/World');stage.SetDefaultPrim(root.GetPrim())
manifest=json.loads((a.assets/'calibration.json').read_text())
config=manifest['physics_proxy'];robot_cfg=manifest['robot']
def xform(path,pos):
obj=UsdGeom.Xform.Define(stage,path);obj.AddTranslateOp().Set(Gf.Vec3d(*pos));return obj
def material(name,rgb,emission=0):
mat=UsdShade.Material.Define(stage,'/World/Looks/'+name);shader=UsdShade.Shader.Define(stage,mat.GetPath().AppendChild('Surface'))
shader.CreateIdAttr('UsdPreviewSurface');shader.CreateInput('diffuseColor',Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*rgb))
shader.CreateInput('roughness',Sdf.ValueTypeNames.Float).Set(.65)
shader.CreateInput('emissiveColor',Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*(np.array(rgb)*emission)))
mat.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(),'surface');return mat
def bind(obj,mat):UsdShade.MaterialBindingAPI.Apply(obj.GetPrim()).Bind(mat)
green=material('RobotGreen',(.30,.65,.025),.15);dark=material('Rubber',(.045,.05,.055),.05)
steel=material('Steel',(.35,.39,.42));orange=material('TestCrate',(.96,.34,.025),.1);gray=material('ProxyFloor',(.33,.40,.42),.1)
blue=material('Probe',(.03,.35,.95),.2);white=material('Ruler',(.94,.94,.85),.3)
def physics_material(name,friction):
mat=UsdShade.Material.Define(stage,'/World/Looks/'+name);api=UsdPhysics.MaterialAPI.Apply(mat.GetPrim())
api.CreateStaticFrictionAttr(friction);api.CreateDynamicFrictionAttr(friction);api.CreateRestitutionAttr(0.)
return mat
traction=physics_material('Traction',.9);caster_mat=physics_material('Caster',.015)
def box(path,pos,size,mat,collision=False):
o=UsdGeom.Cube.Define(stage,path);o.CreateSizeAttr(1.);o.AddTranslateOp().Set(Gf.Vec3d(*pos));o.AddScaleOp().Set(Gf.Vec3d(*size));bind(o,mat)
if collision:UsdPhysics.CollisionAPI.Apply(o.GetPrim())
return o
def rigid(obj,mass):
UsdPhysics.RigidBodyAPI.Apply(obj.GetPrim());UsdPhysics.MassAPI.Apply(obj.GetPrim()).CreateMassAttr(mass)
# The render mesh is a decimation of the generated RGB-distance shell.
mesh_data=np.load(a.assets/'room-mesh.npz');mesh=UsdGeom.Mesh.Define(stage,'/World/GeneratedRoom')
mesh.CreatePointsAttr(mesh_data['points']);mesh.CreateFaceVertexCountsAttr([3]*len(mesh_data['indices']));mesh.CreateFaceVertexIndicesAttr(mesh_data['indices'].reshape(-1))
mesh.CreateSubdivisionSchemeAttr('none');mesh.CreateDoubleSidedAttr(True)
UsdGeom.PrimvarsAPI(mesh).CreatePrimvar('st',Sdf.ValueTypeNames.TexCoord2fArray,UsdGeom.Tokens.vertex).Set(mesh_data['uv'])
mesh.CreateExtentAttr([Gf.Vec3f(*mesh_data['points'].min(0).tolist()),Gf.Vec3f(*mesh_data['points'].max(0).tolist())])
# Native OmniPBR avoids the PreviewSurface texture-graph translation on RTX.
room_mat=UsdShade.Material.Define(stage,'/World/Looks/Room')
room_shader=UsdShade.Shader.Define(stage,'/World/Looks/Room/Shader')
room_shader.CreateIdAttr('OmniPBR')
room_shader.GetImplementationSourceAttr().Set(UsdShade.Tokens.sourceAsset)
room_shader.SetSourceAsset(Sdf.AssetPath('OmniPBR.mdl'),'mdl')
room_shader.SetSourceAssetSubIdentifier('OmniPBR','mdl')
out=room_shader.CreateOutput('out',Sdf.ValueTypeNames.Token)
room_mat.CreateSurfaceOutput('mdl').ConnectToSource(out)
for name in ['diffuse_texture','emissive_color_texture']:
room_shader.CreateInput(name,Sdf.ValueTypeNames.Asset).Set(Sdf.AssetPath(str(a.assets/'panorama.jpg')))
room_shader.CreateInput('project_uvw',Sdf.ValueTypeNames.Bool).Set(False)
room_shader.CreateInput('texture_scale',Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(1,1))
room_shader.CreateInput('diffuse_color_constant',Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(1))
room_shader.CreateInput('reflection_roughness_constant',Sdf.ValueTypeNames.Float).Set(1.)
room_shader.CreateInput('enable_emission',Sdf.ValueTypeNames.Bool).Set(True)
room_shader.CreateInput('emissive_color',Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(1))
room_shader.CreateInput('emissive_intensity',Sdf.ValueTypeNames.Float).Set(a.room_emission)
bind(mesh,room_mat)
if a.raw_collider:
UsdPhysics.CollisionAPI.Apply(mesh.GetPrim())
UsdPhysics.MeshCollisionAPI.Apply(mesh.GetPrim()).CreateApproximationAttr('none')
if a.collision_view:mesh.CreateVisibilityAttr('invisible')
if not a.no_floor:
floor=box('/World/ProxyFloor',config['floor_center'],config['floor_size'],gray,True)
UsdShade.MaterialBindingAPI.Apply(floor.GetPrim()).Bind(traction,materialPurpose='physics')
if not a.collision_view:floor.CreateVisibilityAttr('invisible')
crate=box('/World/TestCrate',config['obstacle_center'],config['obstacle_size'],orange,True)
# One metre, in the chosen simulation scale, rather than a claim about the generated simulation.
box('/World/OneMetreBar',(0,.95,.06),(1,.015,.01),white)
for x in np.linspace(-.5,.5,11):box(f'/World/Tick{int(round((x+.5)*10))}',(float(x),.95,.065),(.01,.06 if abs(x)>.49 else .035,.01),white)
paths=[];drives=[]
if a.scenario=='probes':
for i,(x,y) in enumerate([(-1,-.7),(-1,.7),(1,-.7),(1,.7)]):
obj=xform(f'/World/Probe{i}',(x,y,.75));rigid(obj,.1)
if not a.headless:PhysxSchema.PhysxRigidBodyAPI.Apply(obj.GetPrim()).CreateDisableGravityAttr(True)
box(str(obj.GetPath())+'/Geometry',(0,0,0),(.1,.1,.1),blue,True);paths.append(str(obj.GetPath()))
else:
robot=xform('/World/Robot',(0,0,0));UsdPhysics.ArticulationRootAPI.Apply(robot.GetPrim())
PhysxSchema.PhysxArticulationAPI.Apply(robot.GetPrim()).CreateEnabledSelfCollisionsAttr(False)
start=np.array(manifest['route']['start']);chassis=xform('/World/Robot/Chassis',start);rigid(chassis,8.)
PhysxSchema.PhysxContactReportAPI.Apply(chassis.GetPrim()).CreateThresholdAttr(0)
box('/World/Robot/Chassis/Body',(0,0,0),robot_cfg['body_size'],green,True)
box('/World/Robot/Chassis/Top',(0,0,.13),(.38,.30,.08),steel)
box('/World/Robot/Chassis/Front',(.28,0,.035),(.012,.22,.04),white)
caster=UsdGeom.Sphere.Define(stage,'/World/Robot/Chassis/Caster');caster.CreateRadiusAttr(.05);caster.AddTranslateOp().Set(Gf.Vec3d(-.21,0,-.18));bind(caster,dark)
UsdPhysics.CollisionAPI.Apply(caster.GetPrim());UsdShade.MaterialBindingAPI.Apply(caster.GetPrim()).Bind(caster_mat,materialPurpose='physics')
for i,y in enumerate([.26,-.26]):
path=f'/World/Robot/Wheel{i}';local=np.array([.10,y,-.12]);wheel=xform(path,start+local);rigid(wheel,.3)
cylinder=UsdGeom.Cylinder.Define(stage,path+'/Tyre');cylinder.CreateAxisAttr('Y');cylinder.CreateRadiusAttr(.11);cylinder.CreateHeightAttr(.06);bind(cylinder,dark)
UsdPhysics.CollisionAPI.Apply(cylinder.GetPrim());UsdShade.MaterialBindingAPI.Apply(cylinder.GetPrim()).Bind(traction,materialPurpose='physics')
for j in range(3):
spoke=box(path+f'/Spoke{j}',(0,(-.031 if y<0 else .031),0),(.16,.006,.015),white)
spoke.AddRotateYOp().Set(j*60.)
joint=UsdPhysics.RevoluteJoint.Define(stage,f'/World/Robot/Joint{i}');joint.CreateAxisAttr('Y')
joint.CreateBody0Rel().SetTargets([chassis.GetPath()]);joint.CreateBody1Rel().SetTargets([wheel.GetPath()])
joint.CreateLocalPos0Attr(Gf.Vec3f(*local));joint.CreateLocalPos1Attr(Gf.Vec3f(0))
drive=UsdPhysics.DriveAPI.Apply(joint.GetPrim(),'angular');drive.CreateTypeAttr('force');drive.CreateStiffnessAttr(0);drive.CreateDampingAttr(20);drive.CreateMaxForceAttr(6);drive.CreateTargetVelocityAttr(0)
drives.append(drive)
paths=['/World/Robot/Chassis']
# Save the source scene before stepping. The exported state can be inspected in the GUI.
def aim(camera,eye,target):
matrix=Gf.Matrix4d(1).SetLookAt(Gf.Vec3d(*eye),Gf.Vec3d(*target),Gf.Vec3d(0,0,1)).GetInverse()
UsdGeom.Xformable(camera).AddTransformOp().Set(matrix)
camera=UsdGeom.Camera.Define(stage,'/World/FilmCamera');camera.GetPrim().ApplyAPI('OmniSensorAPI');aim(camera,(0,-1.8,1.35),(0,.6,.45));camera.CreateFocalLengthAttr(11);camera.CreateHorizontalApertureAttr(36);camera.CreateClippingRangeAttr(Gf.Vec2f(.03,120))
dome=UsdLux.DomeLight.Define(stage,'/World/Dome');dome.CreateIntensityAttr(450)
key=UsdLux.SphereLight.Define(stage,'/World/Light');key.AddTranslateOp().Set(Gf.Vec3d(-.3,-.5,2.1));key.CreateIntensityAttr(1800);key.CreateRadiusAttr(.7)
stage.Export(str(a.output/'scene.usdc'))
portable=Sdf.Layer.FindOrOpen(str(a.output/'scene.usdc'))
for name in ['diffuse_texture','emissive_color_texture']:
portable.GetAttributeAtPath('/World/Looks/Room/Shader.inputs:'+name).default=Sdf.AssetPath(os.path.relpath(a.assets/'panorama.jpg',a.output))
portable.Save()
simulation.initialize()
if not a.headless:
viewport=get_active_viewport();ViewportManager.set_camera(camera)
import asyncio
from omni.kit.viewport.utility import capture_viewport_to_file
from PIL import Image
for _ in range(8):
simulation.step()
capture=capture_viewport_to_file(viewport,str(a.output/'initial-rgb.png'))
async def wait_for_frame():
return await asyncio.wait_for(capture.wait_for_result(),timeout=120)
app.run_coroutine(wait_for_frame())
image_deadline=time.monotonic()+10
while True:
try:
with Image.open(a.output/'initial-rgb.png') as frame:
pixels=np.array(frame)
break
except (FileNotFoundError,OSError):
if time.monotonic()>image_deadline:raise
RenderingManager.render();time.sleep(.02)
(a.output/'initial-rgb.png').chmod(0o644)
assert pixels.ndim==3 and pixels[:,:,:3].mean()>5,'Native viewport remained black'
print('RENDER_CHECK',pixels.shape,float(pixels[:,:,:3].mean()),flush=True)
if a.scenario=='probes':
for _ in range(40):RenderingManager.render()
else:
for _ in range(40):simulation.step(render=True)
inspector=omni.physx.get_physx_interface()
def pose(path):
v=inspector.get_rigidbody_transformation(path);assert v['ret_val'],path
return list(v['position']),list(v['rotation'])
raycasts={}
for name,xy in [('floor_left',[-1,-1]),('floor_right',[1,-1]),('crate',[0,0])]:
hit=omni.physx.get_physx_scene_query_interface().raycast_closest((xy[0],xy[1],2.),(0.,0.,-1.),5.)
raycasts[name]={'hit':bool(hit['hit']),'collider':str(hit.get('collision','')),'position':list(hit.get('position',[]))}
contacts=[]
def on_contact(headers,data):
for header in headers:
actor0=str(PhysicsSchemaTools.intToSdfPath(header.actor0));actor1=str(PhysicsSchemaTools.intToSdfPath(header.actor1))
if 'TestCrate' in actor0+actor1 and 'Chassis' in actor0+actor1:
contacts.append({'actor0':actor0,'actor1':actor1,'type':int(header.type),'time':simulation.current_time})
subscription=omni.physx.get_physx_simulation_interface().subscribe_contact_report_events(on_contact)
if a.record_handshake:
(a.output/'ready.json').write_text(json.dumps({'camera':str(camera.GetPath()),'application':'Isaac Sim 6.2 native window'}))
deadline=time.monotonic()+60
while not (a.output/'record-go').exists():
if time.monotonic()>deadline:raise TimeoutError('Native recorder did not start')
RenderingManager.render()
if a.scenario!='probes':
for _ in range(45):simulation.step(render=True)
print('NATIVE_GUI_RECORDING_STARTED',flush=True)
if a.scenario=='probes' and not a.headless:
for path in paths:PhysxSchema.PhysxRigidBodyAPI.Get(stage,path).GetDisableGravityAttr().Set(False)
samples=[];waypoints=manifest['route']['detour_waypoints'];waypoint=0
steps={'probes':180,'blocked':600,'detour':1800,'combined':2400}[a.scenario]
start_wall=time.monotonic();start_sim=simulation.current_time;reached=False
for step in range(steps):
v=omega=0.
if drives:
position,rotation=pose(paths[0]);x,y,z=position;qx,qy,qz,qw=rotation
yaw=math.atan2(2*(qw*qz+qx*qy),1-2*(qy*qy+qz*qz))
elapsed=simulation.current_time-start_sim
if a.scenario=='blocked' or (a.scenario=='combined' and elapsed<4):v=.32
elif a.scenario=='combined' and elapsed<5.6:v=-.25
else:
target=np.array(waypoints[waypoint]);distance=float(np.linalg.norm(target-np.array([x,y])))
if distance<.12:
if waypoint<len(waypoints)-1:waypoint+=1
else:reached=True
if not reached:
target=np.array(waypoints[waypoint]);delta=target-np.array([x,y]);error=math.atan2(math.sin(math.atan2(delta[1],delta[0])-yaw),math.cos(math.atan2(delta[1],delta[0])-yaw))
omega=float(np.clip(2.8*error,-1.1,1.1));v=min(.32,.9*distance)*max(0.,math.cos(error)) if abs(error)<.65 else 0.
wheel_speeds=[(v-.26*omega)/.11,(v+.26*omega)/.11]
for drive,speed in zip(drives,wheel_speeds):drive.GetTargetVelocityAttr().Set(math.degrees(speed))
simulation.step(render=True)
if step%60==0:print('SIM_STEP',step,simulation.current_time,flush=True)
if step%6==0:
sample={'step':step,'sim_time_s':simulation.current_time-start_sim,'wall_s':time.monotonic()-start_wall,'poses':{path:pose(path) for path in paths},'command':[v,omega],'waypoint':waypoint,'phase':('contact' if elapsed<4 else 'reverse' if elapsed<5.6 else 'detour') if a.scenario=='combined' else a.scenario}
samples.append(sample)
if reached and step>60:
if samples[-1].get('goal_hold') is None:samples[-1]['goal_hold']=True
if sum(s.get('goal_hold',False) for s in samples)>15:break
# Preserve real simulation time in the window recording whenever the renderer keeps up.
if not a.headless:time.sleep(max(0,(step+1)/60-(time.monotonic()-start_wall)))
for drive in drives:drive.GetTargetVelocityAttr().Set(0)
try: sim_version=version('isaacsim')
except PackageNotFoundError:
from isaacsim.core.version import get_version
sim_version=get_version()[0]
result={'status':'complete','scenario':a.scenario,'collision_view':a.collision_view,'no_floor':a.no_floor,'raw_collider':a.raw_collider,
'isaacsim_version':sim_version,'physics':'live PhysX; joint velocity drives; not a USD trajectory replay',
'control':'pose-feedback waypoint controller with initial contact and recovery' if a.scenario=='combined' else 'pose-feedback waypoint controller' if a.scenario=='detour' else 'fixed wheel commands' if drives else 'gravity probes',
'start_sim_s':start_sim,'duration_sim_s':simulation.current_time-start_sim,'duration_wall_s':time.monotonic()-start_wall,'reached_goal':reached,
'stage':{'up_axis':str(UsdGeom.GetStageUpAxis(stage)),'meters_per_unit':UsdGeom.GetStageMetersPerUnit(stage),'render_mesh_collision':mesh.GetPrim().HasAPI(UsdPhysics.CollisionAPI),'multitick_rendering':settings.get_as_bool('/rtx/hydra/supportMultiTickRate'),'room_emission_display_setting':a.room_emission,'proxy_floor':not a.no_floor},'raycasts':raycasts,'crate_contact_events':contacts,'samples':samples,'final_poses':{path:pose(path) for path in paths}}
(a.output/'result.json').write_text(json.dumps(result,indent=2)+'\n')
print('RUN_RESULT',json.dumps({k:v for k,v in result.items() if k not in ['samples','crate_contact_events']}),flush=True)
failed=False
except BaseException:
traceback.print_exc()
finally:
if failed:(a.output/'FAILED').touch()
app.close()
if failed:raise SystemExit(1)
record_gui.py
GitHub에서 파일 보기"""Record the real native Isaac Sim window while run.py performs live physics."""
import argparse,json,os,signal,subprocess,time
from pathlib import Path
p=argparse.ArgumentParser();p.add_argument('--work',type=Path,required=True)
p.add_argument('--scenario',choices=['blocked','detour','probes','combined'],default='detour')
p.add_argument('--ffmpeg',type=Path,required=True);p.add_argument('--collision-view',action='store_true')
a=p.parse_args();root=Path(__file__).resolve().parent;a.work=a.work.resolve()
output=a.work/a.scenario;output.mkdir(parents=True,exist_ok=True)
assert not (output/'ready.json').exists(),'Use a new output folder for a fresh recording'
env=dict(os.environ,WORLDGEN_DATA_ROOT=str(a.work),DISPLAY=os.environ.get('DISPLAY',':1'),XAUTHORITY=os.environ.get('XAUTHORITY',f'/run/user/{os.getuid()}/gdm/Xauthority'))
command=['bash',str(root/'run.sh'),a.scenario,'--record-handshake']+(['--collision-view'] if a.collision_view else [])
recorder=None
with (output/'simulator.log').open('w') as log:
process=subprocess.Popen(command,env=env,stdout=log,stderr=subprocess.STDOUT)
try:
deadline=time.monotonic()+240
while not (output/'ready.json').exists():
if process.poll() is not None:raise RuntimeError('Isaac Sim stopped before the viewport was ready; see simulator.log')
if time.monotonic()>deadline:raise TimeoutError('Isaac Sim startup timed out')
time.sleep(.3)
listing=subprocess.check_output(['xwininfo','-root','-tree'],env=env,text=True)
window=next(row.split()[0] for row in listing.splitlines() if ('"Isaac Sim' in row or '"Isaac-Sim' in row) and 'mutter-x11-frames' not in row)
metadata=subprocess.check_output(['xwininfo','-id',window],env=env,text=True)
(output/'window.txt').write_text(metadata)
with (output/'recorder.log').open('w') as recordlog:
recorder=subprocess.Popen([str(a.ffmpeg),'-nostdin','-hide_banner','-loglevel','warning','-y','-f','x11grab','-draw_mouse','0','-framerate','30','-window_id',str(int(window,16)),'-i',env['DISPLAY']+'.0','-an','-vf','scale=trunc(iw/2)*2:trunc(ih/2)*2','-c:v','libx264','-preset','ultrafast','-crf','18','-pix_fmt','yuv420p','-movflags','+faststart',str(output/'native-gui.mp4')],env=env,stdout=recordlog,stderr=subprocess.STDOUT)
time.sleep(.5);assert recorder.poll() is None,'X11 recorder could not start'
(output/'record-go').touch()
process.wait(timeout=300)
if (output/'FAILED').exists() or not (output/'result.json').exists():raise RuntimeError('Simulation failed; keep the logs for diagnosis')
finally:
if recorder and recorder.poll() is None:
recorder.send_signal(signal.SIGINT);recorder.wait(timeout=15)
if process.poll() is None:process.terminate()
print('Native GUI recording:',output/'native-gui.mp4')
package.py
GitHub에서 파일 보기"""Crop actual X11 window recordings into lightweight viewport clips.
No offline renderer or animation is substituted for the native GUI footage.
"""
import argparse,hashlib,json,subprocess,shutil,re
from pathlib import Path
p=argparse.ArgumentParser();p.add_argument('--source',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
p.add_argument('--ffmpeg',default='ffmpeg');p.add_argument('--ffprobe',default='ffprobe');a=p.parse_args();a.output.mkdir(parents=True,exist_ok=True)
# Fixed geometry from our 1440×900 native Kit window; inspect window.txt on other layouts.
for scenario,stem in [('combined','worldgen-isaac'),('blocked','worldgen-isaac-blocked'),('detour','worldgen-isaac-detour'),('probes','worldgen-isaac-probes')]:
folder=a.source/scenario
if not (folder/'native-gui.mp4').exists():continue
window=(folder/'window.txt').read_text()
assert 'Width: 1440' in window and 'Height: 900' in window,'Reinspect the viewport crop for another layout'
result=json.loads((folder/'result.json').read_text());duration=result['duration_wall_s']+(.75 if scenario!='probes' else 0)+.2
output=a.output/f'{stem}.mp4'
subprocess.run([a.ffmpeg,'-hide_banner','-loglevel','error','-y','-ss','0.4','-i',str(folder/'native-gui.mp4'),'-t',str(duration),'-an',
'-vf','crop=952:536:50:64,scale=960:540','-c:v','libx264','-preset','slow','-crf','23','-pix_fmt','yuv420p','-movflags','+faststart',str(output)],check=True)
subprocess.run([a.ffmpeg,'-hide_banner','-loglevel','error','-y','-ss','1.4' if scenario=='probes' else '3','-i',str(output),'-frames:v','1',str(a.output/f'{stem}.jpg')],check=True)
if shutil.which(a.ffprobe):
probe=json.loads(subprocess.check_output([a.ffprobe,'-v','error','-show_format','-of','json',str(output)]))
duration_s=float(probe['format']['duration'])
else:
info=subprocess.run([a.ffmpeg,'-hide_banner','-i',str(output)],capture_output=True,text=True).stderr
hh,mm,ss=re.search(r'Duration: (\d+):(\d+):([\d.]+)',info).groups()
duration_s=int(hh)*3600+int(mm)*60+float(ss)
metadata={'source':'native X11 Isaac Sim window, 1440x900','crop_xywh':[50,64,952,536],'trim_start_s':.4,'speed':1.,'published_resolution':[960,540],
'duration_s':duration_s,'bytes':output.stat().st_size,'sha256':hashlib.sha256(output.read_bytes()).hexdigest(),
'source_sha256':hashlib.sha256((folder/'native-gui.mp4').read_bytes()).hexdigest(),'physical_simulation_s':result['duration_sim_s']}
(a.output/f'{stem}.edit.json').write_text(json.dumps(metadata,indent=2)+'\n');print(stem,metadata['duration_s'],metadata['bytes'])
plot.py
GitHub에서 파일 보기"""Plot measured chassis paths, not the requested waypoint polyline (CPU)."""
import argparse,json
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.font_manager import FontProperties
p=argparse.ArgumentParser();p.add_argument('--evidence',type=Path,required=True);p.add_argument('--output',type=Path,required=True);p.add_argument('--font',type=Path);a=p.parse_args();a.output.mkdir(parents=True,exist_ok=True)
if a.font:plt.rcParams['font.family']=FontProperties(fname=str(a.font)).get_name()
plt.rcParams.update({'svg.fonttype':'path','axes.unicode_minus':False,'font.size':11})
runs={name:json.loads((a.evidence/name/'result.json').read_text()) for name in ['combined','blocked']}
for lang in ['en','ko']:
fig,ax=plt.subplots(figsize=(9,5),layout='constrained');fig.patch.set_facecolor('#f6f8fa');ax.set_facecolor('white')
ax.add_patch(Rectangle((-.225,-.4),.45,.8,facecolor='#f4a340',edgecolor='#9d5c05',label='Test crate' if lang=='en' else '시험 상자'))
for name,color,label in [('combined','#659f00','Contact, reverse, detour' if lang=='en' else '접촉·후진 후 우회'),('blocked','#ce5a46','Straight drive' if lang=='en' else '직진')]:
xy=[s['poses']['/World/Robot/Chassis'][0][:2] for s in runs[name]['samples']]
ax.plot([q[0] for q in xy],[q[1] for q in xy],color=color,lw=2.5,label=label,zorder=4 if name=='blocked' else 3,linestyle='--' if name=='blocked' else '-')
ax.scatter([-1.3,1.3],[0,0],s=75,marker='o',color=['#416a94','#659f00'],zorder=4)
ax.annotate('Start' if lang=='en' else '출발',(-1.3,0),xytext=(-16,14),textcoords='offset points')
ax.annotate('Goal' if lang=='en' else '목표',(1.3,0),xytext=(-10,14),textcoords='offset points')
ax.set(xlim=(-1.8,1.8),ylim=(-1.4,.8),xlabel='X (chosen simulation metres)' if lang=='en' else 'X (정한 시뮬레이션 크기, m)',ylabel='Y (m)',title='Measured chassis motion · live PhysX' if lang=='en' else '실제 몸체 이동 기록 · PhysX 실행')
ax.set_aspect('equal');ax.grid(alpha=.18);ax.legend(loc='upper center',ncol=3,fontsize=10)
for spine in ax.spines.values():spine.set_edgecolor('#c8d0d7')
fig.savefig(a.output/f'paths.{lang}.svg');plt.close(fig)
check.py
GitHub에서 파일 보기"""Validate saved calibration, physical outcomes and media without CUDA or NumPy."""
import argparse,hashlib,json,math
from pathlib import Path
def check_run(folder):
r=json.loads((folder/'result.json').read_text())
assert r['status']=='complete' and r['isaacsim_version'].startswith('6.2')
assert r['stage']['up_axis']=='Z' and r['stage']['meters_per_unit']==1
assert r['samples'] and all(math.isfinite(v) for s in r['samples'] for pose in s['poses'].values() for values in pose for v in values)
if r['scenario']=='probes':
heights=[p[0][2] for p in r['final_poses'].values()]
if r['no_floor'] and not r['raw_collider']:assert max(heights)<-1
elif r['raw_collider']:assert all(.0<z<.20 for z in heights)
else:assert all(abs(z-.05)<.002 for z in heights)
else:
path='/World/Robot/Chassis';position=r['final_poses'][path][0]
assert all(.20<s['poses'][path][0][2]<.28 for s in r['samples'])
assert r['stage']['render_mesh_collision'] is False and r['stage']['proxy_floor'] is True
assert r['raycasts']['floor_left']['collider']=='/World/ProxyFloor'
assert abs(r['raycasts']['crate']['position'][2]-.6)<1e-4
if r['scenario']=='blocked':
assert abs(position[0]+.5)<.025 and r['crate_contact_events']
assert position[0]-r['samples'][0]['poses'][path][0][0]>.6
else:
assert r['reached_goal'] and math.hypot(position[0]-1.3,position[1])<.12
assert min(s['poses'][path][0][1] for s in r['samples'])<-.8
if r['scenario']=='detour':assert not r['crate_contact_events'],'The detour touched the crate'
else:
assert r['crate_contact_events']
assert {'contact','reverse','detour'}=={sample['phase'] for sample in r['samples']}
print(folder.name,r['scenario'],'physical outcome verified')
return r
def main():
p=argparse.ArgumentParser();p.add_argument('--run',type=Path);a=p.parse_args()
if a.run:check_run(a.run);return
folder=Path(__file__).resolve().parent;root=folder.parents[1]
record=json.loads((folder/'recorded.json').read_text())
calibration=json.loads((folder/'assets/calibration.json').read_text())
assert calibration['metric_scale'].startswith('assumed')
assert abs(calibration['meters_per_worldgen_unit']*calibration['source_floor_plane']['offset']-1.5)<1e-6
rows=calibration['source_to_isaac']['rotation_rows']
for i in range(3):
for j in range(3):assert abs(sum(a*b for a,b in zip(rows[i],rows[j]))-int(i==j))<1e-6
assert calibration['floor_inlier_rms_m']<.025
assert calibration['render_mesh']=={'stride':4,'vertices':80000,'triangles':158802,'collision_enabled':False,'small_uv_seam_gap':True}
for case in record['runs']:check_run(folder/'evidence'/case)
for rel,meta in record['files'].items():
data=(root/rel).read_bytes();assert len(data)==meta['bytes'] and hashlib.sha256(data).hexdigest()==meta['sha256'],rel
print('Calibrated assets, contact tests, live robot runs and native-GUI media hashes verified.')
if __name__=='__main__':main()



