-
Notifications
You must be signed in to change notification settings - Fork 259
Expand file tree
/
Copy pathmujoco_parser.py
More file actions
4385 lines (3830 loc) · 160 KB
/
Copy pathmujoco_parser.py
File metadata and controls
4385 lines (3830 loc) · 160 KB
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import time
import mujoco
import copy
import glfw
import pathlib
import cv2
import numpy as np
from threading import Lock
MUJOCO_VERSION = tuple(map(int,mujoco.__version__.split('.')))
from .transforms import (
t2p,
t2r,
pr2t,
r2quat,
quat2r,
r2w,
rpy2r,
meters2xyz,
get_rotation_matrix_from_two_points,
)
from .utils import (
trim_scale,
compute_view_params,
get_idxs,
get_colors,
get_monitor_size,
TicTocClass,
)
class MinimalCallbacks:
def __init__(self, hide_menus):
self._gui_lock = Lock()
self._button_left_pressed = False
self._button_right_pressed = False
self._left_double_click_pressed = False
self._right_double_click_pressed = False
self._last_left_click_time = None
self._last_right_click_time = None
self._last_mouse_x = 0
self._last_mouse_y = 0
self._paused = False
self._render_every_frame = True
self._time_per_render = 1/60.0
self._run_speed = 1.0
self._loop_count = 0
self._advance_by_one_step = False
# Keyboard
self._key_pressed = None
self._is_key_pressed = False
# Keyboard buffer
self._key_pressed_set = set()
self._key_repeated_set = set()
def _key_callback(self, window, key, scancode, action, mods):
"""
Key callback
"""
# Flags for key pressed
is_key_pressed = (action==glfw.PRESS)
is_key_released = (action==glfw.RELEASE)
is_key_repeated = (action==glfw.REPEAT)
# Add and discard keys
if is_key_pressed:
self._key_pressed_set.add(key)
if is_key_repeated:
self._key_repeated_set.add(key)
if is_key_released:
# Remove from pressed and repeated lists (if present)
self._key_pressed_set.discard(key)
self._key_repeated_set.discard(key)
# Pause / resume handling (space)
# if is_key_pressed and (key==glfw.KEY_SPACE) and (self._paused is not None):
# self._paused = not self._paused
# Quit (escape)
if (key==glfw.KEY_ESCAPE):
glfw.set_window_should_close(self.window, True)
# Store key pressed (legacy)
self._key_pressed = key
self._is_key_pressed = True
# Return
return
def _cursor_pos_callback(self, window, xpos, ypos):
if not (self._button_left_pressed or self._button_right_pressed):
return
mod_shift = (
glfw.get_key(window, glfw.KEY_LEFT_SHIFT) == glfw.PRESS or
glfw.get_key(window, glfw.KEY_RIGHT_SHIFT) == glfw.PRESS)
if self._button_right_pressed:
action = mujoco.mjtMouse.mjMOUSE_MOVE_H if mod_shift else mujoco.mjtMouse.mjMOUSE_MOVE_V
elif self._button_left_pressed:
action = mujoco.mjtMouse.mjMOUSE_ROTATE_H if mod_shift else mujoco.mjtMouse.mjMOUSE_ROTATE_V
else:
action = mujoco.mjtMouse.mjMOUSE_ZOOM
dx = int(self._scale * xpos) - self._last_mouse_x
dy = int(self._scale * ypos) - self._last_mouse_y
width, height = glfw.get_framebuffer_size(window)
with self._gui_lock:
if self.pert.active:
mujoco.mjv_movePerturb(
self.model,
self.data,
action,
dx / height,
dy / height,
self.scn,
self.pert)
else:
mujoco.mjv_moveCamera(
self.model,
action,
dx / height,
dy / height,
self.scn,
self.cam)
self._last_mouse_x = int(self._scale * xpos)
self._last_mouse_y = int(self._scale * ypos)
def _mouse_button_callback(self, window, button, act, mods):
self._button_left_pressed = button == glfw.MOUSE_BUTTON_LEFT and act == glfw.PRESS
self._button_right_pressed = button == glfw.MOUSE_BUTTON_RIGHT and act == glfw.PRESS
x, y = glfw.get_cursor_pos(window)
self._last_mouse_x = int(self._scale * x)
self._last_mouse_y = int(self._scale * y)
# detect a left- or right- doubleclick
self._left_double_click_pressed = False
self._right_double_click_pressed = False
time_now = glfw.get_time()
if self._button_left_pressed:
if self._last_left_click_time is None:
self._last_left_click_time = glfw.get_time()
time_diff = (time_now - self._last_left_click_time)
if time_diff > 0.01 and time_diff < 0.3:
self._left_double_click_pressed = True
self._last_left_click_time = time_now
if self._button_right_pressed:
if self._last_right_click_time is None:
self._last_right_click_time = glfw.get_time()
time_diff = (time_now - self._last_right_click_time)
if time_diff > 0.01 and time_diff < 0.3:
self._right_double_click_pressed = True
self._last_right_click_time = time_now
# set perturbation
key = mods == glfw.MOD_CONTROL
newperturb = 0
if key and self.pert.select > 0:
# right: translate, left: rotate
if self._button_right_pressed:
newperturb = mujoco.mjtPertBit.mjPERT_TRANSLATE
if self._button_left_pressed:
newperturb = mujoco.mjtPertBit.mjPERT_ROTATE
# perturbation onste: reset reference
if newperturb and not self.pert.active:
mujoco.mjv_initPerturb(
self.model, self.data, self.scn, self.pert)
self.pert.active = newperturb
# 3D release
if act == glfw.RELEASE:
self.pert.active = 0
def _scroll_callback(self, window, x_offset, y_offset):
with self._gui_lock:
mujoco.mjv_moveCamera(
self.model, mujoco.mjtMouse.mjMOUSE_ZOOM, 0, -0.05 * y_offset, self.scn, self.cam)
class MuJoCoMinimalViewer(MinimalCallbacks):
def __init__(
self,
model,
data,
mode = 'window',
title = "MuJoCo Minimal Viewer",
width = None,
height = None,
hide_menus = True,
maxgeom = 10000,
n_fig = 1,
perturbation = True,
use_rgb_overlay = True,
loc_rgb_overlay = 'top right',
):
super().__init__(hide_menus)
self.model = model
self.data = data
self.render_mode = mode
if self.render_mode not in ['window']:
raise NotImplementedError(
"Invalid mode. Only 'window' is supported.")
# keep true while running
self.is_alive = True
self.CONFIG_PATH = pathlib.Path.joinpath(
pathlib.Path.home(), ".config/mujoco_viewer/config.yaml")
# glfw init
glfw.init()
if not width:
width, _ = glfw.get_video_mode(glfw.get_primary_monitor()).size
if not height:
_, height = glfw.get_video_mode(glfw.get_primary_monitor()).size
if self.render_mode == 'offscreen':
glfw.window_hint(glfw.VISIBLE, 0)
# Create window
self.maxgeom = maxgeom
self.window = glfw.create_window(
width, height, title, None, None)
glfw.make_context_current(self.window)
glfw.swap_interval(1)
framebuffer_width, framebuffer_height = glfw.get_framebuffer_size(
self.window)
# install callbacks only for 'window' mode
if self.render_mode == 'window':
window_width, _ = glfw.get_window_size(self.window)
self._scale = framebuffer_width * 1.0 / window_width
# set callbacks
glfw.set_cursor_pos_callback(
self.window, self._cursor_pos_callback)
glfw.set_mouse_button_callback(
self.window, self._mouse_button_callback)
glfw.set_scroll_callback(self.window, self._scroll_callback)
glfw.set_key_callback(self.window, self._key_callback)
# create options, camera, scene, context
self.vopt = mujoco.MjvOption()
self.cam = mujoco.MjvCamera()
self.scn = mujoco.MjvScene(self.model, maxgeom=self.maxgeom)
self.pert = mujoco.MjvPerturb()
self.ctx = mujoco.MjrContext(
self.model, mujoco.mjtFontScale.mjFONTSCALE_150.value)
width, height = glfw.get_framebuffer_size(self.window)
# figures
self.n_fig = n_fig
self.figs = []
for idx in range(self.n_fig):
fig = mujoco.MjvFigure()
mujoco.mjv_defaultFigure(fig)
fig.flg_extend = 1
fig.figurergba = (1,1,1,0)
fig.panergba = (1,1,1,0.2)
self.figs.append(fig)
# get viewport
self.viewport = mujoco.MjrRect(
0, 0, framebuffer_width, framebuffer_height)
# overlay, markers
self._overlay = {}
self._markers = []
# rgb image to overlay (legacy)
self.use_rgb_overlay = use_rgb_overlay
self.loc_rgb_overlay = loc_rgb_overlay
# rgb images to overlay
self.rgb_overlay_top_right = None
self.rgb_overlay_top_left = None
self.rgb_overlay_bottom_right = None
self.rgb_overlay_bottom_left = None
# Perturbation
self.perturbation = perturbation
def add_marker(self, **marker_params):
self._markers.append(marker_params)
def _add_marker_to_scene(self, marker):
if self.scn.ngeom >= self.scn.maxgeom:
raise RuntimeError(
'Ran out of geoms. maxgeom: %d' %
self.scn.maxgeom)
g = self.scn.geoms[self.scn.ngeom]
# default values.
g.dataid = -1
g.objtype = mujoco.mjtObj.mjOBJ_UNKNOWN
g.objid = -1
g.category = mujoco.mjtCatBit.mjCAT_DECOR
# g.matid = -1 # newly added (by Jihwan, 2025-02-27)
"""
mujoco version 3.2 is NOT backward-compatible
"""
if MUJOCO_VERSION[1] == 1:
"""
Following lines make error for mujoco version 3.2
"""
g.texid = -1
g.texuniform = 0
g.texrepeat[0] = 1
g.texrepeat[1] = 1
g.emission = 0
g.specular = 0.5
g.shininess = 0.5
g.reflectance = 0
g.type = mujoco.mjtGeom.mjGEOM_BOX
g.size[:] = np.ones(3) * 0.1
g.mat[:] = np.eye(3)
g.rgba[:] = np.ones(4)
for key, value in marker.items():
# setattr(g, key, value)
if isinstance(value, (int, float, mujoco._enums.mjtGeom)):
setattr(g, key, value)
elif isinstance(value, (tuple, list, np.ndarray)):
attr = getattr(g, key)
attr[:] = np.asarray(value).reshape(attr.shape)
elif isinstance(value, str):
# assert key == "label", "Only label is a string in mjtGeom."
if value is None:
g.label[0] = 0
else:
g.label = value
elif hasattr(g, key):
raise ValueError(
"mjtGeom has attr {} but type {} is invalid".format(
key, type(value)))
else:
raise ValueError("mjtGeom doesn't have field %s" % key)
# Increment number of geoms
self.scn.ngeom += 1
return
def apply_perturbations(self):
self.data.xfrc_applied = np.zeros_like(self.data.xfrc_applied)
mujoco.mjv_applyPerturbPose(self.model, self.data, self.pert, 0)
mujoco.mjv_applyPerturbForce(self.model, self.data, self.pert)
def read_pixels(self, camid=None, depth=False):
if self.render_mode == 'window':
raise NotImplementedError(
"Use 'render()' in 'window' mode.")
if camid is not None:
if camid == -1:
self.cam.type = mujoco.mjtCamera.mjCAMERA_FREE
else:
self.cam.type = mujoco.mjtCamera.mjCAMERA_FIXED
self.cam.fixedcamid = camid
self.viewport.width, self.viewport.height = glfw.get_framebuffer_size(
self.window)
# update scene
mujoco.mjv_updateScene(
self.model,
self.data,
self.vopt,
self.pert,
self.cam,
mujoco.mjtCatBit.mjCAT_ALL.value,
self.scn)
# render
mujoco.mjr_render(self.viewport, self.scn, self.ctx)
shape = glfw.get_framebuffer_size(self.window)
if depth:
rgb_img = np.zeros((shape[1], shape[0], 3), dtype=np.uint8)
depth_img = np.zeros((shape[1], shape[0], 1), dtype=np.float32)
mujoco.mjr_readPixels(rgb_img, depth_img, self.viewport, self.ctx)
return (np.flipud(rgb_img), np.flipud(depth_img))
else:
img = np.zeros((shape[1], shape[0], 3), dtype=np.uint8)
mujoco.mjr_readPixels(img, None, self.viewport, self.ctx)
return np.flipud(img)
def add_overlay(
self,
loc = 'bottom left',
gridpos = mujoco.mjtGridPos.mjGRID_TOPLEFT,
text1 = '',
text2 = '',
):
"""
Add overlay
loc: ['top','top right','top left','bottom','bottom right','bottom left']
Usage:
env.viewer.add_overlay(gridpos=mujoco.mjtGridPos.mjGRID_TOPLEFT,text1='TopLeft')
env.viewer.add_overlay(gridpos=mujoco.mjtGridPos.mjGRID_TOP,text1='Top')
env.viewer.add_overlay(gridpos=mujoco.mjtGridPos.mjGRID_TOPRIGHT,text1='TopRight')
env.viewer.add_overlay(gridpos=mujoco.mjtGridPos.mjGRID_BOTTOMLEFT,text1='BottomLeft')
env.viewer.add_overlay(gridpos=mujoco.mjtGridPos.mjGRID_BOTTOM,text1='Bottom')
env.viewer.add_overlay(gridpos=mujoco.mjtGridPos.mjGRID_BOTTOMRIGHT,text1='BottomRight')
"""
if loc is not None:
if loc == 'top': gridpos = mujoco.mjtGridPos.mjGRID_TOP
elif loc == 'top right': gridpos = mujoco.mjtGridPos.mjGRID_TOPRIGHT
elif loc == 'top left': gridpos = mujoco.mjtGridPos.mjGRID_TOPLEFT
elif loc == 'bottom': gridpos = mujoco.mjtGridPos.mjGRID_BOTTOM
elif loc == 'bottom right': gridpos = mujoco.mjtGridPos.mjGRID_BOTTOMRIGHT
elif loc == 'bottom left': gridpos = mujoco.mjtGridPos.mjGRID_BOTTOMLEFT
if gridpos not in self._overlay:
self._overlay[gridpos] = ["", ""]
self._overlay[gridpos][0] += text1
self._overlay[gridpos][1] += text2
else:
self._overlay[gridpos][0] += "\n" + text1
self._overlay[gridpos][1] += "\n" + text2
# self._overlay[gridpos][0] += text1 + "\n"
# self._overlay[gridpos][1] += text2 + "\n"
def _create_overlay(self):
"""
Overlay items
"""
topleft = mujoco.mjtGridPos.mjGRID_TOPLEFT
topright = mujoco.mjtGridPos.mjGRID_TOPRIGHT
bottomleft = mujoco.mjtGridPos.mjGRID_BOTTOMLEFT
bottomright = mujoco.mjtGridPos.mjGRID_BOTTOMRIGHT
# self.add_overlay(
# gridpos = topleft,
# text1 = "A",
# text2 = "B",
# )
def add_line(
self,
fig_idx = 0,
line_idx = 0,
xdata = np.linspace(0,1,mujoco.mjMAXLINEPNT),
ydata = np.zeros(mujoco.mjMAXLINEPNT),
linergb = (0,0,1),
linename = 'Line Name',
figurergba = (1,1,1,0),
panergba = (1,1,1,0.2),
):
"""
Add line to the internal figure
Usage:
xdata = np.linspace(start=0.0,stop=10.0,num=100)
ydata = np.sin(xdata)
env.viewer.add_line(
fig_idx=0,line_idx=0,xdata=xdata,ydata=ydata,linergb=(1,0,0),linename='Line 1')
xdata = np.linspace(start=0.0,stop=10.0,num=100)
ydata = np.cos(xdata)
env.viewer.add_line(
fig_idx=0,line_idx=1,xdata=xdata,ydata=ydata,linergb=(0,0,1),linename='Line 2')
"""
fig = self.figs[fig_idx]
fig.figurergba = figurergba
fig.panergba = panergba
L = len(xdata) # this cannot exceed 'mujoco.mjMAXLINEPNT'
for i in range(L):
fig.linedata[line_idx][2*i] = xdata[i]
fig.linedata[line_idx][2*i+1] = ydata[i]
fig.linergb[line_idx] = linergb
fig.linename[line_idx] = linename
fig.linepnt[line_idx] = L
def add_rgb_overlay(self,rgb_img_raw,fix_ratio=False):
"""
Set RGB image to render
"""
width,height = glfw.get_framebuffer_size(self.window)
rgb_h,rgb_w = height//4,width//4
self.rgb_overlay = np.zeros((rgb_h,rgb_w,3))
(h,w) = self.rgb_overlay.shape[:2]
if fix_ratio: # fix aspect ratio
h_raw, w_raw = rgb_img_raw.shape[:2]
# Calculate scale to preserve aspect ratio
scale = min(w / w_raw, h / h_raw)
new_w = int(w_raw * scale)
new_h = int(h_raw * scale)
# Resize the image while preserving the aspect ratio
resized_img = cv2.resize(rgb_img_raw, (new_w, new_h), interpolation=cv2.INTER_NEAREST)
# Create a black canvas with the target size
padded_img = np.zeros((h, w, 3), dtype=np.uint8)
# Calculate the top-left corner for centering the resized image
x_offset = (w - new_w) // 2
y_offset = (h - new_h) // 2
# Place the resized image onto the canvas
padded_img[y_offset:y_offset + new_h, x_offset:x_offset + new_w] = resized_img
rgb_img_rsz = padded_img # Final resized and padded image
else:
rgb_img_rsz = cv2.resize(rgb_img_raw,(w,h),interpolation=cv2.INTER_NEAREST)
self.rgb_overlay = rgb_img_rsz
def plot_rgb_overlay(self,rgb=None,loc='top right'):
"""
loc:['top right','top left','bottom right','bottom left']
"""
w_window,h_window = glfw.get_framebuffer_size(self.window)
h_overlay,w_overlay = h_window//4,w_window//4
rgb_overlay = np.zeros((h_overlay,w_overlay,3))
# Fix aspect ratio
h_raw,w_raw = rgb.shape[:2]
# Calculate scale to preserve aspect ratio
scale = min(w_overlay/w_raw,h_overlay/h_raw)
w_new = int(w_raw*scale)
h_new = int(h_raw*scale)
# Resize
rgb_resized = cv2.resize(rgb,(w_new,h_new),interpolation=cv2.INTER_NEAREST)
# Create a black canvas with the target size
rgb_padded = np.zeros((h_overlay,w_overlay,3),dtype=np.uint8)
# Calculate the top-left corner for centering the resized image
x_offset = (w_overlay-w_new) // 2
y_offset = (h_overlay-h_new) // 2
# Place the resized image onto the canvas
rgb_padded[y_offset:y_offset+h_new,x_offset:x_offset+w_new] = rgb_resized
# Store the RGB overlay
if loc=='top right':
self.rgb_overlay_top_right = rgb_padded
elif loc=='top left':
self.rgb_overlay_top_left = rgb_padded
elif loc=='bottom right':
self.rgb_overlay_bottom_right = rgb_padded
elif loc=='bottom left':
self.rgb_overlay_bottom_left = rgb_padded
else:
print ("Invalid location for RGB overlay. Use 'top right', 'top left', 'bottom right', or 'bottom left'.")
def reset_rgb_overlay(self,loc=None):
"""
loc:['top right','top left','bottom right','bottom left']
"""
if loc is None:
self.rgb_overlay_top_right = None
self.rgb_overlay_top_left = None
self.rgb_overlay_bottom_right = None
self.rgb_overlay_bottom_left = None
else:
if loc=='top_right':
self.rgb_overlay_top_right = None
if loc=='top left':
self.rgb_overlay_top_left = None
if loc=='bottom right':
self.rgb_overlay_bottom_right = None
if loc=='bottom left':
self.rgb_overlay_bottom_left = None
def render(self):
if not self.is_alive:
raise Exception(
"GLFW window does not exist but you tried to render.")
if glfw.window_should_close(self.window):
self.close()
return
# mjv_updateScene, mjr_render, mjr_overlay
def update():
# Fill overlay items
self._create_overlay()
# Render start
render_start = time.time()
width, height = glfw.get_framebuffer_size(self.window)
self.viewport.width, self.viewport.height = width, height
with self._gui_lock:
# update scene
mujoco.mjv_updateScene(
self.model,
self.data,
self.vopt,
self.pert,
self.cam,
mujoco.mjtCatBit.mjCAT_ALL.value,
self.scn)
# marker items
for marker in self._markers:
self._add_marker_to_scene(marker)
# render
mujoco.mjr_render(self.viewport, self.scn, self.ctx)
# overlay items
for gridpos, [t1, t2] in self._overlay.items():
mujoco.mjr_overlay(
mujoco.mjtFontScale.mjFONTSCALE_150,
gridpos,
self.viewport,
t1,
t2,
self.ctx)
# handle figures
for idx,fig in enumerate(self.figs):
width_adjustment = width % 4
x = int(3 * width / 4) + width_adjustment
y = idx * int(height / 4)
viewport = mujoco.MjrRect(
x, y, int(width / 4), int(height / 4))
# Plot
mujoco.mjr_figure(viewport, fig, self.ctx)
# roverlay rgb images (legacy)
if self.use_rgb_overlay:
rgb_h,rgb_w = height//4,width//4
if self.loc_rgb_overlay == 'top right':
left = 3*rgb_w
bottom = 3*rgb_h
elif self.loc_rgb_overlay == 'top left':
left = 0*rgb_w
bottom = 3*rgb_h
elif self.loc_rgb_overlay == 'bottom right':
left = 3*rgb_w
bottom = 0*rgb_h
elif self.loc_rgb_overlay == 'bottom left':
left = 0*rgb_w
bottom = 0*rgb_h
else:
print ("Invalid location for RGB overlay. Use 'top right', 'top left', 'bottom right', or 'bottom left'.")
self.viewport_rgb_render = mujoco.MjrRect(
left = left,
bottom = bottom,
width = rgb_w,
height = rgb_h,
)
mujoco.mjr_drawPixels(
rgb = np.flipud(self.rgb_overlay).flatten(),
depth = None,
viewport = self.viewport_rgb_render,
con = self.ctx,
)
# overlay rgb images
if self.rgb_overlay_top_right is not None:
h_overlay,w_overlay = self.rgb_overlay_top_right.shape[:2]
viewport_rgb_top_right = mujoco.MjrRect(
left = 3*w_overlay,
bottom = 3*h_overlay,
width = w_overlay,
height = h_overlay,
)
mujoco.mjr_drawPixels(
rgb = np.flipud(self.rgb_overlay_top_right).flatten(),
depth = None,
viewport = viewport_rgb_top_right,
con = self.ctx,
)
if self.rgb_overlay_top_left is not None:
h_overlay,w_overlay = self.rgb_overlay_top_left.shape[:2]
viewport_rgb_top_left = mujoco.MjrRect(
left = 0*w_overlay,
bottom = 3*h_overlay,
width = w_overlay,
height = h_overlay,
)
mujoco.mjr_drawPixels(
rgb = np.flipud(self.rgb_overlay_top_left).flatten(),
depth = None,
viewport = viewport_rgb_top_left,
con = self.ctx,
)
if self.rgb_overlay_bottom_right is not None:
h_overlay,w_overlay = self.rgb_overlay_bottom_right.shape[:2]
viewport_rgb_bottom_right = mujoco.MjrRect(
left = 3*w_overlay,
bottom = 0*h_overlay,
width = w_overlay,
height = h_overlay,
)
mujoco.mjr_drawPixels(
rgb = np.flipud(self.rgb_overlay_bottom_right).flatten(),
depth = None,
viewport = viewport_rgb_bottom_right,
con = self.ctx,
)
if self.rgb_overlay_bottom_left is not None:
h_overlay,w_overlay = self.rgb_overlay_bottom_left.shape[:2]
viewport_rgb_bottom_left = mujoco.MjrRect(
left = 0*w_overlay,
bottom = 0*h_overlay,
width = w_overlay,
height = h_overlay,
)
mujoco.mjr_drawPixels(
rgb = np.flipud(self.rgb_overlay_bottom_left).flatten(),
depth = None,
viewport = viewport_rgb_bottom_left,
con = self.ctx,
)
# Double buffering
glfw.swap_buffers(self.window)
glfw.poll_events()
self._time_per_render = 0.9 * self._time_per_render + \
0.1 * (time.time() - render_start)
if self._paused: # if paused
while self._paused:
update()
if glfw.window_should_close(self.window):
self.close()
break
if self._advance_by_one_step:
self._advance_by_one_step = False
break
else:
self._loop_count += self.model.opt.timestep / \
(self._time_per_render * self._run_speed)
if self._render_every_frame:
self._loop_count = 1
while self._loop_count > 0:
update()
self._loop_count -= 1
# clear markers
self._markers[:] = []
# clear overlay
self._overlay.clear()
# apply perturbation (should this come before mj_step?)
if self.perturbation:
self.apply_perturbations()
def close(self):
self.is_alive = False
glfw.terminate()
self.ctx.free()
class MuJoCoParserClass(object):
"""
MuJoCo Parser Class
"""
def __init__(
self,
name = None,
rel_xml_path = None,
xml_string = None,
assets = None,
verbose = True,
):
"""
Initialize MuJoCo parser
"""
self.name = name
self.rel_xml_path = rel_xml_path
self.xml_string = xml_string
self.assets = assets
self.verbose = verbose
# Constants
self.tick = 0
self.render_tick = 0
self.use_mujoco_viewer = False
# Parse xml file
if (self.rel_xml_path is not None) or (self.xml_string is not None):
self._parse_xml()
if self.name is None:
self.name = self.model_name
# Tic-toc
self.tt = TicTocClass(name='env:[%s]'%(self.name))
# Monitor size
self.monitor_width,self.monitor_height = get_monitor_size()
# Print
if self.verbose:
self.print_info()
# Reset
self.reset(step=True)
def _parse_xml(self):
"""
Parse xml file
"""
if self.rel_xml_path is not None:
self.full_xml_path = os.path.abspath(os.path.join(os.getcwd(),self.rel_xml_path))
self.model = mujoco.MjModel.from_xml_path(self.full_xml_path)
if self.xml_string is not None:
self.model = mujoco.MjModel.from_xml_string(xml=self.xml_string,assets=self.assets)
# Parse xml model name
parsed_strings = [s for s in self.model.names.split(b'\x00') if s]
parsed_strings = [s.decode('utf-8') for s in parsed_strings]
self.model_name = parsed_strings[0]
self.data = mujoco.MjData(self.model)
self.dt = self.model.opt.timestep
self.HZ = int(1/self.dt)
# Integrator (https://mujoco.readthedocs.io/en/latest/APIreference/APItypes.html#mjtintegrator)
self.integrator = self.model.opt.integrator
if self.integrator == mujoco.mjtIntegrator.mjINT_EULER:
self.integrator_name = 'EULER'
elif self.integrator == mujoco.mjtIntegrator.mjINT_RK4:
self.integrator_name = 'RK4'
elif self.integrator == mujoco.mjtIntegrator.mjINT_IMPLICIT:
self.integrator_name = 'IMPLICIT'
elif self.integrator == mujoco.mjtIntegrator.mjINT_IMPLICITFAST:
self.integrator_name = 'IMPLICITFAST'
else:
self.integrator_name = 'UNKNOWN'
# State and action space
self.n_qpos = self.model.nq # number of states
self.n_qvel = self.model.nv # number of velocities (dimension of tangent space)
self.n_qacc = self.model.nv # number of accelerations (dimension of tangent space)
# Geometry
self.n_geom = self.model.ngeom # number of geometries
self.geom_names = [mujoco.mj_id2name(self.model,mujoco.mjtObj.mjOBJ_GEOM,geom_idx)
for geom_idx in range(self.model.ngeom)]
# Mesh
self.n_mesh = self.model.nmesh # number of meshes
self.mesh_names = [mujoco.mj_id2name(self.model,mujoco.mjtObj.mjOBJ_MESH,mesh_idx)
for mesh_idx in range(self.model.nmesh)]
# Body
self.n_body = self.model.nbody # number of bodies
self.body_names = [mujoco.mj_id2name(self.model,mujoco.mjtObj.mjOBJ_BODY,body_idx)
for body_idx in range(self.n_body)]
self.body_masses = self.model.body_mass # (kg)
self.body_total_mass = self.body_masses.sum()
self.parent_body_names = []
for b_idx in range(self.n_body):
parent_id = self.model.body_parentid[b_idx]
parent_body_name = self.body_names[parent_id]
self.parent_body_names.append(parent_body_name)
# Degree of Freedom
self.n_dof = self.model.nv # degree of freedom (=number of columns of Jacobian)
self.dof_names = [mujoco.mj_id2name(self.model,mujoco.mjtObj.mjOBJ_DOF,dof_idx)
for dof_idx in range(self.n_dof)]
# Joint
self.n_joint = self.model.njnt # number of joints
self.joint_names = [mujoco.mj_id2name(self.model,mujoco.mjtObj.mjOBJ_JOINT,joint_idx)
for joint_idx in range(self.n_joint)]
self.joint_types = self.model.jnt_type # joint types
self.joint_ranges = self.model.jnt_range # joint ranges
self.joint_mins = self.joint_ranges[:,0]
self.joint_maxs = self.joint_ranges[:,1]
# Free joint
self.free_joint_idxs = np.where(self.joint_types==mujoco.mjtJoint.mjJNT_FREE)[0].astype(np.int32)
self.free_joint_names = [self.joint_names[joint_idx] for joint_idx in self.free_joint_idxs]
self.n_free_joint = len(self.free_joint_idxs)
# Revolute Joint
self.rev_joint_idxs = np.where(self.joint_types==mujoco.mjtJoint.mjJNT_HINGE)[0].astype(np.int32)
self.rev_joint_names = [self.joint_names[joint_idx] for joint_idx in self.rev_joint_idxs]
self.n_rev_joint = len(self.rev_joint_idxs)
self.rev_joint_mins = self.joint_ranges[self.rev_joint_idxs,0]
self.rev_joint_maxs = self.joint_ranges[self.rev_joint_idxs,1]
self.rev_joint_ranges = self.rev_joint_maxs - self.rev_joint_mins
# Prismatic Joint
self.pri_joint_idxs = np.where(self.joint_types==mujoco.mjtJoint.mjJNT_SLIDE)[0].astype(np.int32)
self.pri_joint_names = [self.joint_names[joint_idx] for joint_idx in self.pri_joint_idxs]
self.n_pri_joint = len(self.pri_joint_idxs)
self.pri_joint_mins = self.joint_ranges[self.pri_joint_idxs,0]
self.pri_joint_maxs = self.joint_ranges[self.pri_joint_idxs,1]
self.pri_joint_ranges = self.pri_joint_maxs - self.pri_joint_mins
# Revolute + Prismatic Joint Information
self.n_rev_pri_joint = self.n_rev_joint + self.n_pri_joint
self.rev_pri_joint_idxs = np.concatenate([self.rev_joint_idxs,self.pri_joint_idxs])
self.rev_pri_joint_names = self.rev_joint_names + self.pri_joint_names
self.rev_pri_joint_mins = np.concatenate([self.rev_joint_mins,self.pri_joint_mins])
self.rev_pri_joint_maxs = np.concatenate([self.rev_joint_maxs,self.pri_joint_maxs])
self.rev_pri_joint_ranges = self.rev_pri_joint_maxs - self.rev_pri_joint_mins
# Controls
self.n_ctrl = self.model.nu # number of actuators (or controls)
self.ctrl_names = [mujoco.mj_id2name(self.model,mujoco.mjtObj.mjOBJ_ACTUATOR,ctrl_idx)
for ctrl_idx in range(self.n_ctrl)]
self.ctrl_ranges = self.model.actuator_ctrlrange # control range
self.ctrl_mins = self.ctrl_ranges[:,0]
self.ctrl_maxs = self.ctrl_ranges[:,1]
self.ctrl_gears = self.model.actuator_gear[:,0] # gears
# Cameras
self.n_cam = self.model.ncam
self.cam_names = [mujoco.mj_id2name(self.model,mujoco.mjtObj.mjOBJ_CAMERA,cam_idx)
for cam_idx in range(self.n_cam)]
self.cams = []
self.cam_fovs = []
self.cam_viewports = []
for cam_idx in range(self.n_cam):
cam_name = self.cam_names[cam_idx]
cam = mujoco.MjvCamera()
cam.fixedcamid = self.model.cam(cam_name).id
cam.type = mujoco.mjtCamera.mjCAMERA_FIXED
cam_fov = self.model.cam_fovy[cam_idx]
viewport = mujoco.MjrRect(0,0,800,600) # SVGA?
# Append
self.cams.append(cam)
self.cam_fovs.append(cam_fov)
self.cam_viewports.append(viewport)
# qpos and qvel indices attached to the controls
"""
# Usage
self.env.data.qpos[self.env.ctrl_qpos_idxs] # joint position
self.env.data.qvel[self.env.ctrl_qvel_idxs] # joint velocity
"""
self.ctrl_qpos_idxs = []
self.ctrl_qpos_names = []
self.ctrl_qpos_mins = []
self.ctrl_qpos_maxs = []
self.ctrl_qvel_idxs = []
self.ctrl_types = []
for ctrl_idx in range(self.n_ctrl):
# transmission (joint) index attached to an actuator, we assume that there is just one joint attached
joint_idx = self.model.actuator(self.ctrl_names[ctrl_idx]).trnid[0]
# joint position attached to control
self.ctrl_qpos_idxs.append(self.model.jnt_qposadr[joint_idx])
self.ctrl_qpos_names.append(self.joint_names[joint_idx])
self.ctrl_qpos_mins.append(self.joint_ranges[joint_idx,0])
self.ctrl_qpos_maxs.append(self.joint_ranges[joint_idx,1])
# joint velocity attached to control
self.ctrl_qvel_idxs.append(self.model.jnt_dofadr[joint_idx])
# Check types
trntype = self.model.actuator_trntype[ctrl_idx]
if trntype == mujoco.mjtTrn.mjTRN_JOINT:
self.ctrl_types.append('JOINT')
elif trntype == mujoco.mjtTrn.mjTRN_TENDON:
self.ctrl_types.append('TENDON')
else:
self.ctrl_types.append('UNKNOWN(trntype=%d)'%(trntype))
# Sensor
self.n_sensor = self.model.nsensor
self.sensor_names = [mujoco.mj_id2name(self.model,mujoco.mjtObj.mjOBJ_SENSOR,sensor_idx)
for sensor_idx in range(self.n_sensor)]
# Site
self.n_site = self.model.nsite
self.site_names = [mujoco.mj_id2name(self.model,mujoco.mjtObj.mjOBJ_SITE,site_idx)
for site_idx in range(self.n_site)]
def print_info(self):
"""
Print model information
"""
print ("")
print ("-----------------------------------------------------------------------------")
print ("name:[%s] dt:[%.3f] HZ:[%d]"%(self.name,self.dt,self.HZ))
print (" n_qpos:[%d] n_qvel:[%d] n_qacc:[%d] n_ctrl:[%d]"%(self.n_qpos,self.n_qvel,self.n_qacc,self.n_ctrl))
print (" integrator:[%s]"%(self.integrator_name))
print ("")
print ("n_body:[%d]"%(self.n_body))
for body_idx,body_name in enumerate(self.body_names):
body_mass = self.body_masses[body_idx]
print (" [%d/%d] [%s] mass:[%.2f]kg"%(body_idx,self.n_body,body_name,body_mass))
print ("body_total_mass:[%.2f]kg"%(self.body_total_mass))
print ("")
print ("n_geom:[%d]"%(self.n_geom))
print ("geom_names:%s"%(self.geom_names))
print ("")
print ("n_mesh:[%d]"%(self.n_mesh))
print ("mesh_names:%s"%(self.mesh_names))
print ("")
print ("n_joint:[%d]"%(self.n_joint))
for joint_idx,joint_name in enumerate(self.joint_names):
print (" [%d/%d] [%s] axis:%s"%
(joint_idx,self.n_joint,joint_name,self.model.joint(joint_idx).axis))
# print ("joint_types:[%s]"%(self.joint_types))
# print ("joint_ranges:[%s]"%(self.joint_ranges))
print ("")
print ("n_dof:[%d] (=number of rows of Jacobian)"%(self.n_dof))