Articulations¶
MJCF, URDF, and USD loaders produce a common ArticulationDesc.
Load a robot, then pass its data to world.add_articulation().
To create a robot without an asset file, use ArticulationBuilder.
Load a robot¶
Choose the loader for your file:
# world is an existing KangSimWorld.
data: ke.asset.ArticulationDesc = world.load_mjcf("robot.xml", order="DFS")
# Or:
data = world.load_urdf("robot.urdf", order="DFS")
data = world.load_usd("robot.usd", order="DFS")
USD requires a native build with USE_USD enabled. It selects the default
prim; pass prim_path="/Robot" to select a different robot subtree.
For material support and limitations, see
USD scenes.
Format |
Supported joints |
3-axis rotation |
|---|---|---|
MJCF |
Fixed, Revolute (hinge), Spherical (ball) |
Spherical or 3 orthogonal Revolute joints on one body |
URDF |
Fixed, Revolute, Prismatic |
3 Revolute joints with intermediate links |
USD |
Fixed, Revolute, Prismatic |
3 Revolute joints with intermediate links |
MJCF ball imports as a spherical joint with three free rotational DOFs;
rotation-angle limits are not supported. MJCF slide and USD Spherical
joint import are not supported.
Create the articulation¶
config = ke.physics.ArticulationConfig.free_base()
record = world.add_articulation(
data,
env_id=0,
obj_id=0,
name="robot",
config=config,
)
robot = record.articulation
For all three formats, choose ArticulationConfig.free_base() for a floating
root or ArticulationConfig.fixed_base() for a fixed root.
For a floating root, record.set_root_velocity(env_ids, linear_velocity, angular_velocity) changes world velocities without resetting pose, DOFs, or
control commands. The same API is available on articulation batches. See
Change velocity without resetting
for CPU/CUDA inputs and application order.
The following visualization example uses an MJCF asset:
Use the same order for loading and visualization.
robot_visual = visual.add_articulation_scene_graph(
0,
0,
mjcf_path,
path="/robot",
order="DFS",
material=robot_material,
)
Read and set rotations¶
Physics and simulation quaternion arrays use XYZW and world coordinates:
API |
Shape |
|---|---|
|
|
|
Flat |
|
|
|
|
State objects expose the same values as root_quat_xyzw and body_quat_xyzw.
Read after a completed step and refresh, as for the other state fields.
set_root_state(..., quat_xyzw=...) takes XYZW as well. The low-level
robot.reset_root(pos=..., quat_xyzw=...) accepts XYZW arrays or a ke.Quat
object; its default quaternion is the identity (0, 0, 0, 1).
Animation and scene quaternion arrays use WXYZ; see
Quaternion ordering
for conversion. Packed root/link buffers retain their names and
13-column layout.
MimicKit adapter methods such as get_root_rot() keep MimicKit’s interface names
and XYZW convention.
Attachment frames¶
Use frames for end-effectors, sensors, or tool mounts that need a named pose without a separate physical body.
A frame is a named attachment point with a position and orientation fixed relative to a body. MJCF sites are imported as fixed frames. Empty non-root fixed links with no inertial, visual, or collision data are also imported as frames instead of physical bodies. The original skeleton remains available for animation and retargeting.
Find and read¶
Read after a completed simulation step. On CPU, call world.state.refresh()
if you have stepped or reset physics without refreshing state.
import torch
print(robot.body_names) # Physical bodies, in body-state array order.
print(robot.frame_names) # Named attachments, queried separately.
names = robot.frame_names[:1] # Example: select the first available frame.
position: torch.Tensor = world.state.get_frame_pos(obj_id=0, frame_names=names)
rotation: torch.Tensor = world.state.get_frame_quat_xyzw(obj_id=0, frame_names=names)
Positions are in world coordinates; rotations are world-space xyzw quaternions.
Shapes are (num_envs, len(names), 3) and (num_envs, len(names), 4), in the
requested name order. Body, contact, and joint-wrench arrays exclude frames.
A body and a site may share a name; frame queries select the site.
GPU frame queries return CUDA tensors without host readback. Use fetch=False
only when body poses have already been fetched for the current simulation state.
Add¶
For a new robot with a custom frame, use this in place of the creation example
above. Add frames before creating the robot or template; changing data later
does not update an existing robot.
FixedFrameDesc.body_index refers to the source data.skeleton_tree index.
It is not an index into robot.body_names.
frame: ke.asset.FixedFrameDesc = ke.asset.FixedFrameDesc(
"tool_sensor",
body_index=0,
pos=[0.0, 0.0, 0.1],
)
data.add_fixed_frame(frame=frame)
record: ke.sim.SimArticulation = world.add_articulation(
data,
env_id=0,
obj_id=0,
config=ke.physics.ArticulationConfig.free_base(),
)
robot = record.articulation
This places tool_sensor 0.1 m along the source body’s local Z axis.
Frames do not create collision shapes or contact sensors. To attach one to
the world with a constraint, use D6Batch.create_world_frames(); see
D6 joints.
Visualize¶
Frame axes are off by default. Using the names selected above:
visual.set_frames_visible(obj_id=0, visible=True, env_id=0, frame_names=names)
visual.set_frames_visible(obj_id=0, visible=False, env_id=0) # Clear and stop queries.
Axes update during visual.sync(). While enabled, this debug display copies
selected CUDA poses to the host. The MJCF/URDF DOF examples provide a
Show attachment frames checkbox.
Joint wrenches and efforts¶
Read joint effort¶
Read the solver-computed effort transmitted through each articulation DOF after a completed simulation step:
import torch
# All environments, logical DOF order: (num_envs, num_dofs).
effort: torch.Tensor = world.state.get_dof_projected_joint_forces(obj_id=0)
The effort is computed by projecting the total parent-to-child incoming
joint wrench onto each joint’s motion axes. Revolute and spherical DOFs report
torque in N·m; prismatic DOFs report force in N. This follows the semantics of Isaac’s
get_dof_projected_joint_forces.
The incoming wrench is expressed at the child joint origin in the child joint frame, including authored anchor offsets and axis rotations.
Read link wrench¶
Read the full parent-to-child force and torque for each physical link, including links connected by fixed joints with no DOFs. Empty links preserved only as attachment frames have no separate wrench row:
# All environments, logical body/link order: (num_envs, num_links, 6).
wrenches: torch.Tensor = world.state.get_link_incoming_joint_forces(obj_id=0)
# Last dimension: [Fx, Fy, Fz, Tx, Ty, Tz], in N and N·m.
Each wrench uses the child joint origin and axes described above, not the link COM or world frame. The root row is zero because it has no incoming joint.
For example, when a hand pushes against a wall, this reports the force and torque transmitted through the wrist to the hand. Contact and collision loads affect this reading, as do loads induced by gravity and acceleration; it does not isolate the wall’s contact force.
Choose a force API¶
API |
Returns |
Typical use |
|---|---|---|
|
Force and torque transmitted from the parent joint to each link |
Measuring wrist loads when a hand pushes against a wall, including through fixed joints |
|
Solver-computed force/torque transmitted through each articulation DOF |
Joint effort observation, load monitoring, reward/penalty calculation |
|
Commanded force/torque buffer |
Inspecting actuator commands sent to the articulation |
|
Constraint wrench of a specific external D6 joint |
Measuring loads at hand/foot attachments or other external constraints |
Projected joint effort includes transmitted loads. It is neither a PD estimate nor the isolated wrench of an attached D6 joint.
Projected joint effort is not clamped to the actuator’s effort limit.
CPU and GPU behavior¶
CPU scenes read a reusable PhysX articulation cache. For a standalone CPU
articulation, robot.get_dof_projected_joint_forces() returns a NumPy array of
shape (D,); robot.get_link_incoming_joint_forces() returns (B, 6).
GPU scenes fetch the existing incoming-wrench buffer and select logical links
or DOF components with Torch CUDA; there is no host readback. Both results reuse
storage, so use .clone() when retaining a sample. Advanced callers can use
world.state.gpu.get_link_incoming_joint_forces(obj_id=0, fetch=False) or
world.state.gpu.get_dof_projected_joint_forces(obj_id=0, fetch=False) to reuse
the last incoming-wrench fetch.
Control¶
Run the complete control example with an MJCF file:
python ./python/examples/mjcf_dof_control.py /path/to/robot.xml
Complete source: mjcf_dof_control.py
1"""Generic MJCF articulation DOF position-control viewer."""
2
3from __future__ import annotations
4
5import math
6from pathlib import Path
7
8import numpy as np
9
10import kangengine as ke
11from kangengine.utils._example_args import render_example_parser
12from kangengine import imgui, keys
13
14
15def package_asset_path(*parts: str) -> str:
16 return str(Path(ke.__file__).resolve().parent / "assets" / Path(*parts))
17
18
19def default_mjcf_path() -> Path:
20 return Path(package_asset_path("characters", "kw", "kw.xml"))
21
22
23class MjcfDofControlApp(ke.App):
24 """Load an MJCF articulation and expose every DOF as an ImGui slider."""
25
26 window_title = "MJCF DOF Control"
27 object_name = "mjcf"
28 prim_base_path = "/mjcf"
29 camera_pos = (3.8, -5.4, 1.2)
30 camera_target = (0.0, 0.0, 0.45)
31 # None preserves per-geom MJCF rgba. Set an RGBA tuple to force a single
32 # override color for the whole articulation.
33 visual_color = None # np.array([1,1,1, 1.0])
34 ground_size = 10.0
35 root_pos = (0.0, 0.0, 1.5)
36 root_rot_xyzw = (0.0, 0.0, 0.0, 1.0)
37 fixed_base = False
38 order = "DFS"
39 sim_dt = 1.0 / 240.0
40 step_substeps = 4
41 default_kp = 120.0
42 default_kd = 12.0
43 default_anim_amp = 0.35
44 default_anim_speed = 1.0
45 default_contact_force_scale = 0.002
46 contact_force_threshold = 1e-3
47 visual_alpha_with_collision = 0.1
48 drag_force_debug_path = "/debug/mjcf_drag_force"
49 drag_force_target_debug_path = "/debug/mjcf_drag_force_target"
50
51 def __init__(self, mjcf_path: str | Path):
52 super().__init__()
53 self.mjcf_path = str(Path(mjcf_path).expanduser().resolve())
54
55 def setup(self):
56 self.timing = self.configure_timing(
57 ke.SimulationTimingConfig.from_dt(
58 physics_dt=self.sim_dt,
59 fixed_dt=self.sim_dt * self.step_substeps,
60 render_hz=60.0,
61 )
62 )
63 self.set_simulation_hotkeys_enabled(True)
64 self.elapsed = 0.0
65 self.kp = float(self.default_kp)
66 self.kd = float(self.default_kd)
67 self.animate = True
68 self.anim_amp = float(self.default_anim_amp)
69 self.anim_speed = float(self.default_anim_speed)
70 self.show_collision = False
71 self.show_frames = False
72 self.show_contact_forces = False
73 self.contact_force_scale = float(self.default_contact_force_scale)
74 self.contact_force_view = None
75 self.contact_force_color = np.array([[1.0, 0.25, 0.05, 1.0]], dtype=np.float32)
76 self.empty_vec3 = np.empty((0, 3), dtype=np.float32)
77 self.empty_vec4 = np.empty((0, 4), dtype=np.float32)
78 red = ke.ColorLibrary.get(ke.ColorType.RED)
79 magenta = ke.ColorLibrary.get(ke.ColorType.MAGENTA)
80 self.drag_force_line_color = np.array(
81 [[red.r, red.g, red.b, red.a]], dtype=np.float32
82 )
83 self.drag_force_target_color = np.array(
84 [[magenta.r, magenta.g, magenta.b, magenta.a]], dtype=np.float32
85 )
86 self.drag_force_line_starts = np.empty((3, 3), dtype=np.float32)
87 self.drag_force_line_ends = np.empty((3, 3), dtype=np.float32)
88 self.drag_force_up_z = np.array([0.0, 0.0, 1.0], dtype=np.float32)
89 self.drag_force_up_y = np.array([0.0, 1.0, 0.0], dtype=np.float32)
90 self.drag_force_enabled = True
91 self.drag_force_stiffness = 750.0
92 self.drag_force_damping = 75.0
93 self.drag_force_max = 300.0
94 self.drag_force_arrow_scale = 0.003
95 self.show_drag_force_arrow = True
96 self._drag_force_body_id = None
97 self._drag_force_local_anchor = None
98 self._drag_force_target = None
99 self._drag_force_anchor_world = None
100 self._drag_force_vector = None
101 self._clear_drag_force_arrow()
102
103 self.configure_camera()
104 self.standard_materials = self.create_standard_materials()
105 self.debug_material = self.standard_materials.common
106 self.create_world()
107 self.load_articulation()
108 self._reset()
109 self.print_summary()
110
111 def configure_camera(self):
112 self.get_camera().set_camera_pos(ke.Vec3(*self.camera_pos))
113 self.get_camera().set_target_pos(ke.Vec3(*self.camera_target))
114
115 def create_world(self):
116 self.world = ke.sim.KangSimWorld(
117 num_envs=1,
118 sim_dt=self.timing.physics_dt,
119 add_ground=True,
120 )
121 self.visual = ke.visual.sim.SimWorldVisualizer(self, self.world)
122
123 self.ground_view = self.scene.add_ground(
124 "/ground",
125 scale=float(self.ground_size),
126 material=self.standard_materials.ground,
127 )
128
129 def load_articulation(self):
130 data = self.world.load_mjcf(self.mjcf_path, order=self.order)
131 self.obj_id = 0
132 config = (
133 ke.physics.ArticulationConfig.fixed_base()
134 if self.fixed_base
135 else ke.physics.ArticulationConfig.free_base()
136 )
137 self.robot = self.world.add_articulation(
138 data,
139 env_id=0,
140 obj_id=self.obj_id,
141 name=self.object_name,
142 config=config,
143 ).articulation
144
145 self.articulation_visual_view = self.visual.add_articulation_scene_graph(
146 0,
147 self.obj_id,
148 self.mjcf_path,
149 path=self.prim_base_path,
150 order=self.order,
151 material=self.standard_materials.pbr,
152 collision_path=f"{self.prim_base_path}_collision",
153 show_collision=self.show_collision,
154 color=(
155 None
156 if self.visual_color is None
157 else np.array(self.visual_color, dtype=np.float32)
158 ),
159 )
160 self.visual_body_prims = self.articulation_visual_view.prims
161 # self.collision_body_prims = self.articulation_visual_view.collision_visuals
162
163 self.num_dofs = self.robot.num_dofs()
164 self.dof_names = self.world.state.get_obj_dof_names(self.obj_id)
165 self.dof_limits = np.asarray(
166 self.world.state.get_obj_dof_limits(self.obj_id), dtype=np.float32
167 )
168 if self.dof_limits.shape != (self.num_dofs, 2):
169 self.dof_limits = np.tile(
170 np.array([-math.pi, math.pi], dtype=np.float32),
171 (self.num_dofs, 1),
172 )
173 self.targets = self.initial_targets()
174
175 def initial_targets(self) -> np.ndarray:
176 return np.zeros(self.num_dofs, dtype=np.float32)
177
178 def print_summary(self):
179 print(
180 f"{self.object_name} loaded: links={self.robot.num_links()} dofs={self.num_dofs}"
181 )
182 print("DOFs:", ", ".join(self.dof_names))
183 print("XML:", self.mjcf_path)
184
185 def _reset(self):
186 self.elapsed = 0.0
187 self.targets[:] = self.initial_targets()
188 self.world.set_root_state(
189 None,
190 self.obj_id,
191 np.array(self.root_pos, dtype=np.float32),
192 np.array(self.root_rot_xyzw, dtype=np.float32),
193 )
194 self.world.set_dof_state(None, self.obj_id, self.targets)
195 self.world.set_cmd(
196 None,
197 self.obj_id,
198 self.targets,
199 mode=ke.sim.ControlMode.POS,
200 kp=self.kp,
201 kd=self.kd,
202 )
203 self.world.step(substeps=0, apply_commands=False)
204 self.visual.sync()
205 self._update_contact_force_arrows()
206 self._clear_drag_force()
207
208 def _animated_targets(self):
209 out = np.zeros_like(self.targets)
210 for i in range(self.num_dofs):
211 lo, hi = self.slider_limits(i)
212 span = max(0.0, min(float(hi - lo) * 0.35, self.anim_amp))
213 center = 0.5 * float(lo + hi)
214 phase = self.elapsed * self.anim_speed + i * 0.75
215 out[i] = np.clip(center + span * math.sin(phase), lo, hi)
216 return out
217
218 def slider_limits(self, dof_index: int) -> tuple[float, float]:
219 lo, hi = self.dof_limits[dof_index]
220 if not np.isfinite(lo) or not np.isfinite(hi) or hi <= lo:
221 return -math.pi, math.pi
222 return float(lo), float(hi)
223
224 def pre_update(self):
225 if self.was_key_pressed(keys.R):
226 self._reset()
227 if self.was_key_pressed(keys.Q):
228 self.animate = not self.animate
229
230 def fixed_update(self, fixed_dt):
231 self.elapsed += fixed_dt
232 if self.animate:
233 self.targets[:] = self._animated_targets()
234
235 self.world.set_cmd(
236 None,
237 self.obj_id,
238 self.targets,
239 mode=ke.sim.ControlMode.POS,
240 kp=self.kp,
241 kd=self.kd,
242 )
243 self.world.advance(fixed_dt)
244
245 def pre_render(self):
246 self.visual.sync()
247 self._update_contact_force_arrows()
248 self._update_drag_force_arrow()
249 self.check_error()
250
251 def on_force_drag_begin(self, result, target):
252 if not self.drag_force_enabled or not result.hit:
253 self._clear_drag_force()
254 return
255
256 pick = self.articulation_visual_view.pick_body(result)
257 if pick is None:
258 self._clear_drag_force()
259 return
260
261 self._drag_force_body_id = int(pick.body_id)
262 body_state = self._drag_body_state(self._drag_force_body_id)
263 if body_state is None:
264 return
265 body_pos, body_rot, _, _ = body_state
266 hit_pos = self._vec3_to_np(result.position)
267 self._drag_force_local_anchor = self._quat_inverse_rotate_xyzw(
268 body_rot, hit_pos - body_pos
269 )
270 self._drag_force_target = self._vec3_to_np(target)
271 self._apply_drag_force()
272 self._update_drag_force_arrow()
273
274 def on_force_drag_update(self, result, target):
275 if not self.drag_force_enabled or self._drag_force_body_id is None:
276 self._clear_drag_force()
277 return
278 self._drag_force_target = self._vec3_to_np(target)
279 self._apply_drag_force()
280 self._update_drag_force_arrow()
281
282 def on_force_drag_end(self):
283 self._clear_drag_force()
284
285 def _apply_drag_force(self):
286 if (
287 self._drag_force_body_id is None
288 or self._drag_force_local_anchor is None
289 or self._drag_force_target is None
290 ):
291 return
292 body_state = self._drag_body_state(self._drag_force_body_id)
293 if body_state is None:
294 return
295 body_pos, body_rot, body_vel, body_ang_vel = body_state
296 radius = self._quat_rotate_xyzw(body_rot, self._drag_force_local_anchor)
297 anchor_world = body_pos + radius
298 point_vel = body_vel + np.cross(body_ang_vel, radius)
299 force = (self._drag_force_target - anchor_world) * float(
300 self.drag_force_stiffness
301 ) - point_vel * float(self.drag_force_damping)
302 norm = float(np.linalg.norm(force))
303 if norm > float(self.drag_force_max) > 0.0:
304 force *= float(self.drag_force_max) / norm
305 self._drag_force_anchor_world = anchor_world.astype(np.float32)
306 self._drag_force_vector = force.astype(np.float32)
307 self.world.set_body_force_at_position(
308 0,
309 self.obj_id,
310 self._drag_force_body_id,
311 force.astype(np.float32),
312 anchor_world.astype(np.float32),
313 )
314
315 def _clear_drag_force_arrow(self):
316 self.clear_debug_lines(self.drag_force_debug_path)
317 self.clear_debug_points(self.drag_force_target_debug_path)
318
319 def _update_drag_force_arrow(self):
320 if (
321 not self.show_drag_force_arrow
322 or self._drag_force_anchor_world is None
323 or self._drag_force_vector is None
324 or self._drag_force_target is None
325 ):
326 self._clear_drag_force_arrow()
327 return
328
329 start = self._drag_force_anchor_world
330 force = self._drag_force_vector
331 force_len = float(np.linalg.norm(force))
332 if force_len < 1e-5:
333 self._clear_drag_force_arrow()
334 return
335
336 direction = force / force_len
337 end = start + force * float(self.drag_force_arrow_scale)
338 shaft_len = float(np.linalg.norm(end - start))
339 head_len = min(max(shaft_len * 0.25, 0.04), 0.18)
340
341 side = np.cross(direction, self.drag_force_up_z)
342 if np.linalg.norm(side) < 1e-5:
343 side = np.cross(direction, self.drag_force_up_y)
344 side = side / max(float(np.linalg.norm(side)), 1e-8)
345
346 back = end - direction * head_len
347 left = back + side * head_len * 0.45
348 right = back - side * head_len * 0.45
349 self.drag_force_line_starts[0] = start
350 self.drag_force_line_starts[1] = end
351 self.drag_force_line_starts[2] = end
352 self.drag_force_line_ends[0] = end
353 self.drag_force_line_ends[1] = left
354 self.drag_force_line_ends[2] = right
355 self.log_debug_lines(
356 self.drag_force_debug_path,
357 self.drag_force_line_starts,
358 self.drag_force_line_ends,
359 self.drag_force_line_color,
360 3.0,
361 )
362 self.log_debug_points(
363 self.drag_force_target_debug_path,
364 self._drag_force_target.reshape(1, 3),
365 self.drag_force_target_color,
366 10.0,
367 )
368
369 def _drag_body_state(self, body_id: int):
370 body_pos = self._state_array(self.world.state.get_body_pos(self.obj_id)[0])
371 if body_id >= body_pos.shape[0]:
372 self._clear_drag_force()
373 return None
374 body_rot = self._state_array(self.world.state.get_body_quat_xyzw(self.obj_id)[0])
375 body_vel = self._state_array(self.world.state.get_body_vel(self.obj_id)[0])
376 body_ang_vel = self._state_array(
377 self.world.state.get_body_ang_vel(self.obj_id)[0]
378 )
379 return (
380 body_pos[body_id],
381 body_rot[body_id],
382 body_vel[body_id],
383 body_ang_vel[body_id],
384 )
385
386 def _clear_drag_force(self):
387 if getattr(self, "_drag_force_body_id", None) is not None:
388 self.world.set_body_force(
389 0,
390 self.obj_id,
391 int(self._drag_force_body_id),
392 np.zeros(3, dtype=np.float32),
393 )
394 self._drag_force_body_id = None
395 self._drag_force_local_anchor = None
396 self._drag_force_target = None
397
398 def _clear_contact_force_arrows(self):
399 if self.contact_force_view is None:
400 return
401 self.contact_force_view.update_arrows(
402 self.empty_vec3,
403 self.empty_vec3,
404 self.empty_vec4,
405 )
406
407 def _update_contact_force_arrows(self):
408 if not self.show_contact_forces:
409 self._clear_contact_force_arrows()
410 return
411
412 # Body-aggregated force visualization.
413 # the arrows start at link origins instead of real contact points.
414 # body_pos = np.asarray(
415 # self.world.state.get_body_pos(self.obj_id)[0], dtype=np.float32
416 # )
417 # forces = np.asarray(
418 # self.world.state.get_contact_forces(self.obj_id)[0], dtype=np.float32
419 # )
420 # active = np.linalg.norm(forces, axis=1) > float(self.contact_force_threshold)
421 # starts = body_pos[active]
422 # ends = starts + forces[active] * float(self.contact_force_scale)
423
424 contacts = self.world.physics.get_contacts()
425 starts = []
426 ends = []
427 dt = max(float(self.world.sim_dt), 1e-8)
428 for contact in contacts:
429 position = self._vec3_to_np(contact.position)
430 force = self._vec3_to_np(contact.impulse) / dt
431 if np.linalg.norm(force) <= float(self.contact_force_threshold):
432 continue
433 starts.append(position)
434 ends.append(position + force * float(self.contact_force_scale))
435
436 if not starts:
437 self._clear_contact_force_arrows()
438 return
439
440 starts = np.asarray(starts, dtype=np.float32)
441 ends = np.asarray(ends, dtype=np.float32)
442 colors = np.repeat(self.contact_force_color, starts.shape[0], axis=0)
443
444 if self.contact_force_view is None:
445 self.contact_force_view = self.scene.log_arrows(
446 "/debug/contact_forces",
447 self.debug_material,
448 starts,
449 ends,
450 colors,
451 0.015,
452 12,
453 )
454 else:
455 self.contact_force_view.update_arrows(starts, ends, colors)
456
457 @staticmethod
458 def _vec3_to_np(value) -> np.ndarray:
459 return np.array(
460 [float(value.x), float(value.y), float(value.z)], dtype=np.float32
461 )
462
463 @staticmethod
464 def _state_array(value) -> np.ndarray:
465 if hasattr(value, "detach"):
466 value = value.detach().cpu().numpy()
467 return np.asarray(value, dtype=np.float32)
468
469 @staticmethod
470 def _quat_rotate_xyzw(quat, vector) -> np.ndarray:
471 q = np.asarray(quat, dtype=np.float32)
472 v = np.asarray(vector, dtype=np.float32)
473 qv = q[:3]
474 t = 2.0 * np.cross(qv, v)
475 return (v + q[3] * t + np.cross(qv, t)).astype(np.float32)
476
477 @classmethod
478 def _quat_inverse_rotate_xyzw(cls, quat, vector) -> np.ndarray:
479 q = np.asarray(quat, dtype=np.float32).copy()
480 q[:3] *= -1.0
481 return cls._quat_rotate_xyzw(q, vector)
482
483 def _set_visual_alpha(self, alpha: float):
484 if self.visual_color is None:
485 self.articulation_visual_view.set_alpha(alpha)
486 return
487 color = np.array(self.visual_color, dtype=np.float32).reshape(-1)
488 if color.size == 3:
489 color = np.concatenate([color, np.ones(1, dtype=np.float32)])
490 color = color[:4].copy()
491 color[3] = float(alpha)
492 self.articulation_visual_view.set_color(color)
493
494 def _set_collision_visible(self, visible: bool):
495 self.show_collision = bool(visible)
496 self.articulation_visual_view.set_collision_visible(self.show_collision)
497 self._set_visual_alpha(
498 self.visual_alpha_with_collision if self.show_collision else 1.0
499 )
500
501 def render(self):
502 imgui.begin(self.window_title)
503 state = "paused" if self.is_simulation_paused() else "running"
504 imgui.text(f"State: {state}")
505 imgui.text(
506 "Enter: play/pause Space: pause/step R: reset Q: auto motion"
507 )
508 imgui.text(f"Links: {self.robot.num_links()} DOFs: {self.num_dofs}")
509 imgui.text(Path(self.mjcf_path).name)
510 imgui.separator()
511 _, self.kp = imgui.slider_float("kp", self.kp, 0.0, 1000.0)
512 _, self.kd = imgui.slider_float("kd", self.kd, 0.0, 80.0)
513 _, self.animate = imgui.checkbox("Animate targets", self.animate)
514 _, self.anim_amp = imgui.slider_float("anim amplitude", self.anim_amp, 0.0, 1.5)
515 _, self.anim_speed = imgui.slider_float("anim speed", self.anim_speed, 0.0, 6.0)
516 changed, self.show_collision = imgui.checkbox(
517 "Show collision prims",
518 self.show_collision,
519 )
520 if changed:
521 self._set_collision_visible(self.show_collision)
522 changed, self.show_frames = imgui.checkbox("Show attachment frames", self.show_frames)
523 if changed:
524 self.visual.set_frames_visible(self.obj_id, self.show_frames)
525 changed, self.show_contact_forces = imgui.checkbox(
526 "Show contact forces",
527 self.show_contact_forces,
528 )
529 if changed:
530 self._update_contact_force_arrows()
531 _, self.contact_force_scale = imgui.slider_float(
532 "contact force scale",
533 self.contact_force_scale,
534 0.0,
535 0.02,
536 )
537 imgui.separator()
538 changed, self.drag_force_enabled = imgui.checkbox(
539 "Enable drag force",
540 self.drag_force_enabled,
541 )
542 if changed and not self.drag_force_enabled:
543 self._clear_drag_force()
544 changed, self.show_drag_force_arrow = imgui.checkbox(
545 "Show drag force arrow",
546 self.show_drag_force_arrow,
547 )
548 if changed and not self.show_drag_force_arrow:
549 self._clear_drag_force_arrow()
550 _, self.drag_force_stiffness = imgui.slider_float(
551 "drag force stiffness",
552 self.drag_force_stiffness,
553 0.0,
554 1000.0,
555 )
556 _, self.drag_force_damping = imgui.slider_float(
557 "drag force damping",
558 self.drag_force_damping,
559 0.0,
560 80.0,
561 )
562 _, self.drag_force_max = imgui.slider_float(
563 "drag force max",
564 self.drag_force_max,
565 0.0,
566 2000.0,
567 )
568 _, self.drag_force_arrow_scale = imgui.slider_float(
569 "drag force arrow scale",
570 self.drag_force_arrow_scale,
571 0.0005,
572 0.02,
573 )
574 if self._drag_force_body_id is not None:
575 imgui.text(f"Dragging body: {self._drag_force_body_id}")
576 imgui.separator()
577
578 for i, name in enumerate(self.dof_names):
579 lo, hi = self.slider_limits(i)
580 changed, value = imgui.slider_float(name, float(self.targets[i]), lo, hi)
581 if changed:
582 self.targets[i] = value
583 self.animate = False
584
585 pos = self.world.state.get_dof_pos(self.obj_id)[0]
586 imgui.separator()
587 imgui.text("Current DOF positions")
588 for name, value in zip(self.dof_names, pos):
589 imgui.text(f"{name}: {float(value): .3f}")
590 imgui.end()
591
592 def cleanup(self):
593 if hasattr(self, "visual"):
594 self.visual.release()
595 if hasattr(self, "world"):
596 self.world.release()
597
598
599def main():
600 parser = render_example_parser()
601 parser.add_argument(
602 "mjcf_path",
603 nargs="?",
604 default=str(default_mjcf_path()),
605 help="Path to an MJCF XML file",
606 )
607 parser.add_argument(
608 "--fixed-base",
609 action="store_true",
610 help="Use a fixed root instead of the default free root.",
611 )
612 parser.add_argument("--order", default="DFS", choices=("DFS", "BFS"))
613 parser.add_argument("--width", type=int, default=1920)
614 parser.add_argument("--height", type=int, default=1080)
615 args = parser.parse_args()
616
617 class CliMjcfDofControlApp(MjcfDofControlApp):
618 fixed_base = args.fixed_base
619 order = args.order
620
621 app = CliMjcfDofControlApp(args.mjcf_path)
622 app.initialize(args.width, args.height, False, ke.UpAxis.Z, renderer=args.renderer)
623 app.start()
624
625
626if __name__ == "__main__":
627 main()
MJCF articulation |
Collision debug |
|---|---|
|
|
USD import requirements¶
Prepare a USD robot with:
Z-up,
metersPerUnit = 1, andkilogramsPerUnit = 1.One connected body tree with explicit positive mass and inertia.
convexHullcollision meshes and no joint connecting the root to the world.
Configure initial states, drives, simulation settings, and materials after loading. These scene settings are not fully reproduced by the importer. Unsupported joint or collider configurations raise errors; inspect warnings for omitted properties:
result: ke.asset.USDArticulationImportResult = ke.asset.USDLoader.parse_articulation(
usd_path="robot.usd", prim_path="/Robot"
)
print(result.diagnostics.warnings)

