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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
//! Implementation of the interface for use in the viewer.
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use std::ffi::CString;
use std::fmt::Debug;
use glutin::display::{Display, GlDisplay};
use egui_winit::winit::event::WindowEvent;
use egui_glow::glow::{self, HasContext};
use egui::{FontId, RichText, Id};
use egui_winit::winit::window::Window;
use egui_winit::egui;
use egui_winit;
use crate::wrappers::mj_model::{MjModel, MjtObj, MjtJoint, MjtDisableBit, MjtEnableBit};
use crate::wrappers::mj_visualization::{MjvOption, MjvCamera, MjtCamera, MjvScene};
use crate::viewer::{ViewerSharedState, ViewerStatusBit, MjViewerError};
use crate::wrappers::mj_primitive::MjtNum;
use crate::wrappers::mj_data::MjData;
use crate::{cast_mut_info, set_flag};
use crate::mujoco_c::mjNGROUP;
use crate::util::LockUnpoison;
/* UI Fonts */
const MAIN_FONT: FontId = FontId::proportional(15.0);
const HEADING_FONT: FontId = FontId::proportional(20.0);
/* UI Spacing and Dimensions */
const HEADING_POST_SPACE: f32 = 5.0;
const BUTTON_SPACING_X: f32 = 10.0;
const BUTTON_SPACING_Y: f32 = 5.0;
const BUTTON_ROUNDING: f32 = 50.0;
const SIDE_PANEL_DEFAULT_WIDTH: f32 = 200.0;
const TOGGLE_LABEL_HEIGHT_EXTRA_SPACE: f32 = 20.0;
const SIDE_PANEL_PAD: f32 = 10.0;
const MAX_SPAN_WIDTH: f32 = 350.0;
/* Precision and Tolerances */
const RANGE_PRECISION_TOLERANCE: f32 = 1e-4;
/* Camera Tracking Modal Settings */
const CAMERA_MODAL_MAX_HEIGHT: f32 = 300.0;
const CAMERA_MODAL_BUTTONS_PER_ROW: usize = 5;
const CAMERA_MODAL_BUTTON_WIDTH: f32 = 100.0;
const CAMERA_MODAL_BUTTON_HEIGHT: f32 = 35.0;
const CAMERA_MODAL_CELL_SIZE: egui::Vec2 = egui::Vec2 { x: CAMERA_MODAL_BUTTON_WIDTH, y: CAMERA_MODAL_BUTTON_HEIGHT };
const CAMERA_MODAL_BUTTON_ROUNDING: f32 = 4.0;
const CAMERA_MODAL_BUTTON_COLOR_DEFAULT: u8 = 40;
const CAMERA_MODAL_BUTTON_COLOR_HOVERED: u8 = 60;
/* Model Synchronization and Status */
const PHYSICS_SYNC_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1);
const MODEL_OPT_SYNC_WARNING: &str = "[WARNING] Physics options not synced!";
const MODEL_VIS_SYNC_WARNING: &str = "[WARNING] Visualization options not synced!";
const MODEL_STAT_SYNC_WARNING: &str = "[WARNING] Statistics not synced!";
/// Maps [`MjtRndFlag`](crate::wrappers::mj_visualization::MjtRndFlag) to their string
const GL_EFFECT_MAP: [&str; 11] = [
"Shadow",
"Wireframe",
"Reflection",
"Additive",
"Skybox",
"Fog",
"Haze",
"Depth",
"Segment",
"ID color",
"Cull face"
];
const _: () = assert!(GL_EFFECT_MAP.len() == crate::mujoco_c::mjtRndFlag_::mjNRNDFLAG as usize);
/// Maps [`MjtVisFlag`](crate::wrappers::mj_visualization::MjtVisFlag) to their string
const VIS_OPT_MAP: [&str; 31] = [
"Convex hull",
"Texture",
"Joint",
"Camera",
"Actuator",
"Activation",
"Light",
"Tendon",
"Range finder",
"Constraint",
"Inertia",
"Scale inertia",
"Perturbation force",
"Perturbation object",
"Contact point",
"Island",
"Contact force",
"Contact split",
"Transparent",
"Auto-connect",
"Center of mass",
"Select",
"Static",
"Skin",
"Flex vertex",
"Flex edge",
"Flex face",
"Flex skin",
"Body BVH",
"Mesh BVH",
"SDF iteration"
];
const _: () = assert!(VIS_OPT_MAP.len() == crate::mujoco_c::mjtVisFlag_::mjNVISFLAG as usize);
/// Maps [`MjtLabel`](crate::wrappers::mj_visualization::MjtLabel) to their string
const LABEL_TYPE_MAP: [&str; 17] = [
"None",
"Body",
"Joint",
"Geom",
"Site",
"Camera",
"Light",
"Tendon",
"Actuator",
"Constraint",
"Flex",
"Skin",
"Selection",
"Selection point",
"Contact point",
"Contact force",
"Island"
];
const _: () = assert!(LABEL_TYPE_MAP.len() == crate::mujoco_c::mjtLabel_::mjNLABEL as usize);
/// Maps [`MjtFrame`](crate::wrappers::mj_visualization::MjtFrame) to their string
const FRAME_TYPE_MAP: [&str; 8] = [
"None",
"Body",
"Geom",
"Site",
"Camera",
"Light",
"Contact",
"World"
];
const _: () = assert!(FRAME_TYPE_MAP.len() == crate::mujoco_c::mjtFrame_::mjNFRAME as usize);
/// Maps integrator modes to their string representations
const INTEGRATOR_MAP: [&str; 4] = [
"Euler",
"RK4",
"implicit",
"implicitfast"
];
/// Maps friction cone types to their string representations
const CONE_MAP: [&str; 2] = [
"Pyramidal",
"Elliptic"
];
/// Maps Jacobian types to their string representations
const JACOBIAN_MAP: [&str; 3] = [
"Dense",
"Sparse",
"Auto"
];
/// Maps solver algorithms to their string representations
const SOLVER_MAP: [&str; 3] = [
"PGS",
"CG",
"Newton"
];
/// Maps MuJoCo disable flag bits to their string representations
const DISABLE_FLAGS: &[(&str, MjtDisableBit)] = &[
("Constraint", MjtDisableBit::mjDSBL_CONSTRAINT),
("Equality", MjtDisableBit::mjDSBL_EQUALITY),
("Friction Loss", MjtDisableBit::mjDSBL_FRICTIONLOSS),
("Limit", MjtDisableBit::mjDSBL_LIMIT),
("Contact", MjtDisableBit::mjDSBL_CONTACT),
("Spring", MjtDisableBit::mjDSBL_SPRING),
("Damper", MjtDisableBit::mjDSBL_DAMPER),
("Gravity", MjtDisableBit::mjDSBL_GRAVITY),
("Clamp Ctrl", MjtDisableBit::mjDSBL_CLAMPCTRL),
("Warm Start", MjtDisableBit::mjDSBL_WARMSTART),
("Filter Parent", MjtDisableBit::mjDSBL_FILTERPARENT),
("Actuation", MjtDisableBit::mjDSBL_ACTUATION),
("Ref Safe", MjtDisableBit::mjDSBL_REFSAFE),
("Sensor", MjtDisableBit::mjDSBL_SENSOR),
("Mid Phase", MjtDisableBit::mjDSBL_MIDPHASE),
("Euler Damp", MjtDisableBit::mjDSBL_EULERDAMP),
("Auto Reset", MjtDisableBit::mjDSBL_AUTORESET),
("Native CCD", MjtDisableBit::mjDSBL_NATIVECCD),
("Island", MjtDisableBit::mjDSBL_ISLAND),
("Multi CCD", MjtDisableBit::mjDSBL_MULTICCD),
];
const _: () = assert!(DISABLE_FLAGS.len() == crate::mujoco_c::mjtDisableBit_::mjNDISABLE as usize);
/// Maps MuJoCo enable flag bits to their string representations
const ENABLE_FLAGS: &[(&str, MjtEnableBit)] = &[
("Override", MjtEnableBit::mjENBL_OVERRIDE),
("Energy", MjtEnableBit::mjENBL_ENERGY),
("Forward Inverse", MjtEnableBit::mjENBL_FWDINV),
("Inverse Discrete", MjtEnableBit::mjENBL_INVDISCRETE),
("Sleep", MjtEnableBit::mjENBL_SLEEP),
];
const _: () = assert!(ENABLE_FLAGS.len() == crate::mujoco_c::mjtEnableBit_::mjNENABLE as usize);
/// Type alias for a user-provided UI callback function.
pub(crate) type UiCallback = Box<dyn FnMut(&egui::Context, &mut MjData<Box<MjModel>>)>;
/// Type alias for a detached (from state) user-provided UI callback function.
pub(crate) type UiCallbackDetached = Box<dyn FnMut(&egui::Context)>;
/// Viewer user interface context.
pub(crate) struct ViewerUI {
egui_ctx: egui::Context,
state: egui_winit::State,
painter: egui_glow::Painter,
gl: Arc<egui_glow::glow::Context>,
events: VecDeque<UiEvent>,
camera_names: Vec<String>,
actuator_display_info: Vec<(String, bool, [MjtNum; 2])>,
joint_display_info: Vec<(String, bool, [MjtNum; 2], usize)>,
equality_names: Vec<String>,
user_ui_callbacks: Vec<UiCallback>,
user_ui_callbacks_detached: Vec<UiCallbackDetached>,
// Window toggles.
// Note that these are bool for easier integration with egui.
// We assumed they won't take up too much extra space, since
// running multiple viewers isn't what most people will do
// and even then this is minor.
actuator_window: bool,
joint_window: bool,
equality_window: bool,
group_window: bool,
screenshot_viewport_only: bool,
screenshot_depth: bool,
// Camera tracking modal state
show_tracking_modal: bool,
tracking_selected_body: Option<usize>,
}
impl ViewerUI {
/// Create a new [`ViewerUI`] instance for the specific winit window.
pub(crate) fn new(model: &MjModel, window: &Window, display: &Display) -> Result<Self, MjViewerError> {
let egui_ctx = egui::Context::default();
let viewport_id = egui_ctx.viewport_id();
let state = egui_winit::State::new(
egui_ctx.clone(), viewport_id, &window,
None, None, None
);
let get_addr = |s: &str| display.get_proc_address(
&CString::new(s).unwrap()
);
// SAFETY: the glow::Context is constructed from a loader function backed by the
// current glutin Display, which provides valid OpenGL proc addresses.
let gl = unsafe { Arc::new(egui_glow::glow::Context::from_loader_function(get_addr)) };
let painter = egui_glow::Painter::new(
gl.clone(),
"",
None,
false
).map_err(|e| MjViewerError::PainterInitError(e.to_string()))?;
let mut viewer_ui = Self {
egui_ctx, state, painter, gl, events: VecDeque::new(),
camera_names: Vec::new(),
actuator_display_info: Vec::new(),
joint_display_info: Vec::new(),
equality_names: Vec::new(),
user_ui_callbacks: Vec::new(),
user_ui_callbacks_detached: Vec::new(),
actuator_window: false,
joint_window: false,
equality_window: false,
group_window: false,
screenshot_viewport_only: false,
screenshot_depth: false,
show_tracking_modal: false,
tracking_selected_body: None,
};
viewer_ui.update_names(model);
Ok(viewer_ui)
}
/// Rebuilds all model-dependent cached state (name lists).
/// Must be called whenever the active model changes.
pub(crate) fn update_names(&mut self, model: &MjModel) {
self.camera_names = (0..model.ncam()).map(|i| {
if let Some(name) = model.id_to_name(MjtObj::mjOBJ_CAMERA, i as usize) {
name.to_string()
} else { format!("Camera {i}") }
}).collect();
self.actuator_display_info = (0..model.nu()).map(|i| {
let idx = i as usize;
let name = if let Some(name) = model.id_to_name(MjtObj::mjOBJ_ACTUATOR, idx) {
name.to_string()
} else { format!("Actuator {i}") };
let limited = model.actuator_ctrllimited()[idx];
let range = model.actuator_ctrlrange()[idx];
(name, limited, range)
}).collect();
self.joint_display_info = (0..model.njnt()).filter_map(|i| {
let idx = i as usize;
match model.jnt_type()[idx] {
MjtJoint::mjJNT_SLIDE | MjtJoint::mjJNT_HINGE => {
let name = if let Some(name) = model.id_to_name(MjtObj::mjOBJ_JOINT, idx) {
name.to_string()
} else { format!("Joint {i}") };
let limited = model.jnt_limited()[idx];
let range = model.jnt_range()[idx];
let qpos_adr = model.jnt_qposadr()[idx] as usize;
Some((name, limited, range, qpos_adr))
}
_ => None
}
}).collect();
self.equality_names = (0..model.neq()).map(|i| {
if let Some(name) = model.id_to_name(MjtObj::mjOBJ_EQUALITY, i as usize) {
name.to_string()
} else { format!("Equality {i}") }
}).collect();
}
/// Handles winit input events.
pub(crate) fn handle_events(&mut self, window: &Window, event: &WindowEvent) {
let _ = self.state.on_window_event(window, event); // ignore response as it can be obtained later.
}
/// Gains scoped access to [`egui::Context`] for dealing with custom initialization
/// (e.g., loading in images).
pub(crate) fn with_egui_ctx<F>(&mut self, once_fn: F)
where F: FnOnce(&egui::Context)
{
once_fn(&mut self.egui_ctx)
}
/// Draws the UI to the viewport.
#[allow(clippy::too_many_arguments)]
pub(crate) fn process(
&mut self,
window: &Window, status: &mut ViewerStatusBit,
scene: &mut MjvScene, options: &mut MjvOption,
camera: &mut MjvCamera,
shared_viewer_state: &Arc<Mutex<ViewerSharedState>>,
) -> f32 {
// Viewport reservations, which will be excluded from MuJoCo's viewport.
// This way MuJoCo won't draw over the UI.
let mut left = 0.0;
// Process the UI
let raw_input = self.state.take_egui_input(window);
let full_output = self.egui_ctx.run(raw_input, |ctx| {
if status.contains(ViewerStatusBit::UI) {
egui::SidePanel::new(egui::panel::Side::Left,"interface_panel")
.resizable(true)
.default_width(SIDE_PANEL_DEFAULT_WIDTH)
.show(ctx, |ui|
{
// The menu
egui::ScrollArea::vertical()
.max_height(ui.available_height() - (TOGGLE_LABEL_HEIGHT_EXTRA_SPACE + HEADING_POST_SPACE + HEADING_FONT.size))
.show(ui, |ui|
{
// Make buttons have more space in the width
let spacing = ui.spacing_mut();
spacing.button_padding.x = BUTTON_SPACING_X;
spacing.button_padding.y = BUTTON_SPACING_Y;
/* Window controls */
egui::CollapsingHeader::new(RichText::new("Basic").font(HEADING_FONT))
.default_open(true)
.show(ui, |ui|
{
ui.horizontal_wrapped(|ui| {
if ui.add(egui::Button::new(
RichText::new("Quit").font(MAIN_FONT)
).corner_radius(BUTTON_ROUNDING)).clicked() {
self.events.push_back(UiEvent::Close);
}
});
});
/* UI toggles */
egui::CollapsingHeader::new(RichText::new("UI").font(HEADING_FONT))
.default_open(true)
.show(ui, |ui|
{
// Normal toggles
ui.horizontal_wrapped(|ui| {
let mut selected = status.contains(ViewerStatusBit::HELP);
ui.toggle_value(&mut selected, RichText::new("Help").font(MAIN_FONT));
status.set(ViewerStatusBit::HELP, selected);
selected = window.fullscreen().is_some();
if ui.toggle_value(&mut selected, RichText::new("Fullscreen").font(MAIN_FONT)).clicked() {
self.events.push_back(UiEvent::Fullscreen);
};
// VSync
let mut selected = status.contains(ViewerStatusBit::VSYNC);
if ui.toggle_value(&mut selected, RichText::new("V-Sync").font(MAIN_FONT)).clicked() {
self.events.push_back(UiEvent::VSyncToggle);
};
status.set(ViewerStatusBit::VSYNC, selected);
// Info menu (FPS, time, etc.)
let mut selected = status.contains(ViewerStatusBit::INFO);
ui.toggle_value(&mut selected, RichText::new("Info").font(MAIN_FONT));
status.set(ViewerStatusBit::INFO, selected);
});
ui.separator();
/* Window toggles */
ui.horizontal_wrapped(|ui| {
ui.toggle_value(&mut self.actuator_window, RichText::new("Actuator").font(MAIN_FONT));
ui.toggle_value(&mut self.joint_window, RichText::new("Joint").font(MAIN_FONT));
ui.toggle_value(&mut self.equality_window, RichText::new("Equality").font(MAIN_FONT));
ui.toggle_value(&mut self.group_window, RichText::new("Group").font(MAIN_FONT));
});
ui.separator();
ui.horizontal_wrapped(|ui| {
// Warnings
ui.collapsing(RichText::new("Warnings").font(MAIN_FONT), |ui| {
// Non-realtime factor warning
let mut selected = status.contains(ViewerStatusBit::WARN_REALTIME);
ui.checkbox(&mut selected, RichText::new("Realtime factor").font(MAIN_FONT));
status.set(ViewerStatusBit::WARN_REALTIME, selected);
});
});
});
/* Simulation */
egui::CollapsingHeader::new(RichText::new("Simulation").font(HEADING_FONT))
.default_open(true)
.show(ui, |ui|
{
ui.horizontal_wrapped(|ui| {
// Reset simulation
if ui.add(egui::Button::new(
RichText::new("Reset").font(MAIN_FONT)
).corner_radius(BUTTON_ROUNDING)).clicked() {
self.events.push_back(UiEvent::ResetSimulation);
}
// Align camera
if ui.add(egui::Button::new(
RichText::new("Align").font(MAIN_FONT)
).corner_radius(BUTTON_ROUNDING)).clicked() {
self.events.push_back(UiEvent::AlignCamera);
}
});
});
/* Physics options */
egui::CollapsingHeader::new(RichText::new("Physics").font(HEADING_FONT))
.show(ui, |ui|
{
let (opt_is_editable, mut options) = {
let state = shared_viewer_state.lock_unpoison();
(
state.last_opt_sync_time().elapsed() < PHYSICS_SYNC_TIMEOUT,
state.data_passive.model().opt().clone(),
)
};
if !opt_is_editable {
ui.colored_label(egui::Color32::YELLOW, MODEL_OPT_SYNC_WARNING);
}
// Physics solver and method selectors (top level)
egui::Grid::new("physics_enum_grid").num_columns(2).show(ui, |ui| {
ui.label(RichText::new("Integrator").font(MAIN_FONT));
let combo_width = ui.available_width().min(MAX_SPAN_WIDTH);
let current_integrator = INTEGRATOR_MAP.get(options.integrator as usize).copied().unwrap_or("Unknown");
let mut integrator_idx = options.integrator as usize;
egui::ComboBox::from_id_salt("integrator_combo")
.selected_text(current_integrator)
.width(combo_width)
.show_ui(ui, |ui| {
for (i, integrator_name) in INTEGRATOR_MAP.iter().enumerate() {
ui.selectable_value(&mut integrator_idx, i, *integrator_name);
}
});
options.integrator = integrator_idx as i32;
ui.end_row();
ui.label(RichText::new("Cone").font(MAIN_FONT));
let current_cone = CONE_MAP.get(options.cone as usize).copied().unwrap_or("Unknown");
let mut cone_idx = options.cone as usize;
egui::ComboBox::from_id_salt("cone_combo")
.selected_text(current_cone)
.width(combo_width)
.show_ui(ui, |ui| {
for (i, cone_name) in CONE_MAP.iter().enumerate() {
ui.selectable_value(&mut cone_idx, i, *cone_name);
}
});
options.cone = cone_idx as i32;
ui.end_row();
ui.label(RichText::new("Jacobian").font(MAIN_FONT));
let current_jacobian = JACOBIAN_MAP.get(options.jacobian as usize).copied().unwrap_or("Unknown");
let mut jacobian_idx = options.jacobian as usize;
egui::ComboBox::from_id_salt("jacobian_combo")
.selected_text(current_jacobian)
.width(combo_width)
.show_ui(ui, |ui| {
for (i, jacobian_name) in JACOBIAN_MAP.iter().enumerate() {
ui.selectable_value(&mut jacobian_idx, i, *jacobian_name);
}
});
options.jacobian = jacobian_idx as i32;
ui.end_row();
ui.label(RichText::new("Solver").font(MAIN_FONT));
let current_solver = SOLVER_MAP.get(options.solver as usize).copied().unwrap_or("Unknown");
let mut solver_idx = options.solver as usize;
egui::ComboBox::from_id_salt("solver_combo")
.selected_text(current_solver)
.width(combo_width)
.show_ui(ui, |ui| {
for (i, solver_name) in SOLVER_MAP.iter().enumerate() {
ui.selectable_value(&mut solver_idx, i, *solver_name);
}
});
options.solver = solver_idx as i32;
ui.end_row();
});
ui.collapsing(RichText::new("Algorithm parameters").font(MAIN_FONT), |ui| {
egui::Grid::new("algo_param_grid").num_columns(2).show(ui, |ui| {
ui.add(
RowScalar::new("Timestep", &mut options.timestep, 1e-6)
.range(0.0..=f64::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Iterations", &mut options.iterations, 1.0)
.range(1..=i32::MAX)
);
ui.end_row();
ui.add(
RowScalar::new("Tolerance", &mut options.tolerance, 1e-8)
.range(0.0..=f64::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("LS Iter", &mut options.ls_iterations, 1.0)
.range(1..=i32::MAX)
);
ui.end_row();
ui.add(
RowScalar::new("LS Tol", &mut options.ls_tolerance, 1e-8)
.range(0.0..=f64::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Noslip Iter", &mut options.noslip_iterations, 1.0)
.range(0..=i32::MAX)
);
ui.end_row();
ui.add(
RowScalar::new("Noslip Tol", &mut options.noslip_tolerance, 1e-8)
.range(0.0..=f64::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("CCD Iter", &mut options.ccd_iterations, 1.0)
.range(1..=i32::MAX)
);
ui.end_row();
ui.add(
RowScalar::new("CCD Tol", &mut options.ccd_tolerance, 1e-8)
.range(0.0..=f64::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Sleep Tol", &mut options.sleep_tolerance, 1e-8)
.range(0.0..=f64::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("SDF Iter", &mut options.sdf_iterations, 1.0)
.range(1..=i32::MAX)
);
ui.end_row();
ui.add(
RowScalar::new("SDF Init", &mut options.sdf_initpoints, 1.0)
.range(0..=i32::MAX)
);
ui.end_row();
});
});
ui.collapsing(RichText::new("Physics parameters").font(MAIN_FONT), |ui| {
egui::Grid::new("phys_param_grid").num_columns(2).show(ui, |ui| {
ui.add(
RowScalar::new("Density", &mut options.density, 1e-3)
.range(0.0..=f64::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Viscosity", &mut options.viscosity, 1e-6)
.range(0.0..=f64::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Imp Ratio", &mut options.impratio, 1e-3)
.range(0.0..=f64::INFINITY)
);
ui.end_row();
ui.add(RowArray::new(
"Gravity", &mut options.gravity, 1e-3
));
ui.end_row();
ui.add(RowArray::new(
"Wind", &mut options.wind, 1e-3
));
ui.end_row();
ui.add(RowArray::new(
"Magnetic", &mut options.magnetic, 1e-3
));
ui.end_row();
});
});
ui.collapsing(RichText::new("Disable Flags").font(MAIN_FONT), |ui| {
ui.horizontal_wrapped(|ui| {
for (flag_name, flag_value) in DISABLE_FLAGS {
let mut is_enabled = (options.disableflags & (*flag_value as i32)) != 0;
if ui.toggle_value(&mut is_enabled, *flag_name).changed() {
set_flag!(options.disableflags, *flag_value as i32, is_enabled);
}
}
});
});
ui.collapsing(RichText::new("Enable Flags").font(MAIN_FONT), |ui| {
ui.horizontal_wrapped(|ui| {
for (flag_name, flag_value) in ENABLE_FLAGS {
let mut is_enabled = (options.enableflags & (*flag_value as i32)) != 0;
if ui.toggle_value(&mut is_enabled, *flag_name).changed() {
set_flag!(options.enableflags, *flag_value as i32, is_enabled);
}
}
});
});
ui.collapsing(RichText::new("Actuator Group Enable").font(MAIN_FONT), |ui| {
ui.horizontal_wrapped(|ui| {
for i in 0..mjNGROUP as usize {
let mask = 1 << i;
let mut is_enabled = (options.disableactuator & (mask as i32)) == 0;
if ui.toggle_value(&mut is_enabled, format!("Act Group {i}")).changed() {
set_flag!(options.disableactuator, mask as i32, !is_enabled);
}
}
});
});
ui.collapsing(RichText::new("Contact Override").font(MAIN_FONT), |ui| {
egui::Grid::new("contact_override_grid").num_columns(2).show(ui, |ui| {
ui.add(
RowScalar::new("Margin", &mut options.o_margin, 1e-5)
.range(0.0..=f64::INFINITY)
);
ui.end_row();
ui.add(RowArray::new(
"Sol Ref", &mut options.o_solref, 1e-5
));
ui.end_row();
ui.add(RowArray::new(
"Sol Imp", &mut options.o_solimp, 1e-3
));
ui.end_row();
ui.add(RowArray::new(
"Friction", &mut options.o_friction, 1e-3
));
ui.end_row();
});
});
*shared_viewer_state.lock_unpoison().data_passive.model_opt_mut() = options;
});
/* Visualization options */
egui::CollapsingHeader::new(RichText::new("Rendering").font(HEADING_FONT))
.show(ui, |ui|
{
egui::Grid::new("render_select_grid").num_columns(2).show(ui, |ui| {
// Camera
ui.label(RichText::new("Camera").font(MAIN_FONT));
let combo_width = ui.available_width().min(MAX_SPAN_WIDTH);
let Ok(enumerated) = camera.type_.try_into() else {
// Unknown camera type - skip the camera row rather than panic.
ui.label(format!("Unknown camera type {}", camera.type_));
ui.end_row();
return;
};
let enumerated: MjtCamera = enumerated;
let lock = shared_viewer_state.lock_unpoison();
let model = lock.data_passive.model();
let mut camera_choice = match enumerated {
MjtCamera::mjCAMERA_FIXED => self.camera_names[camera.fixedcamid as usize].to_string(),
MjtCamera::mjCAMERA_TRACKING => {
let bid = camera.trackbodyid as usize;
if let Some(name) = model.id_to_name(MjtObj::mjOBJ_BODY, bid) {
format!("Tracking: {}", name)
} else {
format!("Tracking: Body {}", bid)
}
},
MjtCamera::mjCAMERA_FREE => "Free".to_string(),
MjtCamera::mjCAMERA_USER => "User".to_string(),
};
drop(lock);
egui::ComboBox::from_id_salt("camera_combo")
.selected_text(&camera_choice)
.width(combo_width)
.show_ui(ui, |ui| {
if ui.selectable_value(&mut camera_choice, "Free".to_string(), "Free").clicked() {
camera.free();
}
// Button to open tracking modal
if ui.button("Track").clicked() {
self.show_tracking_modal = true;
}
// Separator for fixed cameras
for (pos, name) in self.camera_names.iter().enumerate() {
if ui.selectable_value(&mut camera_choice, name.to_string(), name).clicked() {
*camera = MjvCamera::new_fixed(pos);
}
}
});
// Apply selected body if one was selected in the modal
if let Some(body_id) = self.tracking_selected_body.take() {
camera.track(body_id);
}
ui.end_row();
// Label
ui.label(RichText::new("Label").font(MAIN_FONT));
let mut current_lbl_ty = LABEL_TYPE_MAP[options.label as usize];
egui::ComboBox::from_id_salt("label_combo")
.selected_text(current_lbl_ty)
.width(combo_width)
.show_ui(ui, |ui| {
for (label_type_i, label_type) in LABEL_TYPE_MAP.iter().enumerate() {
if ui.selectable_value(&mut current_lbl_ty, label_type, *label_type).clicked() {
options.label = label_type_i as i32;
}
}
});
ui.end_row();
// Frame
ui.label(RichText::new("Frame").font(MAIN_FONT));
let mut current_frm_ty = FRAME_TYPE_MAP[options.frame as usize];
egui::ComboBox::from_id_salt("frame_combo")
.selected_text(current_frm_ty)
.width(combo_width)
.show_ui(ui, |ui| {
for (frame_type_i, frame_type) in FRAME_TYPE_MAP.iter().enumerate() {
if ui.selectable_value(&mut current_frm_ty, frame_type, *frame_type).clicked() {
options.frame = frame_type_i as i32;
}
}
});
ui.end_row();
});
ui.add_space(5.0);
// Copy camera state to clipboard as XML
if ui.add(egui::Button::new(
RichText::new("Print camera").font(MAIN_FONT)
).corner_radius(BUTTON_ROUNDING)).clicked() {
let gl_cams = scene.camera();
let fwd = gl_cams[0].forward;
let up = gl_cams[0].up;
// right = forward x up
let right = [
fwd[1] * up[2] - fwd[2] * up[1],
fwd[2] * up[0] - fwd[0] * up[2],
fwd[0] * up[1] - fwd[1] * up[0],
];
// Average position of left and right eye cameras
let pos = [
(gl_cams[0].pos[0] + gl_cams[1].pos[0]) / 2.0,
(gl_cams[0].pos[1] + gl_cams[1].pos[1]) / 2.0,
(gl_cams[0].pos[2] + gl_cams[1].pos[2]) / 2.0,
];
println!(
"<camera pos=\"{:.3} {:.3} {:.3}\" \
xyaxes=\"{:.3} {:.3} {:.3} {:.3} {:.3} {:.3}\"/>",
pos[0], pos[1], pos[2],
right[0], right[1], right[2],
up[0], up[1], up[2]
);
// TODO in the future, when
// clipboard copying feature doesn't crash:
// ctx.copy_text(xml);
// Until then ^^^.
}
// Screenshot
ui.collapsing(RichText::new("Screenshot").font(MAIN_FONT), |ui| {
if ui.add(egui::Button::new(
RichText::new("Screenshot").font(MAIN_FONT)
).corner_radius(BUTTON_ROUNDING)).clicked() {
self.events.push_back(UiEvent::Screenshot {
viewport_only: self.screenshot_viewport_only,
depth: self.screenshot_depth
});
}
ui.checkbox(
&mut self.screenshot_viewport_only,
RichText::new("Viewport only").font(MAIN_FONT)
);
ui.checkbox(
&mut self.screenshot_depth,
RichText::new("Depth").font(MAIN_FONT)
);
});
ui.collapsing(RichText::new("Elements").font(MAIN_FONT), |ui| {
ui.horizontal_wrapped(|ui| {
for (flag, (enabled, flag_name)) in options.flags.iter_mut().zip(VIS_OPT_MAP).enumerate() {
ui.toggle_value(cast_mut_info!(enabled, flag), flag_name);
}
});
ui.separator();
egui::Grid::new("tree_flex_slide").show(ui, |ui| {
ui.label("Tree depth");
ui.add(egui::Slider::new(&mut options.bvh_depth, 0..=20));
ui.end_row();
ui.label("Flex layer");
ui.add(egui::Slider::new(&mut options.flex_layer, 0..=10));
});
});
ui.collapsing(RichText::new("OpenGL effects").font(MAIN_FONT), |ui| {
ui.horizontal_wrapped(|ui| {
for (flag, (enabled, flag_name)) in scene.flags_mut().iter_mut().zip(GL_EFFECT_MAP).enumerate() {
ui.toggle_value(
cast_mut_info!(enabled, flag),
flag_name
);
}
});
});
});
/* Visualization */
egui::CollapsingHeader::new(RichText::new("Visualization").font(HEADING_FONT))
.show(ui, |ui|
{
let (stat_is_editable, vis_is_editable, mut vis, mut stat) = {
let state = shared_viewer_state.lock_unpoison();
(
state.last_stat_sync_time().elapsed() < PHYSICS_SYNC_TIMEOUT,
state.last_vis_sync_time().elapsed() < PHYSICS_SYNC_TIMEOUT,
state.data_passive.model_vis().clone(),
state.data_passive.model_stat().clone(),
)
};
if !vis_is_editable {
ui.colored_label(egui::Color32::YELLOW, MODEL_VIS_SYNC_WARNING);
}
if !stat_is_editable {
ui.colored_label(egui::Color32::YELLOW, MODEL_STAT_SYNC_WARNING);
}
// Headlight
ui.collapsing(RichText::new("Headlight").font(MAIN_FONT), |ui| {
egui::Grid::new("headlight_grid").num_columns(2).show(ui, |ui| {
ui.label("Active");
ui.horizontal_top(|ui| {
let mut active_bool = vis.headlight.active != 0;
if ui.checkbox(&mut active_bool, "").changed() {
vis.headlight.active = if active_bool { 1 } else { 0 };
}
});
ui.end_row();
ui.add(RowArray::new("Ambient", &mut vis.headlight.ambient, 1e-3));
ui.end_row();
ui.add(RowArray::new("Diffuse", &mut vis.headlight.diffuse, 1e-3));
ui.end_row();
ui.add(RowArray::new("Specular", &mut vis.headlight.specular, 1e-3));
ui.end_row();
});
});
// Free Camera
ui.collapsing(RichText::new("Free Camera").font(MAIN_FONT), |ui| {
egui::Grid::new("camera_grid").num_columns(2).show(ui, |ui| {
ui.label("Orthographic");
ui.horizontal_top(|ui| {
let mut ortho_bool = vis.global.orthographic != 0;
if ui.checkbox(&mut ortho_bool, "").changed() {
vis.global.orthographic = if ortho_bool { 1 } else { 0 };
}
});
ui.end_row();
ui.add(
RowScalar::new("Field of view", &mut vis.global.fovy, 1e-2)
.range(5.0..=175.0)
);
ui.end_row();
ui.add(RowArray::new("Center", &mut stat.center, 1e-3));
ui.end_row();
ui.add(RowScalar::new("Azimuth", &mut vis.global.azimuth, 1e-2));
ui.end_row();
ui.add(RowScalar::new("Elevation", &mut vis.global.elevation, 1e-2));
ui.end_row();
if ui.button("Align").clicked() {
self.events.push_back(UiEvent::AlignCamera);
}
ui.end_row();
});
});
// Global
ui.collapsing(RichText::new("Global").font(MAIN_FONT), |ui| {
egui::Grid::new("global_grid").num_columns(2).show(ui, |ui| {
ui.add(
RowScalar::new("Extent", &mut stat.extent, 1e-3)
.range(0.001..=f64::INFINITY)
);
ui.end_row();
ui.label("Inertia Geom");
ui.horizontal_top(|ui| {
let combo_width = ui.available_width().min(MAX_SPAN_WIDTH);
let mut inertia_choice = if vis.global.ellipsoidinertia == 0 { "Box" } else { "Ellipsoid" };
egui::ComboBox::from_id_salt("inertia_geom_combo")
.selected_text(inertia_choice)
.width(combo_width)
.show_ui(ui, |ui| {
ui.selectable_value(&mut inertia_choice, "Box", "Box");
ui.selectable_value(&mut inertia_choice, "Ellipsoid", "Ellipsoid");
});
vis.global.ellipsoidinertia = if inertia_choice == "Box" { 0 } else { 1 };
});
ui.end_row();
ui.label("BVH active");
ui.horizontal_top(|ui| {
let mut bvh_bool = vis.global.bvactive != 0;
if ui.checkbox(&mut bvh_bool, "").changed() {
vis.global.bvactive = if bvh_bool { 1 } else { 0 };
}
});
ui.end_row();
});
});
// Map
ui.collapsing(RichText::new("Map").font(MAIN_FONT), |ui| {
egui::Grid::new("map_grid").num_columns(2).show(ui, |ui| {
ui.add(
RowScalar::new("Stiffness", &mut vis.map.stiffness, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Rot stiffness", &mut vis.map.stiffnessrot, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Force", &mut vis.map.force, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Torque", &mut vis.map.torque, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Alpha", &mut vis.map.alpha, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowScalar::new("Fog start", &mut vis.map.fogstart, 1e-3)
.range(0.0..=(vis.map.fogend - RANGE_PRECISION_TOLERANCE).max(0.0))
);
ui.end_row();
ui.add(
RowScalar::new("Fog end", &mut vis.map.fogend, 1e-3)
.range((vis.map.fogstart + RANGE_PRECISION_TOLERANCE)..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Z near", &mut vis.map.znear, 1e-3)
.range(0.001..=(vis.map.zfar - RANGE_PRECISION_TOLERANCE))
);
ui.end_row();
ui.add(
RowScalar::new("Z far", &mut vis.map.zfar, 1e-3)
.range((vis.map.znear + RANGE_PRECISION_TOLERANCE)..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Haze", &mut vis.map.haze, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowScalar::new("Shadow clip", &mut vis.map.shadowclip, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Shadow scale", &mut vis.map.shadowscale, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Actuator tendon", &mut vis.map.actuatortendon, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
});
});
// Scale
ui.collapsing(RichText::new("Scale").font(MAIN_FONT), |ui| {
egui::Grid::new("scale_grid").num_columns(2).show(ui, |ui| {
ui.add(
RowScalar::new("Force width", &mut vis.scale.forcewidth, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Contact width", &mut vis.scale.contactwidth, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Contact height", &mut vis.scale.contactheight, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Connect", &mut vis.scale.connect, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("COM", &mut vis.scale.com, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Camera", &mut vis.scale.camera, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Light", &mut vis.scale.light, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Select point", &mut vis.scale.selectpoint, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Joint length", &mut vis.scale.jointlength, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Joint width", &mut vis.scale.jointwidth, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Actuator length", &mut vis.scale.actuatorlength, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Actuator width", &mut vis.scale.actuatorwidth, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Frame length", &mut vis.scale.framelength, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Frame width", &mut vis.scale.framewidth, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Constraint", &mut vis.scale.constraint, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Slider crank", &mut vis.scale.slidercrank, 1e-3)
.range(0.0..=f32::INFINITY)
);
ui.end_row();
ui.add(
RowScalar::new("Frustum", &mut vis.scale.frustum, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
});
});
// RGBA
ui.collapsing(RichText::new("RGBA").font(MAIN_FONT), |ui| {
egui::Grid::new("rgba_grid").num_columns(2).show(ui, |ui| {
ui.add(
RowArray::new("Fog", &mut vis.rgba.fog, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Haze", &mut vis.rgba.haze, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Force", &mut vis.rgba.force, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Inertia", &mut vis.rgba.inertia, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Joint", &mut vis.rgba.joint, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Actuator", &mut vis.rgba.actuator, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Actuator negative", &mut vis.rgba.actuatornegative, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Actuator positive", &mut vis.rgba.actuatorpositive, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("COM", &mut vis.rgba.com, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Camera", &mut vis.rgba.camera, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Light", &mut vis.rgba.light, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Select point", &mut vis.rgba.selectpoint, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Connect", &mut vis.rgba.connect, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Contact point", &mut vis.rgba.contactpoint, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Contact force", &mut vis.rgba.contactforce, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Contact friction", &mut vis.rgba.contactfriction, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Contact torque", &mut vis.rgba.contacttorque, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Contact gap", &mut vis.rgba.contactgap, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Rangefinder", &mut vis.rgba.rangefinder, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Constraint", &mut vis.rgba.constraint, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Slider crank", &mut vis.rgba.slidercrank, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Crank broken", &mut vis.rgba.crankbroken, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("Frustum", &mut vis.rgba.frustum, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("BV", &mut vis.rgba.bv, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
ui.add(
RowArray::new("BV active", &mut vis.rgba.bvactive, 1e-3)
.range(0.0..=1.0)
);
ui.end_row();
});
});
// Write modified vis and stat back to model
{
let mut lock = shared_viewer_state.lock_unpoison();
*lock.data_passive.model_vis_mut() = vis;
*lock.data_passive.model_stat_mut() = stat;
}
});
// Make the scroll bars span to the edges of the sidebar.
ui.take_available_space();
});
// Panel toggle info
ui.with_layout(egui::Layout::bottom_up(egui::Align::Center), |ui| {
ui.add_space(HEADING_POST_SPACE);
ui.heading("Toggle: X");
});
// Make the panel track its width on resize
left = ui.max_rect().max.x + SIDE_PANEL_PAD;
});
}
/* Windows */
// Controls window
egui::Window::new("Actuator")
.scroll(true)
.open(&mut self.actuator_window)
.show(ctx, |ui|
{
let mut lock = shared_viewer_state.lock_unpoison();
let ctrl_mut = lock.data_passive.ctrl_mut();
egui::Grid::new("ctrl_grid").show(ui, |ui| {
debug_assert_eq!(
self.actuator_display_info.len(), ctrl_mut.len(),
"actuator names don't match num of actuators in model. This is a bug!"
);
for ((name, limited, range), ctrl) in self.actuator_display_info.iter()
.zip(ctrl_mut.iter_mut())
{
ui.label(RichText::new(name).font(MAIN_FONT));
let range_inc = if *limited {
range[0]..=range[1]
} else { -1.0..=1.0 };
ui.add(
egui::Slider::new(ctrl, range_inc)
.update_while_editing(false)
);
ui.end_row();
}
});
// Clear all actuator controls by setting them to 0
if ui.button(RichText::new("Clear").font(MAIN_FONT)).clicked() {
ctrl_mut.fill(0.0);
}
});
// Joints window
egui::Window::new("Joint")
.scroll(true)
.open(&mut self.joint_window)
.show(ctx, |ui|
{
egui::Grid::new("joint_grid").show(ui, |ui| {
let lock = shared_viewer_state.lock_unpoison();
let qpos = lock.data_passive.qpos();
for (name, limited, range, qpos_adr) in &self.joint_display_info
{
ui.label(RichText::new(name).font(MAIN_FONT));
let mut value = qpos[*qpos_adr];
ui.add_enabled(false, egui::DragValue::new(&mut value));
if *limited {
let [low, high] = *range;
let value_scaled = ((value - low) / (high - low)).clamp(0.0, 1.0);
ui.add(egui::ProgressBar::new(value_scaled as f32));
}
else {
ui.label("no limit");
}
ui.end_row();
}
});
});
// Equalities window
egui::Window::new("Equality")
.scroll(true)
.open(&mut self.equality_window)
.show(ctx, |ui|
{
ui.horizontal_wrapped(|ui| {
let data = &mut shared_viewer_state.lock_unpoison().data_passive;
debug_assert_eq!(
self.equality_names.len(), data.eq_active_mut().len(),
"equality names length don't match the number of equalities found in model. This is a bug!"
);
for (equality_name, active) in self.equality_names.iter()
.zip(data.eq_active_mut())
{
ui.toggle_value(active, RichText::new(equality_name).font(MAIN_FONT));
}
});
});
egui::Window::new("Group")
.open(&mut self.group_window)
.show(ctx, |ui|
{
egui::Grid::new("group_grid").show(ui, |ui| {
for i in 0..mjNGROUP as usize {
ui.toggle_value(cast_mut_info!(&mut options.geomgroup[i], i), format!("Geom {i}"));
ui.toggle_value(cast_mut_info!(&mut options.sitegroup[i], i), format!("Site {i}"));
ui.toggle_value(cast_mut_info!(&mut options.jointgroup[i], i), format!("Joint {i}"));
ui.toggle_value(cast_mut_info!(&mut options.tendongroup[i], i), format!("Tendon {i}"));
ui.toggle_value(cast_mut_info!(&mut options.actuatorgroup[i], i), format!("Actuator {i}"));
ui.toggle_value(cast_mut_info!(&mut options.flexgroup[i], i), format!("Flex {i}"));
ui.toggle_value(cast_mut_info!(&mut options.skingroup[i], i), format!("Skin {i}"));
ui.end_row();
}
});
});
/* Camera Tracking Modal */
if self.show_tracking_modal {
let modal = egui::Modal::new(Id::new("select_body_tracking"))
.show(ctx, |ui|
{
ui.heading("Select the body to track");
ui.separator();
egui::ScrollArea::vertical()
.max_height(CAMERA_MODAL_MAX_HEIGHT)
.show(ui, |ui| {
let lock = shared_viewer_state.lock_unpoison();
let model = lock.data_passive.model();
let nbody = model.nbody();
egui::Grid::new("body_grid")
.num_columns(CAMERA_MODAL_BUTTONS_PER_ROW)
.show(ui, |ui| {
for body_id in 0..nbody as usize {
let body_name = if let Some(name) = model.id_to_name(MjtObj::mjOBJ_BODY, body_id) {
name.to_string()
} else {
format!("Body {}", body_id)
};
let (rect, response) = ui.allocate_exact_size(CAMERA_MODAL_CELL_SIZE, egui::Sense::click());
if response.clicked() {
self.tracking_selected_body = Some(body_id);
ui.close();
}
let button_color = if response.hovered() {
egui::Color32::from_gray(CAMERA_MODAL_BUTTON_COLOR_HOVERED)
} else {
egui::Color32::from_gray(CAMERA_MODAL_BUTTON_COLOR_DEFAULT)
};
ui.painter().rect_filled(rect, CAMERA_MODAL_BUTTON_ROUNDING, button_color);
ui.painter().with_clip_rect(rect).text(
rect.center(),
egui::Align2::CENTER_CENTER,
&body_name,
MAIN_FONT,
egui::Color32::WHITE,
);
if response.hovered() {
response.on_hover_text(&body_name);
}
if (body_id + 1) % CAMERA_MODAL_BUTTONS_PER_ROW == 0 {
ui.end_row();
}
}
});
});
ui.separator();
if ui.button(RichText::new("Cancel").font(MAIN_FONT)).clicked() {
ui.close();
}
});
if modal.should_close() {
self.show_tracking_modal = false;
}
}
/* User-defined UI callbacks */
// Callbacks that receive the egui context and MjData passive instance
for callback in self.user_ui_callbacks.iter_mut() {
callback(ctx, &mut shared_viewer_state.lock_unpoison().data_passive);
}
// Callbacks that only receive the egui context
for callback in self.user_ui_callbacks_detached.iter_mut() {
callback(ctx);
}
});
// Prevent window interactions when covering egui widgets
self.state.handle_platform_output(window, full_output.platform_output);
// Tessellate
let pixels_per_point = full_output.pixels_per_point;
let textures_delta = &full_output.textures_delta;
let clipped_primitives = self.egui_ctx.tessellate(full_output.shapes, pixels_per_point);
// Paint the menu
self.painter.paint_and_update_textures(
window.inner_size().into(),
pixels_per_point,
&clipped_primitives,
textures_delta
);
left * pixels_per_point
}
/// Checks whether the UI is focused (e.g., typing).
pub(crate) fn focused(&self) -> bool {
self.egui_ctx.memory(|ui| ui.focused().is_some())
}
/// Checks whether the mouse is over the UI.
pub(crate) fn covered(&self) -> bool {
self.egui_ctx.is_pointer_over_area()
}
/// Checks whether the UI is currently being dragged.
pub(crate) fn dragged(&self) -> bool {
self.egui_ctx.dragged_id().is_some()
}
/// Prepares OpenGL for drawing 2D overlays.
pub(crate) fn init_2d(&self) {
let gl = &self.gl;
// SAFETY: the GL context is current (made current by the render loop before this call).
unsafe {
gl.disable(glow::DEPTH_TEST);
gl.disable(glow::CULL_FACE);
gl.disable(glow::BLEND);
gl.blend_func(glow::SRC_ALPHA, glow::ONE_MINUS_SRC_ALPHA);
gl.polygon_mode(glow::FRONT_AND_BACK, glow::FILL);
}
}
/// Resets OpenGL state. This is needed for MuJoCo's renderer.
pub(crate) fn reset(&mut self) {
let gl = &self.gl;
// SAFETY: the GL context is current; unbinding programs and buffers is always safe
// as long as no draw calls are in flight, which is guaranteed by the render loop.
unsafe {
// Disable shaders
gl.use_program(None);
// Unbind buffers
gl.bind_vertex_array(None);
gl.bind_buffer(glow::ARRAY_BUFFER, None);
gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, None);
gl.bind_framebuffer(glow::FRAMEBUFFER, None);
}
}
/// Drains events from queue. If no event is queued, [`None`] is returned.
pub(crate) fn drain_events(&mut self) -> Option<UiEvent> {
self.events.pop_front()
}
/// Adds a user-defined UI callback that will be invoked during UI rendering.
/// The callback receives the egui context and can be used to create custom windows,
/// panels, or other UI elements.
pub(crate) fn add_ui_callback<F>(&mut self, callback: F)
where
F: FnMut(&egui::Context, &mut MjData<Box<MjModel>>) + 'static
{
self.user_ui_callbacks.push(Box::new(callback));
}
/// Adds a detached user-defined UI callback that will be invoked during UI rendering.
/// Unlike [`ViewerUI::add_ui_callback`], this method does not pass in the passive [`MjData`]
/// instance, located in the shared state, thus avoiding mutex locking when not necessary.
pub(crate) fn add_ui_callback_detached<F>(&mut self, callback: F)
where
F: FnMut(&egui::Context) + 'static
{
self.user_ui_callbacks_detached.push(Box::new(callback));
}
/// Release OpenGL resources held by the egui painter.
/// Must be called while the GL context is still current.
pub(crate) fn destroy_gl(&mut self) {
self.painter.destroy();
}
}
/// Implement an empty shell to support use in [`MjViewer`](super::MjViewer).
impl Debug for ViewerUI {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ViewerUI {{ .. }}")
}
}
/// Enum representing UI events raised from the interface.
pub(crate) enum UiEvent {
Close,
Fullscreen,
ResetSimulation,
AlignCamera,
VSyncToggle,
Screenshot { viewport_only: bool, depth: bool }
}
// Extra widgets
#[must_use = "use ui.add( row_scalar )"]
struct RowScalar<'t, Num: egui::emath::Numeric> {
name: egui::WidgetText,
target: &'t mut Num,
increment: f64,
maybe_range: Option<std::ops::RangeInclusive<Num>>
}
impl<'t, Num: egui::emath::Numeric> RowScalar<'t, Num> {
fn new(name: impl Into<egui::WidgetText>, target: &'t mut Num, increment: f64) -> Self {
Self { name: name.into(), target, increment, maybe_range: None }
}
fn range(mut self, range: std::ops::RangeInclusive<Num>) -> Self {
self.maybe_range = Some(range);
self
}
}
impl<'t, Num: egui::emath::Numeric> egui::Widget for RowScalar<'t, Num> {
fn ui(self, ui: &mut egui::Ui) -> egui::Response {
let mut drag = egui::DragValue::new(self.target)
.speed(self.increment);
if let Some(range) = self.maybe_range {
drag = drag.range(range);
}
ui.label(self.name);
ui.horizontal_top(|ui| {
ui.add_sized(
[ui.available_width().min(MAX_SPAN_WIDTH), ui.spacing().interact_size.y],
drag
)
}).inner
}
}
struct RowArray<'t, Num: egui::emath::Numeric> {
name: egui::WidgetText,
values: &'t mut [Num],
increment: f64,
maybe_range: Option<std::ops::RangeInclusive<Num>>,
}
impl<'t, Num: egui::emath::Numeric> RowArray<'t, Num> {
fn new(name: impl Into<egui::WidgetText>, values: &'t mut [Num], increment: f64) -> Self {
Self { name: name.into(), values, increment, maybe_range: None }
}
fn range(mut self, range: std::ops::RangeInclusive<Num>) -> Self {
self.maybe_range = Some(range);
self
}
}
impl<'t, Num: egui::emath::Numeric> egui::Widget for RowArray<'t, Num> {
fn ui(self, ui: &mut egui::Ui) -> egui::Response {
ui.label(self.name);
let interact_height = ui.spacing().interact_size.y;
let available_width = ui.available_width().min(MAX_SPAN_WIDTH);
let values_len = self.values.len();
let x_spacing = ui.spacing_mut().item_spacing.y;
ui.spacing_mut().item_spacing.x = x_spacing;
let per_element_width = (available_width - x_spacing * (values_len - 1) as f32) / values_len as f32;
let response = ui.horizontal_top(|ui| {
let mut last_response = None;
for value in self.values.iter_mut() {
let mut drag = egui::DragValue::new(value)
.speed(self.increment);
if let Some(range) = &self.maybe_range {
drag = drag.range(range.clone());
}
last_response = Some(ui.add_sized(
[per_element_width, interact_height],
drag
));
}
last_response.unwrap_or_else(|| ui.label(""))
});
response.response
}
}