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
//! Module related to implementation of the [`MjRenderer`].
use crate::wrappers::mj_visualization::MjvScene;
use crate::wrappers::mj_rendering::MjrContext;
#[cfg(target_os = "linux")]
use crate::renderer::egl::GlStateEgl;
use crate::vis_common::{sync_geoms, flip_image_vertically, write_png};
use crate::builder_setters;
use crate::prelude::*;
use bitflags::bitflags;
use std::io::{self, BufWriter, Write};
use std::fmt::Display;
use std::error::Error;
use std::num::NonZero;
use std::ops::Deref;
use std::path::Path;
use std::fs::File;
/// Exported `png` crate for convenience.
pub use png;
/// Scale factor for converting normalized [0..1] depth to u16.
const DEPTH_U16_SCALE: f32 = u16::MAX as f32;
#[cfg(feature = "renderer-winit-fallback")]
mod universal;
#[cfg(feature = "renderer-winit-fallback")]
use universal::GlStateWinit;
#[cfg(target_os = "linux")]
mod egl;
const EXTRA_INTERNAL_VISUAL_GEOMS: u32 = 100;
/// Compute the depth near/far clip planes in metres from the model.
fn model_near_far(model: &MjModel) -> (f32, f32) {
let map = &model.vis().map;
let extent = model.stat().extent as f32;
(map.znear * extent, map.zfar * extent)
}
/// GlState enum wrapper. By default, headless implementation will be used
/// when supported. Only on failure will an invisible winit window be used.
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub(crate) enum GlState {
#[cfg(feature = "renderer-winit-fallback")] Winit(GlStateWinit),
#[cfg(target_os = "linux")] Egl(egl::GlStateEgl),
}
impl GlState {
/// Creates a new [`GlState`], which by default tries to use
/// an offscreen implementation. As a fallback, winit will be used.
pub(crate) fn new(width: NonZero<u32>, height: NonZero<u32>) -> Result<Self, RendererError> {
#[cfg(target_os = "linux")]
#[allow(unused_variables)]
let egl_err = match GlStateEgl::new(width, height) {
Ok(egl_state) => return Ok(Self::Egl(egl_state)),
Err(e) => e,
};
#[cfg(feature = "renderer-winit-fallback")]
match GlStateWinit::new(width, height) {
Ok(winit_state) => return Ok(Self::Winit(winit_state)),
#[cfg(not(target_os = "linux"))]
Err(e) => {
return Err(e);
},
#[cfg(target_os = "linux")]
_ => {}
}
#[cfg(target_os = "linux")]
Err(RendererError::GlutinError(egl_err))
}
/// Makes the internal OpenGL context current for the calling thread.
pub(crate) fn make_current(&self) -> glutin::error::Result<()> {
match self {
#[cfg(target_os = "linux")]
Self::Egl(egl_state) => egl_state.make_current(),
#[cfg(feature = "renderer-winit-fallback")]
Self::Winit(winit_state) => winit_state.make_current()
}
}
}
/// A builder for [`MjRenderer`].
#[derive(Debug)]
pub struct MjRendererBuilder {
width: u32,
height: u32,
num_visual_internal_geom: u32,
num_visual_user_geom: u32,
rgb: bool,
depth: bool,
png_compression: png::Compression,
font_scale: MjtFontScale,
camera: MjvCamera,
opts: MjvOption,
}
impl MjRendererBuilder {
/// Create a builder with default configuration.
/// Defaults are:
/// - `width` and `height`: use offwidth and offheight of MuJoCo's visual/global settings from the model,
/// - `num_visual_internal_geom`: 100,
/// - `num_visual_user_geom`: 0,
/// - `rgb`: true,
/// - `depth`: false,
/// - `png_compression`: [`png::Compression::NoCompression`] (fastest, largest files),
/// - `font_scale`: [`MjtFontScale::mjFONTSCALE_100`],
/// - `camera`: [`MjvCamera::default()`] (MuJoCo's `mjv_defaultCamera`),
/// - `opts`: [`MjvOption::default()`] (MuJoCo's `mjv_defaultOption`).
pub fn new() -> Self {
Self {
width: 0, height: 0,
num_visual_internal_geom: EXTRA_INTERNAL_VISUAL_GEOMS, num_visual_user_geom: 0,
rgb: true, depth: false, png_compression: png::Compression::NoCompression,
font_scale: MjtFontScale::mjFONTSCALE_100,
camera: MjvCamera::default(), opts: MjvOption::default(),
}
}
builder_setters! {
width: u32; "
image width.
<div class=\"warning\">
The width must be less or equal to the offscreen buffer width,
which can be configured at the top of the model's XML like so:
```xml
<visual>
<global offwidth=\"1920\" .../>
</visual>
```
</div>";
height: u32; "\
image height.
<div class=\"warning\">
The height must be less or equal to the offscreen buffer height,
which can be configured at the top of the model's XML like so:
```xml
<visual>
<global offheight=\"1080\" .../>
</visual>
```
</div>";
num_visual_internal_geom: u32; "\
maximum number of additional visual-only internal geoms to allocate for.
Note that the total number of geoms in the internal scene will be
`model.ngeom` + `num_visual_internal_geom` + `num_visual_user_geom`.";
num_visual_user_geom: u32; "maximum number of additional visual-only user geoms (drawn by the user).";
rgb: bool; "RGB rendering enabled (true) or disabled (false).";
depth: bool; "depth rendering enabled (true) or disabled (false).";
png_compression: png::Compression; "PNG compression level used by [`MjRenderer::save_rgb`] and [`MjRenderer::save_depth`].";
font_scale: MjtFontScale; "font scale of drawn text (with [MjrContext]).";
camera: MjvCamera; "camera used for drawing.";
opts: MjvOption; "visualization options.";
}
/// Builds a [`MjRenderer`].
/// # Returns
/// On success, returns [`Ok`] variant containing the [`MjRenderer`].
/// # Errors
/// - [`RendererError::ZeroDimension`] if the width or height is zero.
/// - [`RendererError::GlutinError`] if OpenGL initialization fails.
/// - [`RendererError::EventLoopError`] if the event loop fails to initialize
/// (feature `renderer-winit-fallback`).
/// - [`RendererError::GlInitFailed`] if the fallback window initialization fails
/// (feature `renderer-winit-fallback`).
pub fn build<M: Deref<Target = MjModel>>(self, model: M) -> Result<MjRenderer, RendererError> {
// Assume model's maximum should be used
let mut height = self.height;
let mut width = self.width;
if width == 0 && height == 0 {
let global = &model.vis().global;
height = global.offheight as u32;
width = global.offwidth as u32;
}
let gl_state = GlState::new(
NonZero::new(width).ok_or(RendererError::ZeroDimension)?,
NonZero::new(height).ok_or(RendererError::ZeroDimension)?,
)?;
// Initialize the rendering context to render to the offscreen buffer.
// SAFETY: gl_state was just created above, establishing a current GL context.
let mut context = unsafe { MjrContext::new(&model) };
context.offscreen();
context.change_font(self.font_scale);
let extra_geom = self.num_visual_internal_geom as usize + self.num_visual_user_geom as usize;
let (near, far) = model_near_far(&model);
// The 3D scene for visualization
let scene = MjvScene::new(
&*model,
model.ffi().ngeom as usize + extra_geom
);
let user_scene = MjvScene::new(
&*model,
self.num_visual_user_geom as usize
);
// Construct the renderer and create allocated buffers.
let renderer = MjRenderer {
scene, user_scene, context, camera: self.camera, option: self.opts,
flags: RendererFlags::empty(), rgb: None, depth: None,
width: width as usize, height: height as usize, gl_state,
png_compression: self.png_compression, font_scale: self.font_scale,
near, far, extra_geom,
} // These require special care
.with_rgb_rendering(self.rgb)
.with_depth_rendering(self.depth);
Ok(renderer)
}
}
/// Delegates to [`MjRendererBuilder::new`].
impl Default for MjRendererBuilder {
fn default() -> Self {
Self::new()
}
}
/// A renderer for rendering 3D scenes.
/// By default, RGB rendering is enabled and depth rendering is disabled.
#[derive(Debug)]
pub struct MjRenderer {
scene: MjvScene,
user_scene: MjvScene,
context: MjrContext,
/* OpenGL */
gl_state: GlState,
/* Configuration */
camera: MjvCamera,
option: MjvOption,
flags: RendererFlags,
png_compression: png::Compression,
font_scale: MjtFontScale,
/* Cached from the current model */
// Depth near/far clip planes in metres, derived from model.vis().map and model.stat().
near: f32,
far: f32,
// Scene capacity headroom beyond ngeom: preserved across model switches.
extra_geom: usize,
/* Storage */
// Use Box to allow less space to be used
// when rgb or depth rendering is disabled
rgb: Option<Box<[u8]>>,
depth: Option<Box<[f32]>>,
width: usize,
height: usize,
}
impl MjRenderer {
/// Construct a new renderer.
/// The `max_user_geom` parameter
/// defines how much space will be allocated for additional, user-defined visual-only geoms.
/// It can thus be set to 0 if no additional geoms will be drawn by the user.
/// # Scene allocation
/// The renderer uses two scenes:
/// - the internal scene: used by the renderer to draw the model's state.
/// - the user scene: used by the user to add additional geoms to the internal scene
///
/// The **internal scene** allocates the amount of space needed to fit every pre-existing
/// model geom + user visual-only geoms + additional visual-only geoms that aren't from the user (e.g., tendons).
/// By default, the renderer reserves 100 extra geom slots for drawing the additional visual-only geoms.
/// If that is not enough or it is too much, you can construct [`MjRenderer`] via its builder
/// ([`MjRenderer::builder`]), which allows more configuration.
///
/// <div class="warning">
///
/// Parameters `width` and `height` must be less or equal to the offscreen buffer size,
/// which can be configured at the top of the model's XML like so:
///
/// ```xml
/// <visual>
/// <global offwidth="1920" offheight="1080"/>
/// </visual>
/// ```
///
/// </div>
/// # Returns
/// On success, returns [`Ok`] variant containing the [`MjRenderer`].
/// # Errors
/// - [`RendererError::ZeroDimension`] if the width or height is zero.
/// - [`RendererError::GlutinError`] if OpenGL initialization fails.
/// - [`RendererError::EventLoopError`] if the event loop fails to initialize
/// (feature `renderer-winit-fallback`).
/// - [`RendererError::GlInitFailed`] if the fallback window initialization fails
/// (feature `renderer-winit-fallback`).
pub fn new<M: Deref<Target = MjModel>>(model: M, width: usize, height: usize, max_user_geom: usize) -> Result<Self, RendererError> {
MjRendererBuilder::new()
.width(width as u32).height(height as u32).num_visual_user_geom(max_user_geom as u32)
.build(model)
}
/// Create a [`MjRendererBuilder`] to configure [`MjRenderer`].
pub fn builder() -> MjRendererBuilder {
MjRendererBuilder::new()
}
/// Return an immutable reference to the internal scene.
pub fn scene(&self) -> &MjvScene {
&self.scene
}
/// Return an immutable reference to a user scene for drawing custom visual-only geoms.
pub fn user_scene(&self) -> &MjvScene {
&self.user_scene
}
/// Return a mutable reference to a user scene for drawing custom visual-only geoms.
pub fn user_scene_mut(&mut self) -> &mut MjvScene {
&mut self.user_scene
}
/// Return an immutable reference to visualization options.
pub fn opts(&self) -> &MjvOption {
&self.option
}
/// Return a mutable reference to visualization options.
pub fn opts_mut(&mut self) -> &mut MjvOption {
&mut self.option
}
/// Return an immutable reference to the camera.
pub fn camera(&self) -> &MjvCamera {
&self.camera
}
/// Return a mutable reference to the camera.
pub fn camera_mut(&mut self) -> &mut MjvCamera {
&mut self.camera
}
/// Check if RGB rendering is enabled.
pub fn rgb_enabled(&self) -> bool {
self.flags.contains(RendererFlags::RENDER_RGB)
}
/// Check if depth rendering is enabled.
pub fn depth_enabled(&self) -> bool {
self.flags.contains(RendererFlags::RENDER_DEPTH)
}
/// Sets the font scale.
///
/// # Errors
/// Returns [`RendererError::GlutinError`] if the OpenGL context cannot be made current.
pub fn set_font_scale(&mut self, font_scale: MjtFontScale) -> Result<(), RendererError> {
self.gl_state.make_current().map_err(RendererError::GlutinError)?;
self.font_scale = font_scale;
self.context.change_font(font_scale);
Ok(())
}
/// Update the visualization options.
pub fn set_opts(&mut self, options: MjvOption) {
self.option = options;
}
/// Set the camera used for rendering.
pub fn set_camera(&mut self, camera: MjvCamera) {
self.camera = camera;
}
/// Enables/disables RGB rendering.
pub fn set_rgb_rendering(&mut self, enable: bool) {
self.flags.set(RendererFlags::RENDER_RGB, enable);
self.rgb = if enable { Some(vec![0; 3 * self.width * self.height].into_boxed_slice()) } else { None } ;
}
/// Enables/disables depth rendering.
pub fn set_depth_rendering(&mut self, enable: bool) {
self.flags.set(RendererFlags::RENDER_DEPTH, enable);
self.depth = if enable { Some(vec![0.0; self.width * self.height].into_boxed_slice()) } else { None } ;
}
/// Sets the font scale. To be used on construction.
///
/// # Errors
/// Returns [`RendererError::GlutinError`] if the OpenGL context cannot be made current.
pub fn with_font_scale(mut self, font_scale: MjtFontScale) -> Result<Self, RendererError> {
self.set_font_scale(font_scale)?;
Ok(self)
}
/// Update the visualization options and return `self`. To be used on construction.
pub fn with_opts(mut self, options: MjvOption) -> Self {
self.set_opts(options);
self
}
/// Set the camera used for rendering. To be used on construction.
pub fn with_camera(mut self, camera: MjvCamera) -> Self {
self.set_camera(camera);
self
}
/// Enables/disables RGB rendering. To be used on construction.
pub fn with_rgb_rendering(mut self, enable: bool) -> Self {
self.set_rgb_rendering(enable);
self
}
/// Enables/disables depth rendering. To be used on construction.
pub fn with_depth_rendering(mut self, enable: bool) -> Self {
self.set_depth_rendering(enable);
self
}
/// Set the PNG compression level used by [`MjRenderer::save_rgb`] and [`MjRenderer::save_depth`].
pub fn set_png_compression(&mut self, compression: png::Compression) {
self.png_compression = compression;
}
/// Set the PNG compression level. To be used on construction.
pub fn with_png_compression(mut self, compression: png::Compression) -> Self {
self.set_png_compression(compression);
self
}
/// Update the scene with new data from data.
/// When `data` was created from a different model than the renderer,
/// the internal scene is automatically recreated for the new model.
///
/// # Errors
/// - [`RendererError::GlutinError`] if the OpenGL context could not be made current
/// (only when the [`MjModel`] in `data` differs from the internal model).
pub fn sync_data<M: Deref<Target = MjModel>>(&mut self, data: &mut MjData<M>) -> Result<(), RendererError> {
if data.model().signature() != self.scene.signature() {
/* Model changed: preserve the extra-geom headroom and user-geom
* capacity, only substitute the per-model ngeom base count. */
// Ensure the GL context is current before dropping old GPU resources
// (MjrContext::drop calls mjr_freeContext) and creating new ones.
self.gl_state.make_current().map_err(RendererError::GlutinError)?;
let user_geom_cap = self.user_scene.maxgeom() as usize;
let new_ngeom = data.model().ffi().ngeom as usize;
self.scene = MjvScene::new(data.model(), new_ngeom + self.extra_geom);
self.user_scene = MjvScene::new(data.model(), user_geom_cap);
(self.near, self.far) = model_near_far(data.model());
// Recreate the rendering context so that GPU resources (textures,
// meshes, heightfields, skins) match the new model.
// SAFETY: the GL context was made current above.
self.context = unsafe { MjrContext::new(data.model()) };
self.context.offscreen();
self.context.change_font(self.font_scale);
}
self.scene.update(data, &self.option, &MjvPerturb::default(), &mut self.camera);
Ok(())
}
/// Update the scene with new data and render it.
///
/// # Panics
/// Panics if syncing the data or performing the render step fails (e.g. the OpenGL
/// context cannot be made current). Use [`MjRenderer::sync_data`] + [`MjRenderer::render`]
/// instead.
#[deprecated(note = "replaced with sync_data + render", since = "3.0.0")]
pub fn sync<M: Deref<Target = MjModel>>(&mut self, data: &mut MjData<M>) {
self.sync_data(data).unwrap();
self.render().unwrap();
}
/// Return a flattened RGB image of the scene.
pub fn rgb_flat(&self) -> Option<&[u8]> {
self.rgb.as_deref()
}
/// Return an RGB image of the scene. This method accepts two generic parameters <WIDTH, HEIGHT>
/// that define the shape of the output slice.
///
/// # Panics
/// - If the image size doesn't match the required dimensions.
/// - If RGB rendering is disabled.
///
/// Use [`MjRenderer::try_rgb`] for a fallible alternative.
pub fn rgb<const WIDTH: usize, const HEIGHT: usize>(&self) -> &[[[u8; 3]; WIDTH]; HEIGHT] {
self.try_rgb::<WIDTH, HEIGHT>().unwrap()
}
/// Fallible version of [`MjRenderer::rgb`].
/// # Returns
/// On success, returns [`Ok`] variant containing the rendered RGB image.
/// # Errors
/// - [`RendererError::DimensionMismatch`] if the image size doesn't match the required dimensions.
/// - [`RendererError::RgbDisabled`] if RGB rendering is disabled.
pub fn try_rgb<const WIDTH: usize, const HEIGHT: usize>(&self) -> Result<&[[[u8; 3]; WIDTH]; HEIGHT], RendererError> {
if let Some(flat) = self.rgb_flat() {
bytemuck::try_from_bytes(flat)
.map_err(|_| RendererError::DimensionMismatch)
}
else {
Err(RendererError::RgbDisabled)
}
}
/// Return a flattened depth image of the scene.
pub fn depth_flat(&self) -> Option<&[f32]> {
self.depth.as_deref()
}
/// Return a depth image of the scene. This method accepts two generic parameters <WIDTH, HEIGHT>
/// that define the shape of the output slice.
///
/// # Panics
/// - If the image size doesn't match the required dimensions.
/// - If depth rendering is disabled.
///
/// Use [`MjRenderer::try_depth`] for a fallible alternative.
pub fn depth<const WIDTH: usize, const HEIGHT: usize>(&self) -> &[[f32; WIDTH]; HEIGHT] {
self.try_depth::<WIDTH, HEIGHT>().unwrap()
}
/// Fallible version of [`MjRenderer::depth`].
/// # Returns
/// On success, returns [`Ok`] variant containing the rendered depth image.
/// # Errors
/// - [`RendererError::DimensionMismatch`] if the image size doesn't match the required dimensions.
/// - [`RendererError::DepthDisabled`] if depth rendering is disabled.
pub fn try_depth<const WIDTH: usize, const HEIGHT: usize>(&self) -> Result<&[[f32; WIDTH]; HEIGHT], RendererError> {
if let Some(flat) = self.depth_flat() {
let bytes: &[u8] = bytemuck::cast_slice(flat);
bytemuck::try_from_bytes(bytes)
.map_err(|_| RendererError::DimensionMismatch)
}
else {
Err(RendererError::DepthDisabled)
}
}
/// Save an RGB image of the scene to a path.
/// # Returns
/// `Ok(())` on success.
/// # Errors
/// - [`RendererError::RgbDisabled`] when RGB rendering is disabled.
/// - [`RendererError::IoError`] if a file I/O operation fails.
pub fn save_rgb<T: AsRef<Path>>(&self, path: T) -> Result<(), RendererError> {
if let Some(rgb) = &self.rgb {
write_png(
path,
rgb,
self.width as u32,
self.height as u32,
png::ColorType::Rgb,
png::BitDepth::Eight,
self.png_compression
)?;
Ok(())
}
else {
Err(RendererError::RgbDisabled)
}
}
/// Save a depth image of the scene to a path. The image is 16-bit PNG, which
/// can be converted into depth (distance) data by dividing the grayscale values by
/// 65535.0 and applying inverse normalization: `depth = min + (grayscale / 65535.0) * (max - min)`.
///
/// If `normalize` is `true`, then the data is normalized with per-frame min-max normalization.
/// When `normalize` is `false`, the depth values are mapped using the model's camera
/// near/far clip planes as the range, providing a fixed (frame-independent) mapping.
///
/// Use of [`MjRenderer::save_depth_raw`] is recommended if performance is critical, as
/// it skips PNG encoding and also saves the true depth values directly.
/// # Returns
/// An [`Ok`]`((min, max))` is returned, where min and max represent the normalization parameters.
/// # Errors
/// - [`RendererError::DepthDisabled`] when depth rendering is disabled.
/// - [`RendererError::IoError`] if a file I/O operation fails.
pub fn save_depth<T: AsRef<Path>>(&self, path: T, normalize: bool) -> Result<(f32, f32), RendererError> {
if let Some(depth) = &self.depth {
let (norm, min, max) =
if normalize {
let max = depth.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
let min = depth.iter().cloned().fold(f32::INFINITY, f32::min);
let range = max - min;
if range == 0.0 {
(vec![0u8; depth.len() * 2].into_boxed_slice(), min, max)
} else {
(depth.iter().flat_map(|&x| (((x - min) / range * DEPTH_U16_SCALE).clamp(0.0, DEPTH_U16_SCALE) as u16).to_be_bytes()).collect::<Box<_>>(), min, max)
}
}
else {
// Use model's camera near/far clip planes as the fixed normalization range.
// After linearization (in render()), depth values are in meters within [near, far].
let near = self.near;
let far = self.far;
(depth.iter().flat_map(|&x| (((x - near) / (far - near) * DEPTH_U16_SCALE).clamp(0.0, DEPTH_U16_SCALE) as u16).to_be_bytes()).collect::<Box<_>>(), near, far)
};
write_png(
path,
&norm,
self.width as u32,
self.height as u32,
png::ColorType::Grayscale,
png::BitDepth::Sixteen,
self.png_compression
)?;
Ok((min, max))
}
else {
Err(RendererError::DepthDisabled)
}
}
/// Save the raw depth data to the `path`. The data is encoded
/// as a sequence of bytes, where groups of four represent a single f32 value
/// in native byte order.
/// # Returns
/// `Ok(())` on success.
/// # Errors
/// - [`RendererError::DepthDisabled`] when depth rendering is disabled.
/// - [`RendererError::IoError`] if a file I/O operation fails.
pub fn save_depth_raw<T: AsRef<Path>>(&self, path: T) -> Result<(), RendererError> {
if let Some(depth) = &self.depth {
let file = File::create(path.as_ref())?;
let mut writer = BufWriter::new(file);
let bytes: &[u8] = bytemuck::cast_slice(depth);
writer.write_all(bytes)?;
Ok(())
}
else {
Err(RendererError::DepthDisabled)
}
}
/// Draws the scene to internal arrays.
/// Use [`MjRenderer::rgb`] or [`MjRenderer::depth`] to obtain the rendered image.
///
/// # Errors
/// - [`RendererError::GlutinError`] if the OpenGL context could not be made current.
/// - [`RendererError::SceneError`] if the user-scene sync overflows the geom buffer
/// or if reading pixels from the framebuffer fails.
pub fn render(&mut self) -> Result<(), RendererError> {
/* Sync user scene geoms into the main scene before rendering */
sync_geoms(&self.user_scene, &mut self.scene).map_err(RendererError::SceneError)?;
self.gl_state.make_current().map_err(RendererError::GlutinError)?;
let vp = MjrRectangle::new(0, 0, self.width as i32, self.height as i32);
self.scene.render(&vp, &self.context);
/* Fully flatten everything */
let flat_rgb = self.rgb.as_deref_mut();
let flat_depth = self.depth.as_deref_mut();
/* Read to whatever is enabled */
self.context.read_pixels(
flat_rgb,
flat_depth,
&vp
).map_err(RendererError::SceneError)?;
/* Flip the read pixels vertically, as OpenGL reads bottom-up */
if let Some(rgb) = self.rgb.as_deref_mut() {
flip_image_vertically(rgb, self.height, self.width * 3);
}
/* Make depth values be the actual distance in meters and flip them vertically */
if let Some(depth) = self.depth.as_deref_mut() {
flip_image_vertically(depth, self.height, self.width);
let near = self.near;
let far = self.far;
for value in depth {
*value = near / (1.0 - *value * (1.0 - near / far));
}
}
Ok(())
}
}
/// Errors that can occur during renderer operations.
#[derive(Debug)]
#[non_exhaustive]
pub enum RendererError {
/// The event loop failed to initialize.
#[cfg(feature = "renderer-winit-fallback")]
EventLoopError(winit::error::EventLoopError),
/// A glutin operation failed.
GlutinError(glutin::error::Error),
/// The supplied width or height was zero; MuJoCo requires positive dimensions.
ZeroDimension,
/// OpenGL / window initialization failed.
#[cfg(feature = "renderer-winit-fallback")]
GlInitFailed(crate::error::GlInitError),
/// RGB rendering was not enabled.
RgbDisabled,
/// Depth rendering was not enabled.
DepthDisabled,
/// The requested `WIDTH`/`HEIGHT` do not match the renderer's dimensions.
DimensionMismatch,
/// An I/O error occurred (e.g. while saving to a file).
IoError(io::Error),
/// A scene operation failed (e.g. user-scene sync overflowed the geom buffer).
SceneError(crate::error::MjSceneError),
}
/// Formats a human-readable description of the renderer error.
impl Display for RendererError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
#[cfg(feature = "renderer-winit-fallback")]
Self::EventLoopError(e) => write!(f, "event loop failed to initialize: {e}"),
Self::GlutinError(e) => write!(f, "glutin error: {e}"),
Self::ZeroDimension => write!(f, "renderer width and height must both be greater than zero"),
#[cfg(feature = "renderer-winit-fallback")]
Self::GlInitFailed(e) => write!(f, "GL initialization failed: {e}"),
Self::RgbDisabled => write!(f, "RGB rendering is not enabled (renderer.with_rgb_rendering(true))"),
Self::DepthDisabled => write!(f, "depth rendering is not enabled (renderer.with_depth_rendering(true))"),
Self::DimensionMismatch => write!(f, "the input width and height don't match the renderer's configuration"),
Self::IoError(e) => write!(f, "I/O error: {e}"),
Self::SceneError(e) => write!(f, "scene error: {e}"),
}
}
}
/// Provides the underlying error source, if any.
impl Error for RendererError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
#[cfg(feature = "renderer-winit-fallback")]
Self::EventLoopError(e) => Some(e),
#[cfg(feature = "renderer-winit-fallback")]
Self::GlInitFailed(e) => Some(e),
Self::GlutinError(e) => Some(e),
Self::IoError(e) => Some(e),
Self::SceneError(e) => Some(e),
_ => None,
}
}
}
/// Converts an [`io::Error`] into [`RendererError::IoError`].
impl From<io::Error> for RendererError {
fn from(e: io::Error) -> Self {
Self::IoError(e)
}
}
/// Converts a [`png::EncodingError`] into [`RendererError::IoError`].
impl From<png::EncodingError> for RendererError {
fn from(e: png::EncodingError) -> Self {
Self::IoError(io::Error::from(e))
}
}
/// Converts an [`MjSceneError`] into [`RendererError::SceneError`].
impl From<crate::error::MjSceneError> for RendererError {
fn from(e: crate::error::MjSceneError) -> Self {
Self::SceneError(e)
}
}
/// Converts a [`GlInitError`] into [`RendererError::GlInitFailed`].
#[cfg(feature = "renderer-winit-fallback")]
impl From<crate::error::GlInitError> for RendererError {
fn from(e: crate::error::GlInitError) -> Self {
Self::GlInitFailed(e)
}
}
bitflags! {
/// Flags that enable features of the renderer.
#[derive(Debug)]
struct RendererFlags: u8 {
const RENDER_RGB = 1 << 0;
const RENDER_DEPTH = 1 << 1;
}
}
/// Ensures the OpenGL context is current before GPU resources are freed.
impl Drop for MjRenderer {
fn drop(&mut self) {
// Ensure the GL context is current before the implicit field drops
// (MjrContext's Drop calls mjr_freeContext which requires an active GL context).
let _ = self.gl_state.make_current();
}
}
/*
** Don't run any tests as OpenGL hates if anything
** runs outside the main thread.
*/
#[cfg(test)]
mod test {
use crate::assert_relative_eq;
use super::*;
const MODEL: &str = stringify!(
<mujoco>
<visual>
<global offwidth="1280" offheight="720"/>
</visual>
<worldbody>
<geom name="floor" type="plane" size="10 10 1" euler="0 0 0"/>
<geom type="box" size="1 10 10" pos="-1 0 0" euler="0 0 0"/>
<camera name="depth_test" euler="90 90 0" pos="2.25 0 1"/>
</worldbody>
</mujoco>
);
/// Depth calculation test.
/// This is only run on Linux due to EGL requirements (winit cannot be used on multiple threads).
#[test]
#[cfg(target_os = "linux")]
fn test_depth() {
let model = MjModel::from_xml_string(MODEL).expect("could not load the model");
let mut data = MjData::new(&model);
data.step();
let mut renderer = MjRenderer::builder()
.rgb(false)
.depth(true)
.camera(MjvCamera::new_fixed(model.name_to_id(MjtObj::mjOBJ_CAMERA, "depth_test").unwrap()))
.build(&model)
.unwrap();
renderer.sync_data(&mut data).unwrap();
renderer.render().unwrap();
let min = renderer.depth_flat().unwrap().iter().fold(f32::INFINITY, |a , &b| a.min(b));
let max = renderer.depth_flat().unwrap().iter().fold(f32::NEG_INFINITY, |a , &b| a.max(b));
assert_relative_eq!(min, max, epsilon = 1e-4);
assert_relative_eq!(min, 2.25, epsilon = 1e-4);
}
/// Decode a PNG file and return the raw pixel bytes.
#[cfg(target_os = "linux")]
fn decode_png_pixels(path: &std::path::Path) -> Vec<u8> {
let decoder = png::Decoder::new(std::io::BufReader::new(std::fs::File::open(path).unwrap()));
let mut reader = decoder.read_info().unwrap();
let mut buf = vec![0u8; reader.output_buffer_size().unwrap()];
reader.next_frame(&mut buf).unwrap();
buf
}
/// Verify that all compression levels produce identical pixel data.
/// This is only run on Linux due to EGL requirements (winit cannot be used on multiple threads).
#[test]
#[cfg(target_os = "linux")]
fn test_png_compression_lossless() {
let model = MjModel::from_xml_string(MODEL).expect("could not load the model");
let mut data = MjData::new(&model);
data.step();
let mut renderer = MjRenderer::builder()
.rgb(true)
.depth(false)
.build(&model)
.unwrap();
renderer.sync_data(&mut data).unwrap();
renderer.render().unwrap();
let tmp = std::env::temp_dir();
let path_none = tmp.join("mujoco_rs_test_none.png");
let path_fast = tmp.join("mujoco_rs_test_fast.png");
let path_high = tmp.join("mujoco_rs_test_high.png");
renderer.save_rgb(&path_none).unwrap();
renderer.set_png_compression(png::Compression::Fast);
renderer.save_rgb(&path_fast).unwrap();
renderer.set_png_compression(png::Compression::High);
renderer.save_rgb(&path_high).unwrap();
let pixels_none = decode_png_pixels(&path_none);
let pixels_fast = decode_png_pixels(&path_fast);
let pixels_high = decode_png_pixels(&path_high);
assert_eq!(pixels_none, pixels_fast, "Fast compression must produce identical pixels");
assert_eq!(pixels_none, pixels_high, "High compression must produce identical pixels");
let _ = std::fs::remove_file(&path_none);
let _ = std::fs::remove_file(&path_fast);
let _ = std::fs::remove_file(&path_high);
}
}