File size: 9,288 Bytes
671e154 d0d030b 671e154 d0d030b 671e154 d0d030b 671e154 d0d030b 671e154 d0d030b 671e154 d0d030b 671e154 d0d030b 671e154 d0d030b 671e154 d0d030b 671e154 d0d030b 671e154 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | import os, sys, math
import json, time
import numpy as np
import argparse
from isaacgym import gymtorch, gymapi
import torch
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
CSV_FRAME_RATE = 50.0
CSV_TOTAL_COLS = 36
CSV_ROOT_POS_SLICE = slice(0, 3)
CSV_ROOT_QUAT_SLICE = slice(3, 7)
CSV_DOF_SLICE = slice(7, 36)
def get_label_indices(labels, prefix):
return [i for i, label in enumerate(labels) if label.startswith(prefix)]
def load_motion_data_json(json_path):
with open(json_path, 'r') as f:
motion = json.load(f)
labels = motion.get('Labels', [])
frames = np.array(motion['Frames'], dtype=np.float32)
# 提取 DOF、root_pos、root_quat 的列索引
dof_indices = get_label_indices(labels, "dof_pos/")
root_pos_indices = get_label_indices(labels, "root_pos/")
root_quat_indices = get_label_indices(labels, "root_quat/")
print(f"Found {len(dof_indices)} DOF channels:")
for idx in dof_indices:
print(f" {labels[idx]}")
print(f"root_pos indices: {[labels[i] for i in root_pos_indices]}")
print(f"root_quat indices: {[labels[i] for i in root_quat_indices]}")
return (
frames[:, dof_indices],
frames[:, root_pos_indices],
frames[:, root_quat_indices],
motion['FrameDuration']
)
def load_motion_data_csv(csv_path):
frames = np.loadtxt(csv_path, delimiter=',', dtype=np.float32)
if frames.ndim == 1:
frames = frames[None, :]
if frames.shape[1] < CSV_TOTAL_COLS:
raise ValueError(
f"CSV requires at least {CSV_TOTAL_COLS} columns, got {frames.shape[1]}: {csv_path}"
)
if frames.shape[1] > CSV_TOTAL_COLS:
print(
f"CSV has {frames.shape[1]} columns, using first {CSV_TOTAL_COLS} columns: {csv_path}"
)
frames = frames[:, :CSV_TOTAL_COLS]
print(f"Loaded CSV motion: {csv_path}")
print(f"root_pos columns: {CSV_ROOT_POS_SLICE.start + 1}~{CSV_ROOT_POS_SLICE.stop}")
print(f"root_quat columns: {CSV_ROOT_QUAT_SLICE.start + 1}~{CSV_ROOT_QUAT_SLICE.stop}")
print(f"dof columns: {CSV_DOF_SLICE.start + 1}~{CSV_DOF_SLICE.stop}")
return (
frames[:, CSV_DOF_SLICE],
frames[:, CSV_ROOT_POS_SLICE],
frames[:, CSV_ROOT_QUAT_SLICE],
1.0 / CSV_FRAME_RATE
)
def load_motion_data(motion_path):
ext = os.path.splitext(motion_path)[1].lower()
if ext == ".json":
return load_motion_data_json(motion_path)
if ext == ".csv":
return load_motion_data_csv(motion_path)
raise ValueError(f"Unsupported motion file format: {motion_path}")
def set_base_pose(gym, sim, env, actor, root_pos, root_quat):
"""
设置机器人 base link 的位置和旋转
:param root_pos: [x, y, z]
:param root_quat: [x, y, z, w]
"""
root_state_tensor = gym.acquire_actor_root_state_tensor(sim)
root_state = gymtorch.wrap_tensor(root_state_tensor)
# 获取 actor 在 tensor 中的索引(通常为 0,如果你只加载了一个 actor)
actor_index = 0
# 更新 base 位置和四元数
root_state[actor_index, :3] = torch.tensor(root_pos, dtype=torch.float32)
root_state[actor_index, 3:7] = torch.tensor(root_quat, dtype=torch.float32)
# 写回物理引擎
gym.set_actor_root_state_tensor(sim, root_state_tensor)
def set_dof_positions(gym, env, actor, target_pos):
dof_states = np.zeros(len(target_pos), dtype=gymapi.DofState.dtype)
dof_states['pos'] = target_pos
dof_states['vel'] = np.zeros_like(target_pos)
gym.set_actor_dof_states(env, actor, dof_states, gymapi.STATE_POS + gymapi.STATE_VEL)
def parse_args():
parser = argparse.ArgumentParser(description="Isaac Gym Preview 4 Motion Visualizer")
parser.add_argument('--file_name', type=str,
default="mixamo/low_jump.json",
help='Motion file name (.json or .csv). Default: "mixamo/low_jump.json"')
parser.add_argument('--robot_type', type=str,
choices=['adam_lite', 'adam_sp'],
default='adam_lite',
help='Robot type to load. Default: "adam_lite"')
return parser.parse_args()
def resolve_existing_path(candidates):
for rel_path in candidates:
abs_path = os.path.join(CURRENT_DIR, rel_path)
if os.path.exists(abs_path):
return rel_path
raise FileNotFoundError(f"No valid path found in candidates: {candidates}")
def get_robot_paths(robot_type):
if robot_type == "adam_lite":
urdf_path = resolve_existing_path([
"robot_description/adam_lite/urdf/adam_lite.urdf",
"robot_description/adam_lite/adam_lite.urdf",
])
motion_dir = "adam_lite"
elif robot_type == "adam_sp":
urdf_path = resolve_existing_path([
"robot_description/adam_sp/urdf/adam_sp.urdf",
"robot_description/adam_sp/adam_sp.urdf",
])
motion_dir = "adam_sp"
else:
raise ValueError(f"Unknown robot_type: {robot_type}")
return urdf_path, motion_dir
def main():
args = parse_args()
# 加载机器人资产
asset_path, motion_dir = get_robot_paths(args.robot_type)
asset_root = os.path.dirname(asset_path)
asset_file = os.path.basename(asset_path)
# 加载动作数据
motion_path = os.path.join(CURRENT_DIR, motion_dir, args.file_name)
frames_dof, frames_root_pos, frames_root_quat, frame_duration = load_motion_data(motion_path)
num_frames = len(frames_dof)
current_frame = 0
# 初始化 gym
gym = gymapi.acquire_gym()
# 设置仿真参数
sim_params = gymapi.SimParams()
sim_params.dt = frame_duration # 模拟频率
sim_params.substeps = 2
sim_params.up_axis = gymapi.UP_AXIS_Z
sim_params.gravity = gymapi.Vec3(0.0, 0.0, 0.0) # 关闭重力
sim_params.use_gpu_pipeline = False # 禁用 GPU pipeline(更简单)
sim = gym.create_sim(0, 0, gymapi.SIM_PHYSX, sim_params)
if sim is None:
raise Exception("Failed to create sim")
# 加载地面
plane_params = gymapi.PlaneParams()
plane_params.normal = gymapi.Vec3(0, 0, 1)
gym.add_ground(sim, plane_params)
asset_options = gymapi.AssetOptions()
asset_options.fix_base_link = False
asset_options.disable_gravity = True
asset_options.collapse_fixed_joints = True
robot_asset = gym.load_asset(sim, asset_root, asset_file, asset_options)
# 获取 DOF 数量
num_dof = gym.get_asset_dof_count(robot_asset)
if frames_dof.shape[1] != num_dof:
print(
f"DOF count mismatch: motion has {frames_dof.shape[1]}, "
f"asset requires {num_dof}. Auto-aligning."
)
if frames_dof.shape[1] > num_dof:
frames_dof = frames_dof[:, :num_dof]
else:
pad = np.zeros((frames_dof.shape[0], num_dof - frames_dof.shape[1]), dtype=np.float32)
frames_dof = np.concatenate([frames_dof, pad], axis=1)
# 创建环境
spacing = 1.0
lower = gymapi.Vec3(-spacing, -spacing, 0.0)
upper = gymapi.Vec3(spacing, spacing, spacing)
env = gym.create_env(sim, lower, upper, 8)
# 创建机器人 actor
pose = gymapi.Transform()
pose.p = gymapi.Vec3(0.0, 0.0, 1.0)
pose.r = gymapi.Quat(0.0, 0.0, 0.0, 1.0)
actor = gym.create_actor(env, robot_asset, pose, "actor", 0, 0)
cam_props = gymapi.CameraProperties()
viewer = gym.create_viewer(sim, cam_props)
if viewer is None:
raise Exception("Failed to create viewer")
# 设置相机参数
CAMERA_DISTANCE = -3.0 # 距离 base 的距离
CAMERA_HEIGHT = 1.0 # 高度
CAMERA_ANGLE = math.radians(90) # 视角角度(弧度)
while not gym.query_viewer_has_closed(viewer):
if current_frame < num_frames:
target_dof = frames_dof[current_frame]
target_root_pos = frames_root_pos[current_frame]
target_root_quat = frames_root_quat[current_frame]
# 设置 Base 位姿
set_base_pose(gym, sim, env, actor, target_root_pos, target_root_quat)
# 设置关节角度
set_dof_positions(gym, env, actor, target_dof)
current_frame += 1
else:
print("Animation finished.")
break
# Step simulation and render
gym.simulate(sim)
gym.fetch_results(sim, True)
gym.step_graphics(sim)
# 获取机器人 base 位置
root_state_tensor = gym.acquire_actor_root_state_tensor(sim)
root_state = gymtorch.wrap_tensor(root_state_tensor)
root_pos = root_state[0, :3].cpu().numpy()
# 使用球面坐标系计算相机位置
cam_x = root_pos[0] + CAMERA_DISTANCE * math.cos(CAMERA_ANGLE)
cam_y = root_pos[1] + CAMERA_DISTANCE * math.sin(CAMERA_ANGLE)
cam_z = root_pos[2] + CAMERA_HEIGHT
cam_pos = gymapi.Vec3(cam_x, cam_y, cam_z)
cam_target = gymapi.Vec3(root_pos[0], root_pos[1], root_pos[2])
# 更新相机视角
gym.viewer_camera_look_at(viewer, None, cam_pos, cam_target)
gym.draw_viewer(viewer, sim, True)
gym.sync_frame_time(sim)
time.sleep(0.001)
if __name__ == "__main__":
main()
|