Migrated from GitHub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+170
- data/AUTHORSAdded+7
- data/CONTRIBUTING.mdAdded+23
- data/LICENSEAdded+202
- data/README.mdAdded+138
- data/dm_control/__init__.pyAdded+14
- data/dm_control/_render/__init__.pyAdded+109
- data/dm_control/_render/base.pyAdded+166
- data/dm_control/_render/base_test.pyAdded+162
- data/dm_control/_render/constants.pyAdded+33
- data/dm_control/_render/executor/__init__.pyAdded+51
- data/dm_control/_render/executor/render_executor.pyAdded+218
- data/dm_control/_render/executor/render_executor_test.pyAdded+205
- data/dm_control/_render/glfw_renderer.pyAdded+68
- data/dm_control/_render/glfw_renderer_test.pyAdded+68
- data/dm_control/_render/pyopengl/__init__.pyAdded+14
- data/dm_control/_render/pyopengl/egl_ext.pyAdded+74
- data/dm_control/_render/pyopengl/egl_renderer.pyAdded+140
- data/dm_control/_render/pyopengl/osmesa_renderer.pyAdded+86
- data/dm_control/_render/pyopengl/osmesa_renderer_test.pyAdded+70
- data/dm_control/autowrap/__init__.pyAdded+15
- data/dm_control/autowrap/autowrap.pyAdded+126
- data/dm_control/autowrap/binding_generator.pyAdded+296
- data/dm_control/autowrap/codegen_util.pyAdded+119
- data/dm_control/autowrap/header_parsing.pyAdded+335
- data/dm_control/blender/fake_core/bpy.pyAdded+229
- data/dm_control/blender/fake_core/mathutils.pyAdded+123
- data/dm_control/blender/mujoco_exporter/README.mdAdded+213
- data/dm_control/blender/mujoco_exporter/__init__.pyAdded+170
- data/dm_control/blender/mujoco_exporter/blender_scene.pyAdded+428
- data/dm_control/blender/mujoco_exporter/blender_scene_test.pyAdded+244
- data/dm_control/blender/mujoco_exporter/doc/add_ik_constraint.pngAdded
- data/dm_control/blender/mujoco_exporter/doc/convhull_blend.pngAdded
- data/dm_control/blender/mujoco_exporter/doc/convhull_mj_hull.pngAdded
- data/dm_control/blender/mujoco_exporter/doc/convhull_mj_rend.pngAdded
- data/dm_control/blender/mujoco_exporter/doc/enable_plugin.pngAdded
- data/dm_control/blender/mujoco_exporter/doc/end_effector_selection.pngAdded
- data/dm_control/blender/mujoco_exporter/doc/gizmo.pngAdded
- data/dm_control/blender/mujoco_exporter/doc/ik_chain_length.pngAdded
- data/dm_control/blender/mujoco_exporter/doc/ik_target.pngAdded
- data/dm_control/blender/mujoco_exporter/doc/install_plugin.pngAdded
- data/dm_control/blender/mujoco_exporter/doc/limits.pngAdded
- data/dm_control/blender/mujoco_exporter/install.shAdded+13
- data/dm_control/blender/mujoco_exporter/mujoco_assets.pyAdded+175
- data/dm_control/blender/mujoco_exporter/mujoco_assets_test.pyAdded+225
- data/dm_control/blender/mujoco_exporter/mujoco_scene.pyAdded+188
- data/dm_control/blender/mujoco_exporter/mujoco_scene_test.pyAdded+195
- data/dm_control/blender/mujoco_exporter/testing.pyAdded+198
- data/dm_control/composer/__init__.pyAdded+33
- data/dm_control/composer/arena.pyAdded+70
57 unmodified lines58596057 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text57 unmodified lines58596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923057 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/soccer/assets/humanoid/jersey.skn filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/abdomen_1_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/abdomen_8_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/antenna_left_black.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/antenna_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/antenna_right_black.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/antenna_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/coxa_T1_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/coxa_T1_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/coxa_T2_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/coxa_T2_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/coxa_T3_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/coxa_T3_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/femur_T1_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/femur_T1_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/femur_T2_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/femur_T2_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/femur_T3_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/femur_T3_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/haltere_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/haltere_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/haustellum_black.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/haustellum_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/head_black.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/head_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/head_ocelli.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/head_red.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/labrum_left_lower.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/labrum_right_lower.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/rostrum_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/rostrum_bristle-brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsal_claw_T1_left_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsal_claw_T1_right_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsal_claw_T2_left_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsal_claw_T2_right_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsal_claw_T3_left_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsal_claw_T3_right_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsus_T2_1_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsus_T2_1_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsus_T3_1_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsus_T3_1_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/thorax_black.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/thorax_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tibia_T1_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tibia_T1_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tibia_T2_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tibia_T2_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tibia_T3_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tibia_T3_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/wing_left_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/build_fruitfly/assets/wing_right_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/dog_v2/dog_skin.skn filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/abdomen_1_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/abdomen_8_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/antenna_left_black.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/antenna_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/antenna_right_black.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/antenna_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/blender_model/drosophila_v2.blend filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/coxa_T1_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/coxa_T1_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/coxa_T2_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/coxa_T2_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/coxa_T3_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/coxa_T3_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/femur_T1_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/femur_T1_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/femur_T2_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/femur_T2_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/femur_T3_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/femur_T3_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/haltere_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/haltere_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/haustellum_black.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/haustellum_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/head_black.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/head_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/head_ocelli.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/head_red.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/labrum_left_lower.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/labrum_right_lower.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/rostrum_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/rostrum_bristle-brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsal_claw_T1_left_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsal_claw_T1_right_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsal_claw_T2_left_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsal_claw_T2_right_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsal_claw_T3_left_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsal_claw_T3_right_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsus_T2_1_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsus_T2_1_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsus_T3_1_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsus_T3_1_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/thorax_black.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/thorax_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tibia_T1_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tibia_T1_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tibia_T2_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tibia_T2_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tibia_T3_left_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/tibia_T3_right_body.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/wing_left_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/fruitfly_v2/wing_right_brown.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/locomotion/walkers/assets/rodent_walker_skin.skn filter=lfs diff=lfs merge=lfs -textdata/dm_control/mjcf/test_assets/skins/test_skin.skn filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEC_1.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEC_2.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEC_3.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEC_4.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEC_5.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEC_6.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEC_7.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEJaw.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEL_1.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEL_2.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEL_3.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEL_4.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEL_5.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEL_6.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEL_7.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEMergedSkull.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONEPelvis.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONERibcage.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/BONESacrum.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/SKINbody.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/dog_skin.msh filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/dog_skin.skn filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONEEthmoid.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONEMandible.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONESkull.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONET_1.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONET_10.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONET_11.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONET_12.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONET_13.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONET_2.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONET_3.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONET_4.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONET_5.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONET_6.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONET_7.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONET_8.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/BONET_9.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCMm.dorsi_Fascia_thoracolumbar_.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCMm.thoracis_serratus_ventr_L.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCMm.thoracis_serratus_ventr_R.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCNose.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCabdominis_Aponeurosis.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCdiaphragma.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCm.brachiocephalicus.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCm.flexor_digitorum_profundus_L(2).stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCm.flexor_digitorum_profundus_L.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCm.flexor_digitorum_profundus_R(2).stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCm.flexor_digitorum_profundus_R.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCm.orbicularis_oculi.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCm.trapezius.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCmm.intercostals_ext.L.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCmm.intercostals_ext_R.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCmm.intercostals_int.L.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCmm.intercostals_int_R.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/suite/dog_assets/extras/MUSCmm.thoracis_m.pectoralis_profundus.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/third_party/kinova/meshes/arm.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/third_party/kinova/meshes/base.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/third_party/kinova/meshes/finger_proximal.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/third_party/kinova/meshes/forearm.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/third_party/kinova/meshes/hand_3finger.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/third_party/kinova/meshes/hand_3finger_insert.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/third_party/kinova/meshes/hand_3finger_main.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/third_party/kinova/meshes/shoulder.stl filter=lfs diff=lfs merge=lfs -textdata/dm_control/third_party/kinova/meshes/wrist.stl filter=lfs diff=lfs merge=lfs -text
1234567# This is the list of dm_control authors for copyright purposes.## This does not necessarily list everyone who has contributed code, since in# some cases, their employer may be the copyright holder. To see the full list# of contributors, see the revision history in source control.
DeepMind Technologies1234567891011121314151617181920212223# How to Contribute
We'd love to accept your patches and contributions to this project. There arejust a few small guidelines you need to follow.
## Contributor License Agreement
Contributions to this project must be accompanied by a Contributor LicenseAgreement. You (or your employer) retain the copyright to your contribution,this simply gives us permission to use and redistribute your contributions aspart of the project. Head over to <https://cla.developers.google.com/> to seeyour current agreements on file or to sign a new one.
You generally only need to submit a CLA once, so if you've already submitted one(even if it was for a different project), you probably don't need to do itagain.
## Code reviews
All submissions, including submissions by project members, require review. Weuse GitHub pull requests for this purpose. Consult[GitHub Help](https://help.github.com/articles/about-pull-requests/) for moreinformation on using pull requests.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138# `dm_control`: Google DeepMind Infrastructure for Physics-Based Simulation.
Google DeepMind's software stack for physics-based simulation and ReinforcementLearning environments, using MuJoCo physics.
An **introductory tutorial** for this package is available as a Colaboratorynotebook:[](https://colab.research.google.com/github/google-deepmind/dm_control/blob/main/tutorial.ipynb)
## Overview
This package consists of the following "core" components:
- [`dm_control.mujoco`]: Libraries that provide Python bindings to the MuJoCo physics engine.
- [`dm_control.suite`]: A set of Python Reinforcement Learning environments powered by the MuJoCo physics engine.
- [`dm_control.viewer`]: An interactive environment viewer.
Additionally, the following components are available for the creation of morecomplex control tasks:
- [`dm_control.mjcf`]: A library for composing and modifying MuJoCo MJCF models in Python.
- `dm_control.composer`: A library for defining rich RL environments from reusable, self-contained components.
- [`dm_control.locomotion`]: Additional libraries for custom tasks.
- [`dm_control.locomotion.soccer`]: Multi-agent soccer tasks.
If you use this package, please cite our accompanying [publication]:
```@article{tunyasuvunakool2020, title = {dm_control: Software and tasks for continuous control}, journal = {Software Impacts}, volume = {6}, pages = {100022}, year = {2020}, issn = {2665-9638}, doi = {https://doi.org/10.1016/j.simpa.2020.100022}, url = {https://www.sciencedirect.com/science/article/pii/S2665963820300099}, author = {Saran Tunyasuvunakool and Alistair Muldal and Yotam Doron and Siqi Liu and Steven Bohez and Josh Merel and Tom Erez and Timothy Lillicrap and Nicolas Heess and Yuval Tassa},}```
## Installation
Install `dm_control` from PyPI by running
```shpip install dm_control```
> **Note**: **`dm_control` cannot be installed in "editable" mode** (i.e. `pip> install -e`).>> While `dm_control` has been largely updated to use the pybind11-based bindings> provided via the `mujoco` package, at this time it still relies on some legacy> components that are automatically generated from MuJoCo header files in a way> that is incompatible with editable mode. Attempting to install `dm_control` in> editable mode will result in import errors like:>> ```> ImportError: cannot import name 'constants' from partially initialized module 'dm_control.mujoco.wrapper.mjbindings' ...> ```>> The solution is to `pip uninstall dm_control` and then reinstall it without> the `-e` flag.
## Versioning
Starting from version 1.0.0, we adopt semantic versioning.
Prior to version 1.0.0, the `dm_control` Python package was versioned `0.0.N`,where `N` was an internal revision number that increased by an arbitrary amountat every single Git commit.
If you want to install an unreleased version of `dm_control` directly from ourrepository, you can do so by running `pip installgit+https://github.com/google-deepmind/dm_control.git`.
## Rendering
The MuJoCo Python bindings support three different OpenGL rendering backends:EGL (headless, hardware-accelerated), GLFW (windowed, hardware-accelerated), andOSMesa (purely software-based). At least one of these three backends must beavailable in order render through `dm_control`.
* Hardware rendering with a windowing system is supported via GLFW and GLEW. On Linux these can be installed using your distribution's package manager. For example, on Debian and Ubuntu, this can be done by running `sudo apt-get install libglfw3 libglew2.0`. Please note that:
- [`dm_control.viewer`] can only be used with GLFW. - GLFW will not work on headless machines.
* "Headless" hardware rendering (i.e. without a windowing system such as X11) requires [EXT_platform_device] support in the EGL driver. Recent Nvidia drivers support this. You will also need GLEW. On Debian and Ubuntu, this can be installed via `sudo apt-get install libglew2.0`.
* Software rendering requires GLX and OSMesa. On Debian and Ubuntu these can be installed using `sudo apt-get install libgl1-mesa-glx libosmesa6`.
By default, `dm_control` will attempt to use GLFW first, then EGL, then OSMesa.You can also specify a particular backend to use by setting the `MUJOCO_GL=`environment variable to `"glfw"`, `"egl"`, or `"osmesa"`, respectively. Whenrendering with EGL, you can also specify which GPU to use for rendering bysetting the environment variable `MUJOCO_EGL_DEVICE_ID=` to the target GPU ID.
## Additional instructions for Homebrew users on macOS
1. The above instructions using `pip` should work, provided that you use a Python interpreter that is installed by Homebrew (rather than the system-default one).
2. Before running, the `DYLD_LIBRARY_PATH` environment variable needs to be updated with the path to the GLFW library. This can be done by running `export DYLD_LIBRARY_PATH=$(brew --prefix)/lib:$DYLD_LIBRARY_PATH`.
[EXT_platform_device]: https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_platform_device.txt[Releases page on the MuJoCo GitHub repository]: https://github.com/google-deepmind/mujoco/releases[MuJoCo website]: https://mujoco.org/[publication]: https://doi.org/10.1016/j.simpa.2020.100022[`ctypes`]: https://docs.python.org/3/library/ctypes.html[`dm_control.mjcf`]: dm_control/mjcf/README.md[`dm_control.mujoco`]: dm_control/mujoco/README.md[`dm_control.suite`]: dm_control/suite/README.md[`dm_control.viewer`]: dm_control/viewer/README.md[`dm_control.locomotion`]: dm_control/locomotion/README.md[`dm_control.locomotion.soccer`]: dm_control/locomotion/soccer/README.md1234567891011121314# Copyright 2017 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109# Copyright 2017-2018 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""OpenGL context management for rendering MuJoCo scenes.
By default, the `Renderer` class will try to load one of the following renderingAPIs, in descending order of priority: GLFW > EGL > OSMesa.
It is also possible to select a specific backend by setting the `MUJOCO_GL=`environment variable to 'glfw', 'egl', or 'osmesa'."""
import collectionsimport os
from absl import loggingfrom dm_control._render import constants
BACKEND = os.environ.get(constants.MUJOCO_GL)
# pylint: disable=g-import-not-at-topdef _import_egl(): from dm_control._render.pyopengl.egl_renderer import EGLContext return EGLContext
def _import_glfw(): from dm_control._render.glfw_renderer import GLFWContext return GLFWContext
def _import_osmesa(): from dm_control._render.pyopengl.osmesa_renderer import OSMesaContext return OSMesaContext
# Import removed.# pylint: enable=g-import-not-at-top
def _no_renderer(): def no_renderer(*args, **kwargs): del args, kwargs raise RuntimeError('No OpenGL rendering backend is available.') return no_renderer
_ALL_RENDERERS = ( (constants.GLFW, _import_glfw), (constants.EGL, _import_egl), (constants.OSMESA, _import_osmesa), # Option removed.)
_NO_RENDERER = ( (constants.NO_RENDERER, _no_renderer),)
if BACKEND is not None: # If a backend was specified, try importing it and error if unsuccessful. import_func = None for names, importer in _ALL_RENDERERS + _NO_RENDERER: if BACKEND in names: import_func = importer BACKEND = names[0] # canonicalize the renderer name break if import_func is None: all_names = set() for names, _ in _ALL_RENDERERS + _NO_RENDERER: all_names.update(names) raise RuntimeError( 'Environment variable {} must be one of {!r}: got {!r}.' .format(constants.MUJOCO_GL, sorted(all_names), BACKEND)) logging.info('MUJOCO_GL=%s, attempting to import specified OpenGL backend.', BACKEND) Renderer = import_func()else: logging.info('MUJOCO_GL is not set, so an OpenGL backend will be chosen ' 'automatically.') # Otherwise try importing them in descending order of priority until # successful. for names, import_func in _ALL_RENDERERS: try: Renderer = import_func() BACKEND = names[0] logging.info('Successfully imported OpenGL backend: %s', names[0]) break except ImportError: logging.info('Failed to import OpenGL backend: %s', names[0]) if BACKEND is None: logging.info('No OpenGL backend could be imported. Attempting to create a ' 'rendering context will result in a RuntimeError.') Renderer = _no_renderer()
USING_GPU = BACKEND in constants.EGL + constants.GLFW123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166# Copyright 2017 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Base class for OpenGL context handlers.
`ContextBase` defines a common API that OpenGL rendering contexts should conformto. In addition, it provides a `make_current` context manager that:
1. Makes this OpenGL context current within the appropriate rendering thread.2. Yields an object exposing a `call` method that can be used to execute OpenGL calls within the rendering thread.
See the docstring for `dm_control.utils.render_executor` for further detailsregarding rendering threads."""
import abcimport atexitimport collectionsimport contextlibimport sysimport weakref
from absl import loggingfrom dm_control._render import executorimport numpy as np
_CURRENT_CONTEXT_FOR_THREAD = collections.defaultdict(lambda: None)_CURRENT_THREAD_FOR_CONTEXT = collections.defaultdict(lambda: None)
class ContextBase(metaclass=abc.ABCMeta): """Base class for managing OpenGL contexts."""
def __init__(self, max_width, max_height, render_executor_class=executor.RenderExecutor): """Initializes this context.""" logging.debug('Using render executor class: %s', render_executor_class.__name__) self._render_executor = render_executor_class() self._refcount = 0
self_weakref = weakref.ref(self) def _free_at_exit(): if self_weakref(): self_weakref()._free_unconditionally() # pylint: disable=protected-access atexit.register(_free_at_exit)
with self._render_executor.execution_context() as ctx: ctx.call(self._platform_init, max_width, max_height)
self._patients = []
def keep_alive(self, obj): self._patients.append(obj)
def dont_keep_alive(self, obj): try: self._patients.remove(obj) except ValueError: pass
def increment_refcount(self): self._refcount += 1
def decrement_refcount(self): self._refcount -= 1
@property def terminated(self): return self._render_executor.terminated
@property def thread(self): return self._render_executor.thread
def _free_on_executor_thread(self): # pylint: disable=missing-function-docstring current_ctx = _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread] if current_ctx is not None: del _CURRENT_THREAD_FOR_CONTEXT[current_ctx] del _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread]
self._platform_make_current()
try: dummy = [] while self._patients: patient = self._patients.pop() assert sys.getrefcount(patient) == sys.getrefcount(dummy) if hasattr(patient, 'free'): patient.free() del patient finally: self._platform_free()
def free(self): """Frees resources associated with this context if its refcount is zero.""" if self._refcount == 0: self._free_unconditionally()
def _free_unconditionally(self): self._render_executor.terminate(self._free_on_executor_thread)
def __del__(self): self._free_unconditionally()
@contextlib.contextmanager def make_current(self): """Context manager that makes this Renderer's OpenGL context current.
Yields: An object that exposes a `call` method that can be used to call a function on the dedicated rendering thread.
Raises: RuntimeError: If this context is already current on another thread. """
with self._render_executor.execution_context() as ctx: if _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread] != id(self): if _CURRENT_THREAD_FOR_CONTEXT[id(self)]: raise RuntimeError( 'Cannot make context {!r} current on thread {!r}: ' 'this context is already current on another thread {!r}.' .format(self, self._render_executor.thread, _CURRENT_THREAD_FOR_CONTEXT[id(self)])) else: current_context = ( _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread]) if current_context: del _CURRENT_THREAD_FOR_CONTEXT[current_context] _CURRENT_THREAD_FOR_CONTEXT[id(self)] = self._render_executor.thread _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread] = id(self) ctx.call(self._platform_make_current) yield ctx
def to_pixels(self, buffer): """Converts the buffer to pixels.""" return np.flipud(buffer)
@abc.abstractmethod def _platform_init(self, max_width, max_height): """Performs an implementation-specific context initialization."""
@abc.abstractmethod def _platform_make_current(self): """Make the OpenGL context current on the executing thread."""
@abc.abstractmethod def _platform_free(self): """Performs an implementation-specific context cleanup."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162# Copyright 2017 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Tests for the base rendering module."""
import threadingfrom absl.testing import absltestfrom dm_control._render import basefrom dm_control._render import executor
WIDTH = 1024HEIGHT = 768
class ContextBaseTests(absltest.TestCase):
class ContextMock(base.ContextBase):
def _platform_init(self, max_width, max_height): self.init_thread = threading.current_thread() self.make_current_count = 0 self.max_width = max_width self.max_height = max_height self.free_thread = None
def _platform_make_current(self): self.make_current_count += 1 self.make_current_thread = threading.current_thread()
def _platform_free(self): self.free_thread = threading.current_thread()
def setUp(self): super().setUp() self.context = ContextBaseTests.ContextMock(WIDTH, HEIGHT)
def test_init(self): self.assertIs(self.context.init_thread, self.context.thread) self.assertEqual(self.context.max_width, WIDTH) self.assertEqual(self.context.max_height, HEIGHT)
def test_make_current(self): self.assertEqual(self.context.make_current_count, 0)
with self.context.make_current(): pass self.assertEqual(self.context.make_current_count, 1) self.assertIs(self.context.make_current_thread, self.context.thread)
# Already current, shouldn't trigger a call to `_platform_make_current`. with self.context.make_current(): pass self.assertEqual(self.context.make_current_count, 1) self.assertIs(self.context.make_current_thread, self.context.thread)
def test_thread_sharing(self): first_context = ContextBaseTests.ContextMock( WIDTH, HEIGHT, executor.PassthroughRenderExecutor) second_context = ContextBaseTests.ContextMock( WIDTH, HEIGHT, executor.PassthroughRenderExecutor)
with first_context.make_current(): pass self.assertEqual(first_context.make_current_count, 1)
with first_context.make_current(): pass self.assertEqual(first_context.make_current_count, 1)
with second_context.make_current(): pass self.assertEqual(second_context.make_current_count, 1)
with second_context.make_current(): pass self.assertEqual(second_context.make_current_count, 1)
with first_context.make_current(): pass self.assertEqual(first_context.make_current_count, 2)
with second_context.make_current(): pass self.assertEqual(second_context.make_current_count, 2)
def test_free(self): with self.context.make_current(): pass
thread = self.context.thread self.assertIn(id(self.context), base._CURRENT_THREAD_FOR_CONTEXT) self.assertIn(thread, base._CURRENT_CONTEXT_FOR_THREAD)
self.context.free() self.assertIs(self.context.free_thread, thread) self.assertIsNone(self.context.thread)
self.assertNotIn(id(self.context), base._CURRENT_THREAD_FOR_CONTEXT) self.assertNotIn(thread, base._CURRENT_CONTEXT_FOR_THREAD)
def test_free_with_multiple_contexts(self): context1 = ContextBaseTests.ContextMock(WIDTH, HEIGHT, executor.PassthroughRenderExecutor) with context1.make_current(): pass
context2 = ContextBaseTests.ContextMock(WIDTH, HEIGHT, executor.PassthroughRenderExecutor) with context2.make_current(): pass
self.assertEqual(base._CURRENT_CONTEXT_FOR_THREAD[threading.main_thread()], id(context2)) self.assertIs(base._CURRENT_THREAD_FOR_CONTEXT[id(context2)], threading.main_thread())
context1.free() self.assertIsNone( base._CURRENT_CONTEXT_FOR_THREAD[self.context.free_thread]) self.assertIsNone(base._CURRENT_THREAD_FOR_CONTEXT[id(context2)])
def test_refcounting(self): thread = self.context.thread
self.assertEqual(self.context._refcount, 0) self.context.increment_refcount() self.assertEqual(self.context._refcount, 1)
# Context should not be freed yet, since its refcount is still positive. self.context.free() self.assertIsNone(self.context.free_thread) self.assertIs(self.context.thread, thread)
# Decrement the refcount to zero. self.context.decrement_refcount() self.assertEqual(self.context._refcount, 0)
# Now the context can be freed. self.context.free() self.assertIs(self.context.free_thread, thread) self.assertIsNone(self.context.thread)
def test_del(self): self.assertIsNone(self.context.free_thread) self.context.__del__() self.assertIsNotNone(self.context.free_thread)
if __name__ == '__main__': absltest.main()123456789101112131415161718192021222324252627282930313233# Copyright 2018 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""String constants for the rendering module."""
# Name of the environment variable that selects a renderer platform.MUJOCO_GL = 'MUJOCO_GL'
# Name of the environment variable that selects a platform for PyOpenGL.PYOPENGL_PLATFORM = 'PYOPENGL_PLATFORM'
# Renderer platform specifiers.# All values in each tuple are synonyms for the MUJOCO_GL environment variable.# The first entry in each tuple is considered "canonical", and is the one# assigned to the _render.BACKEND variable.OSMESA = ('osmesa',)GLFW = ('glfw', 'on', 'enable', 'enabled', 'true', '1', '')EGL = ('egl',)# Constant removed.NO_RENDERER = ('off', 'disable', 'disabled', 'false', '0')
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051# Copyright 2017 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""RenderExecutor executes OpenGL rendering calls on an appropriate thread.
OpenGL calls must be made on the same thread as where an OpenGL context ismade current on. With GPU rendering, migrating OpenGL contexts between threadscan become expensive. We provide a thread-safe executor that maintains athread on which an OpenGL context can be kept permanently current, and any otherthreads that wish to render with that context will have their rendering callsoffloaded to the dedicated thread.
For single-threaded applications, set the `DISABLE_RENDER_THREAD_OFFLOADING`environment variable before launching the Python interpreter. This willeliminate the overhead of unnecessary thread-switching."""
# pylint: disable=g-import-not-at-topimport os_OFFLOAD = not bool(os.environ.get('DISABLE_RENDER_THREAD_OFFLOADING', ''))del os
from dm_control._render.executor.render_executor import BaseRenderExecutorfrom dm_control._render.executor.render_executor import OffloadingRenderExecutorfrom dm_control._render.executor.render_executor import PassthroughRenderExecutor
_EXECUTORS = (PassthroughRenderExecutor, OffloadingRenderExecutor)
try: from dm_control._render.executor.native_mutex.render_executor import NativeMutexOffloadingRenderExecutor _EXECUTORS += (NativeMutexOffloadingRenderExecutor,)except ImportError: NativeMutexOffloadingRenderExecutor = None
if _OFFLOAD: RenderExecutor = ( # pylint: disable=invalid-name NativeMutexOffloadingRenderExecutor or OffloadingRenderExecutor)else: RenderExecutor = PassthroughRenderExecutor # pylint: disable=invalid-name123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218# Copyright 2017-2018 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""RenderExecutors executes OpenGL rendering calls on an appropriate thread.
The purpose of these classes is to ensure that OpenGL calls are made on thesame thread as where an OpenGL context was made current.
In a single-threaded setting, `PassthroughRenderExecutor` is essentially a no-opthat executes rendering calls on the same thread. This is provided to minimizethread-switching overhead.
In a multithreaded setting, `OffloadingRenderExecutor` maintains a separatededicated thread on which the OpenGL context is created and made current. Allsubsequent rendering calls are then offloaded onto this dedicated thread."""
import abcimport collectionsfrom concurrent import futuresimport contextlibimport threading
_NOT_IN_CONTEXT = 'Cannot be called outside of an `execution_context`.'_ALREADY_TERMINATED = 'This executor has already been terminated.'
class _FakeLock: """An object with the same API as `threading.Lock` but that does nothing."""
def acquire(self, blocking=True): pass
def release(self): pass
def __enter__(self): pass
def __exit__(self, exc_type, exc_value, traceback): del exc_type, exc_value, traceback
_FAKE_LOCK = _FakeLock()
class BaseRenderExecutor(metaclass=abc.ABCMeta): """An object that manages rendering calls for an OpenGL context.
This class helps ensure that OpenGL calls are made on the correct thread. The usage pattern is as follows:
```python executor = SomeRenderExecutorClass() with executor.execution_context() as ctx: ctx.call(an_opengl_call, arg, kwarg=foo) result = ctx.call(another_opengl_call) ``` """
def __init__(self): self._locked = 0 self._terminated = False
def _check_locked(self): if not self._locked: raise RuntimeError(_NOT_IN_CONTEXT)
def _check_not_terminated(self): if self._terminated: raise RuntimeError(_ALREADY_TERMINATED)
@contextlib.contextmanager def execution_context(self): """A context manager that allows calls to be offloaded to this executor.""" self._check_not_terminated() with self._lock_if_necessary: self._locked += 1 yield self self._locked -= 1
@property def terminated(self): return self._terminated
@property @abc.abstractmethod def thread(self): pass
@property @abc.abstractmethod def _lock_if_necessary(self): pass
@abc.abstractmethod def call(self, *args, **kwargs): pass
@abc.abstractmethod def terminate(self, cleanup_callable=None): pass
class PassthroughRenderExecutor(BaseRenderExecutor): """A no-op render executor that executes on the calling thread."""
def __init__(self): super().__init__() self._mutex = threading.RLock()
@property def thread(self): if not self._terminated: return threading.current_thread() else: return None
@property def _lock_if_necessary(self): return self._mutex
def call(self, func, *args, **kwargs): self._check_locked() return func(*args, **kwargs)
def terminate(self, cleanup_callable=None): with self._lock_if_necessary: if not self._terminated: if cleanup_callable: cleanup_callable() self._terminated = True
class _ThreadPoolExecutorPool: """A pool of reusable ThreadPoolExecutors."""
def __init__(self): self._deque = collections.deque() self._lock = threading.Lock()
def acquire(self): with self._lock: if self._deque: return self._deque.popleft() else: return futures.ThreadPoolExecutor(max_workers=1)
def release(self, thread_pool_executor): with self._lock: self._deque.append(thread_pool_executor)
_THREAD_POOL_EXECUTOR_POOL = _ThreadPoolExecutorPool()
class OffloadingRenderExecutor(BaseRenderExecutor): """A render executor that executes calls on a dedicated offload thread."""
def __init__(self): super().__init__() self._mutex = threading.RLock() self._executor = _THREAD_POOL_EXECUTOR_POOL.acquire() self._thread = self._executor.submit(threading.current_thread).result()
@property def thread(self): return self._thread
@property def _lock_if_necessary(self): if threading.current_thread() is self.thread: # If the offload thread needs to make a call to its own executor, for # example when a weakref callback is triggered during an offloaded call, # then we must not try to reacquire our own lock. # Otherwise, a deadlock ensues. return _FAKE_LOCK else: return self._mutex
def call(self, func, *args, **kwargs): self._check_locked() return self._call_locked(func, *args, **kwargs)
def _call_locked(self, func, *args, **kwargs): if threading.current_thread() is self.thread: # If the offload thread needs to make a call to its own executor, for # example when a weakref callback is triggered during an offloaded call, # we should just directly call the function. # Otherwise, a deadlock ensues. return func(*args, **kwargs) else: return self._executor.submit(func, *args, **kwargs).result()
def terminate(self, cleanup_callable=None): if self._terminated: return with self._lock_if_necessary: if not self._terminated: if cleanup_callable: self._call_locked(cleanup_callable) _THREAD_POOL_EXECUTOR_POOL.release(self._executor) self._executor = None self._thread = None self._terminated = True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205# Copyright 2017-2018 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Tests for dm_control.utils.render_executor."""
import threadingimport timeimport unittest
from absl.testing import absltestfrom absl.testing import parameterizedfrom dm_control._render import executorimport mock
def enforce_timeout(timeout): def wrap(test_func): def wrapped_test(self, *args, **kwargs): thread = threading.Thread( target=test_func, args=((self,) + args), kwargs=kwargs) thread.daemon = True thread.start() thread.join(timeout=timeout) self.assertFalse( thread.is_alive(), msg='Test timed out after {} seconds.'.format(timeout)) return wrapped_test return wrap
class RenderExecutorTest(parameterized.TestCase):
def _make_executor(self, executor_type): if (executor_type == executor.NativeMutexOffloadingRenderExecutor and executor_type is None): raise unittest.SkipTest( 'NativeMutexOffloadingRenderExecutor is not available.') else: return executor_type()
def test_passthrough_executor_thread(self): render_executor = self._make_executor(executor.PassthroughRenderExecutor) self.assertIs(render_executor.thread, threading.current_thread()) render_executor.terminate()
@parameterized.parameters(executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_offloading_executor_thread(self, executor_type): render_executor = self._make_executor(executor_type) self.assertIsNot(render_executor.thread, threading.current_thread()) render_executor.terminate()
@parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_call_on_correct_thread(self, executor_type): render_executor = self._make_executor(executor_type) with render_executor.execution_context() as ctx: actual_executed_thread = ctx.call(threading.current_thread) self.assertIs(actual_executed_thread, render_executor.thread) render_executor.terminate()
@parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_multithreaded(self, executor_type): render_executor = self._make_executor(executor_type) list_length = 5 shared_list = [None] * list_length
def fill_list(thread_idx): def assign_value(i): shared_list[i] = thread_idx for _ in range(1000): with render_executor.execution_context() as ctx: for i in range(list_length): ctx.call(assign_value, i) # Other threads should be prevented from calling `assign_value` while # this thread is inside the `execution_context`. self.assertEqual(shared_list, [thread_idx] * list_length)
threads = [threading.Thread(target=fill_list, args=(i,)) for i in range(9)] for thread in threads: thread.start() for thread in threads: thread.join()
render_executor.terminate()
@parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_exception(self, executor_type): render_executor = self._make_executor(executor_type) message = 'fake error' def raise_value_error(): raise ValueError(message) with render_executor.execution_context() as ctx: with self.assertRaisesWithLiteralMatch(ValueError, message): ctx.call(raise_value_error) render_executor.terminate()
@parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_terminate(self, executor_type): render_executor = self._make_executor(executor_type) cleanup = mock.MagicMock() render_executor.terminate(cleanup) cleanup.assert_called_once_with()
@parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_call_outside_of_context(self, executor_type): render_executor = self._make_executor(executor_type) func = mock.MagicMock() with self.assertRaisesWithLiteralMatch( RuntimeError, executor.render_executor._NOT_IN_CONTEXT): render_executor.call(func) # Also test that the locked flag is properly cleared when leaving a context. with render_executor.execution_context(): render_executor.call(lambda: None) with self.assertRaisesWithLiteralMatch( RuntimeError, executor.render_executor._NOT_IN_CONTEXT): render_executor.call(func) func.assert_not_called() render_executor.terminate()
@parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_call_after_terminate(self, executor_type): render_executor = self._make_executor(executor_type) render_executor.terminate() func = mock.MagicMock() with self.assertRaisesWithLiteralMatch( RuntimeError, executor.render_executor._ALREADY_TERMINATED): with render_executor.execution_context() as ctx: ctx.call(func) func.assert_not_called()
@parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) def test_locking(self, executor_type): render_executor = self._make_executor(executor_type) other_thread_context_entered = threading.Condition() other_thread_context_done = [False] def other_thread_func(): with render_executor.execution_context(): with other_thread_context_entered: other_thread_context_entered.notify() time.sleep(1) other_thread_context_done[0] = True other_thread = threading.Thread(target=other_thread_func) with other_thread_context_entered: other_thread.start() other_thread_context_entered.wait() with render_executor.execution_context(): self.assertTrue( other_thread_context_done[0], msg=('Main thread should not be able to enter the execution context ' 'until the other thread is done.'))
@parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) @enforce_timeout(timeout=5.) def test_reentrant_locking(self, executor_type): render_executor = self._make_executor(executor_type) def triple_lock(render_executor): with render_executor.execution_context(): with render_executor.execution_context(): with render_executor.execution_context(): pass triple_lock(render_executor)
@parameterized.parameters(executor.PassthroughRenderExecutor, executor.OffloadingRenderExecutor, executor.NativeMutexOffloadingRenderExecutor) @enforce_timeout(timeout=5.) def test_no_deadlock_in_callbacks(self, executor_type): render_executor = self._make_executor(executor_type) # This test times out in the event of a deadlock. def callback(): with render_executor.execution_context() as ctx: ctx.call(lambda: None) with render_executor.execution_context() as ctx: ctx.call(callback)
if __name__ == '__main__': absltest.main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768# Copyright 2017 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""An OpenGL renderer backed by GLFW."""
from dm_control._render import basefrom dm_control._render import executor
# Re-raise any exceptions that occur during module import as `ImportError`s.# This simplifies the conditional imports in `render/__init__.py`.try: import glfw # pylint: disable=g-import-not-at-topexcept (ImportError, IOError, OSError) as exc: raise ImportError from exctry: glfw.init()except glfw.GLFWError as exc: raise ImportError from exc
class GLFWContext(base.ContextBase): """An OpenGL context backed by GLFW."""
def __init__(self, max_width, max_height): # GLFWContext always uses `PassthroughRenderExecutor` rather than offloading # rendering calls to a separate thread because GLFW can only be safely used # from the main thread. super().__init__(max_width, max_height, executor.PassthroughRenderExecutor)
def _platform_init(self, max_width, max_height): """Initializes this context.
Args: max_width: Integer specifying the maximum framebuffer width in pixels. max_height: Integer specifying the maximum framebuffer height in pixels. """ glfw.window_hint(glfw.VISIBLE, 0) glfw.window_hint(glfw.DOUBLEBUFFER, 0) self._context = glfw.create_window(width=max_width, height=max_height, title='Invisible window', monitor=None, share=None) # This reference prevents `glfw.destroy_window` from being garbage-collected # before the last window is destroyed, otherwise we may get # `AttributeError`s when the `__del__` method is later called. self._destroy_window = glfw.destroy_window
def _platform_make_current(self): glfw.make_context_current(self._context)
def _platform_free(self): """Frees resources associated with this context.""" if self._context: if glfw.get_current_context() == self._context: glfw.make_context_current(None) self._destroy_window(self._context) self._context = None1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768# Copyright 2017 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Tests for GLFWContext."""
import unittestfrom absl.testing import absltestfrom dm_control import _renderfrom dm_control.mujoco import wrapperfrom dm_control.mujoco.testing import decorators
import mock # pylint: disable=g-import-not-at-top
MAX_WIDTH = 1024MAX_HEIGHT = 1024
CONTEXT_PATH = _render.__name__ + '.glfw_renderer.glfw'
@unittest.skipUnless( _render.BACKEND == _render.constants.GLFW[0], reason='GLFW beckend not selected.')class GLFWContextTest(absltest.TestCase):
def test_init(self): mock_context = mock.MagicMock() with mock.patch(CONTEXT_PATH) as mock_glfw: mock_glfw.create_window.return_value = mock_context renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT) self.assertIs(renderer._context, mock_context)
def test_make_current(self): mock_context = mock.MagicMock() with mock.patch(CONTEXT_PATH) as mock_glfw: mock_glfw.create_window.return_value = mock_context renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT) with renderer.make_current(): pass mock_glfw.make_context_current.assert_called_once_with(mock_context)
def test_freeing(self): mock_context = mock.MagicMock() with mock.patch(CONTEXT_PATH) as mock_glfw: mock_glfw.create_window.return_value = mock_context renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT) renderer.free() mock_glfw.destroy_window.assert_called_once_with(mock_context) self.assertIsNone(renderer._context)
@decorators.run_threaded(num_threads=1, calls_per_thread=20) def test_repeatedly_create_and_destroy_context(self): renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT) wrapper.MjrContext(wrapper.MjModel.from_xml_string('<mujoco/>'), renderer)
if __name__ == '__main__': absltest.main()1234567891011121314# Copyright 2018 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374# Copyright 2018 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Extends OpenGL.EGL with definitions necessary for headless rendering."""
import ctypesfrom OpenGL.platform import ctypesloader # pylint: disable=g-bad-import-ordertry: # Nvidia driver seems to need libOpenGL.so (as opposed to libGL.so) # for multithreading to work properly. We load this in before everything else. ctypesloader.loadLibrary(ctypes.cdll, 'OpenGL', mode=ctypes.RTLD_GLOBAL)except OSError: pass
# pylint: disable=g-import-not-at-top
from OpenGL import EGLfrom OpenGL import error
# From the EGL_EXT_device_enumeration extension.PFNEGLQUERYDEVICESEXTPROC = ctypes.CFUNCTYPE( EGL.EGLBoolean, EGL.EGLint, ctypes.POINTER(EGL.EGLDeviceEXT), ctypes.POINTER(EGL.EGLint),)try: _eglQueryDevicesEXT = PFNEGLQUERYDEVICESEXTPROC( # pylint: disable=invalid-name EGL.eglGetProcAddress('eglQueryDevicesEXT'))except TypeError: raise ImportError('eglQueryDevicesEXT is not available.')
# From the EGL_EXT_platform_device extension.EGL_PLATFORM_DEVICE_EXT = 0x313FPFNEGLGETPLATFORMDISPLAYEXTPROC = ctypes.CFUNCTYPE( EGL.EGLDisplay, EGL.EGLenum, ctypes.c_void_p, ctypes.POINTER(EGL.EGLint))try: eglGetPlatformDisplayEXT = PFNEGLGETPLATFORMDISPLAYEXTPROC( # pylint: disable=invalid-name EGL.eglGetProcAddress('eglGetPlatformDisplayEXT'))except TypeError: raise ImportError('eglGetPlatformDisplayEXT is not available.')
# Wrap raw _eglQueryDevicesEXT function into something more Pythonic.def eglQueryDevicesEXT(max_devices=10): # pylint: disable=invalid-name devices = (EGL.EGLDeviceEXT * max_devices)() num_devices = EGL.EGLint() success = _eglQueryDevicesEXT(max_devices, devices, num_devices) if success == EGL.EGL_TRUE: return [devices[i] for i in range(num_devices.value)] else: raise error.GLError(err=EGL.eglGetError(), baseOperation=eglQueryDevicesEXT, result=success)
# Expose everything from upstream so that# we can use this as a drop-in replacement for OpenGL.EGL.# pylint: disable=wildcard-import,g-bad-import-orderfrom OpenGL.EGL import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140# Copyright 2018 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""An OpenGL renderer backed by EGL, provided through PyOpenGL."""
import atexitimport ctypesimport os
from dm_control._render import basefrom dm_control._render import constantsfrom dm_control._render import executor
PYOPENGL_PLATFORM = os.environ.get(constants.PYOPENGL_PLATFORM)
if not PYOPENGL_PLATFORM: os.environ[constants.PYOPENGL_PLATFORM] = constants.EGL[0]elif PYOPENGL_PLATFORM != constants.EGL[0]: raise ImportError( 'Cannot use EGL rendering platform. ' 'The PYOPENGL_PLATFORM environment variable is set to {!r} ' '(should be either unset or {!r}).' .format(PYOPENGL_PLATFORM, constants.EGL[0]))
# pylint: disable=g-import-not-at-topfrom dm_control._render.pyopengl import egl_ext as EGLfrom OpenGL import error
def create_initialized_headless_egl_display(): """Creates an initialized EGL display directly on a device.""" all_devices = EGL.eglQueryDevicesEXT() selected_device = os.environ.get('MUJOCO_EGL_DEVICE_ID', None) if selected_device is None: candidates = all_devices else: device_idx = int(selected_device) if not 0 <= device_idx < len(all_devices): raise RuntimeError( f'MUJOCO_EGL_DEVICE_ID must be an integer between 0 and ' f'{len(all_devices) - 1} (inclusive), got {device_idx}.') candidates = all_devices[device_idx:device_idx + 1] for device in candidates: display = EGL.eglGetPlatformDisplayEXT( EGL.EGL_PLATFORM_DEVICE_EXT, device, None) if display != EGL.EGL_NO_DISPLAY and EGL.eglGetError() == EGL.EGL_SUCCESS: # `eglInitialize` may or may not raise an exception on failure depending # on how PyOpenGL is configured. We therefore catch a `GLError` and also # manually check the output of `eglGetError()` here. try: initialized = EGL.eglInitialize(display, None, None) except error.GLError: pass else: if initialized == EGL.EGL_TRUE and EGL.eglGetError() == EGL.EGL_SUCCESS: return display return EGL.EGL_NO_DISPLAY
EGL_DISPLAY = create_initialized_headless_egl_display()if EGL_DISPLAY == EGL.EGL_NO_DISPLAY: raise ImportError('Cannot initialize a headless EGL display.')atexit.register(EGL.eglTerminate, EGL_DISPLAY)
EGL_ATTRIBUTES = ( EGL.EGL_RED_SIZE, 8, EGL.EGL_GREEN_SIZE, 8, EGL.EGL_BLUE_SIZE, 8, EGL.EGL_ALPHA_SIZE, 8, EGL.EGL_DEPTH_SIZE, 24, EGL.EGL_STENCIL_SIZE, 8, EGL.EGL_COLOR_BUFFER_TYPE, EGL.EGL_RGB_BUFFER, EGL.EGL_SURFACE_TYPE, EGL.EGL_PBUFFER_BIT, EGL.EGL_RENDERABLE_TYPE, EGL.EGL_OPENGL_BIT, EGL.EGL_NONE)
class EGLContext(base.ContextBase): """An OpenGL context backed by EGL."""
def __init__(self, max_width, max_height): # EGLContext currently only works with `PassthroughRenderExecutor`. # TODO(b/110927854) Make this work with the offloading executor. self._context = None super().__init__(max_width, max_height, executor.PassthroughRenderExecutor)
def _platform_init(self, unused_max_width, unused_max_height): """Initialization this EGL context.""" num_configs = ctypes.c_long(0) config_size = 1 # ctypes syntax for making an array of length config_size. configs = (EGL.EGLConfig * config_size)() EGL.eglReleaseThread() EGL.eglChooseConfig( EGL_DISPLAY, EGL_ATTRIBUTES, configs, config_size, num_configs) if num_configs.value < 1: raise RuntimeError( 'EGL failed to find a framebuffer configuration that matches the ' 'desired attributes: {}'.format(EGL_ATTRIBUTES)) EGL.eglBindAPI(EGL.EGL_OPENGL_API) self._context = EGL.eglCreateContext( EGL_DISPLAY, configs[0], EGL.EGL_NO_CONTEXT, None) if not self._context: raise RuntimeError('Cannot create an EGL context.')
def _platform_make_current(self): if self._context: success = EGL.eglMakeCurrent( EGL_DISPLAY, EGL.EGL_NO_SURFACE, EGL.EGL_NO_SURFACE, self._context) if not success: raise RuntimeError('Failed to make the EGL context current.')
def _platform_free(self): """Frees resources associated with this context.""" if self._context: current_context = EGL.eglGetCurrentContext() if current_context and self._context.address == current_context.address: EGL.eglMakeCurrent(EGL_DISPLAY, EGL.EGL_NO_SURFACE, EGL.EGL_NO_SURFACE, EGL.EGL_NO_CONTEXT) EGL.eglDestroyContext(EGL_DISPLAY, self._context) self._context = None1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# Copyright 2018 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""An OpenGL renderer backed by OSMesa."""
import os
from dm_control._render import basefrom dm_control._render import constants
PYOPENGL_PLATFORM = os.environ.get(constants.PYOPENGL_PLATFORM)
if not PYOPENGL_PLATFORM: os.environ[constants.PYOPENGL_PLATFORM] = constants.OSMESA[0]elif PYOPENGL_PLATFORM != constants.OSMESA[0]: raise ImportError( 'Cannot use OSMesa rendering platform. ' 'The PYOPENGL_PLATFORM environment variable is set to {!r} ' '(should be either unset or {!r}).' .format(PYOPENGL_PLATFORM, constants.OSMESA[0]))
# pylint: disable=g-import-not-at-topfrom OpenGL import GLfrom OpenGL import osmesafrom OpenGL.GL import arrays
_DEPTH_BITS = 24_STENCIL_BITS = 8_ACCUM_BITS = 0
class OSMesaContext(base.ContextBase): """An OpenGL context backed by OSMesa."""
def __init__(self, *args, **kwargs): self._context = None super().__init__(*args, **kwargs)
def _platform_init(self, max_width, max_height): """Initializes this OSMesa context.""" self._context = osmesa.OSMesaCreateContextExt( osmesa.OSMESA_RGBA, _DEPTH_BITS, _STENCIL_BITS, _ACCUM_BITS, None, # sharelist ) if not self._context: raise RuntimeError('Failed to create OSMesa GL context.')
self._height = max_height self._width = max_width
# Allocate a buffer to render into. self._buffer = arrays.GLfloatArray.zeros((max_height, max_width, 4))
def _platform_make_current(self): if self._context: success = osmesa.OSMesaMakeCurrent( self._context, self._buffer, GL.GL_FLOAT, self._width, self._height) if not success: raise RuntimeError('Failed to make OSMesa context current.')
def _platform_free(self): """Frees resources associated with this context.""" if self._context and self._context == osmesa.OSMesaGetCurrentContext(): osmesa.OSMesaMakeCurrent(None, None, GL.GL_FLOAT, 0, 0) osmesa.OSMesaDestroyContext(self._context) self._buffer = None self._context = None12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970# Copyright 2018 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Tests for OSMesaContext."""
import unittest
from absl.testing import absltestfrom dm_control import _renderimport mockfrom OpenGL import GL
MAX_WIDTH = 640MAX_HEIGHT = 480
CONTEXT_PATH = _render.__name__ + '.pyopengl.osmesa_renderer.osmesa'GL_ARRAYS_PATH = _render.__name__ + '.pyopengl.osmesa_renderer.arrays'
@unittest.skipUnless( _render.BACKEND == _render.constants.OSMESA, reason='OSMesa backend not selected.')class OSMesaContextTest(absltest.TestCase):
def test_init(self): mock_context = mock.MagicMock() with mock.patch(CONTEXT_PATH) as mock_osmesa: mock_osmesa.OSMesaCreateContextExt.return_value = mock_context renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT) self.assertIs(renderer._context, mock_context) renderer.free()
def test_make_current(self): mock_context = mock.MagicMock() mock_buffer = mock.MagicMock() with mock.patch(CONTEXT_PATH) as mock_osmesa: with mock.patch(GL_ARRAYS_PATH) as mock_glarrays: mock_osmesa.OSMesaCreateContextExt.return_value = mock_context mock_glarrays.GLfloatArray.zeros.return_value = mock_buffer renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT) with renderer.make_current(): pass mock_osmesa.OSMesaMakeCurrent.assert_called_once_with( mock_context, mock_buffer, GL.GL_FLOAT, MAX_WIDTH, MAX_HEIGHT) renderer.free()
def test_freeing(self): mock_context = mock.MagicMock() with mock.patch(CONTEXT_PATH) as mock_osmesa: mock_osmesa.OSMesaCreateContextExt.return_value = mock_context renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT) renderer.free() mock_osmesa.OSMesaDestroyContext.assert_called_once_with(mock_context) self.assertIsNone(renderer._context)
if __name__ == '__main__': absltest.main()123456789101112131415# Copyright 2017 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126# Copyright 2017 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
r"""Automatically generates ctypes Python bindings for MuJoCo.
Parses the following MuJoCo header files:
mjdata.h mjmodel.h mjrender.h mjui.h mjvisualize.h mjxmacro.h mujoco.h;
generates the following Python source files:
constants.py: constants enums.py: enums sizes.py: size information for dynamically-shaped arrays
Example usage:
autowrap --header_paths='/path/to/mjmodel.h /path/to/mjdata.h ...' \ --output_dir=/path/to/mjbindings"""
import collectionsimport ioimport os
from absl import appfrom absl import flagsfrom absl import loggingfrom dm_control.autowrap import binding_generatorfrom dm_control.autowrap import codegen_util
_MJMODEL_H = "mjmodel.h"_MJXMACRO_H = "mjxmacro.h"
FLAGS = flags.FLAGS
flags.DEFINE_spaceseplist( "header_paths", None, "Space-separated list of paths to MuJoCo header files.")
flags.DEFINE_string("output_dir", None, "Path to output directory for wrapper source files.")
def main(unused_argv): special_header_paths = {}
# Get the path to the mjmodel and mjxmacro header files. # These header files need special handling. for header in (_MJMODEL_H, _MJXMACRO_H): for path in FLAGS.header_paths: if path.endswith(header): special_header_paths[header] = path break if header not in special_header_paths: logging.fatal("List of inputs must contain a path to %s", header)
# Make sure mjmodel.h is parsed first, since it is included by other headers. srcs = codegen_util.UniqueOrderedDict() sorted_header_paths = sorted(FLAGS.header_paths) sorted_header_paths.remove(special_header_paths[_MJMODEL_H]) sorted_header_paths.insert(0, special_header_paths[_MJMODEL_H]) for p in sorted_header_paths: with io.open(p, "r", errors="ignore") as f: srcs[p] = f.read()
# consts_dict should be a codegen_util.UniqueOrderedDict. # This is a temporary workaround due to the fact that the parser does not yet # handle nested `#if define(predicate)` blocks, which results in some # constants being parsed twice. We therefore can't enforce the uniqueness of # the keys in `consts_dict`. As of MuJoCo v1.30 there is only a single problem # block beginning on line 10 in mujoco.h, and a single constant is affected # (MJAPI). consts_dict = collections.OrderedDict()
# These are commented in `mjdata.h` but have no macros in `mjxmacro.h`. hints_dict = codegen_util.UniqueOrderedDict({"buffer": ("nbuffer",), "stack": ("narena",)})
parser = binding_generator.BindingGenerator( consts_dict=consts_dict, hints_dict=hints_dict)
# Parse enums. for pth, src in srcs.items(): if pth is not special_header_paths[_MJXMACRO_H]: parser.parse_enums(src)
# Parse constants and type declarations. for pth, src in srcs.items(): if pth is not special_header_paths[_MJXMACRO_H]: parser.parse_consts_typedefs(src)
# Get shape hints from mjxmacro.h. parser.parse_hints(srcs[special_header_paths[_MJXMACRO_H]])
# Create the output directory if it doesn't already exist. if not os.path.exists(FLAGS.output_dir): os.makedirs(FLAGS.output_dir)
# Generate Python source files and write them to the output directory. parser.write_consts(os.path.join(FLAGS.output_dir, "constants.py")) parser.write_enums(os.path.join(FLAGS.output_dir, "enums.py")) parser.write_index_dict(os.path.join(FLAGS.output_dir, "sizes.py"))
if __name__ == "__main__": flags.mark_flag_as_required("header_paths") flags.mark_flag_as_required("output_dir") app.run(main)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296# Copyright 2017 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Parses MuJoCo header files and generates Python bindings."""
import osimport pprintimport textwrap
from absl import loggingfrom dm_control.autowrap import codegen_utilfrom dm_control.autowrap import header_parsingimport pyparsing
class BindingGenerator: """Parses declarations from MuJoCo headers and generates Python bindings."""
def __init__(self, enums_dict=None, consts_dict=None, typedefs_dict=None, hints_dict=None, index_dict=None): """Constructs a new HeaderParser instance.
The optional arguments listed below can be used to passing in dict-like objects specifying pre-defined declarations. By default empty UniqueOrderedDicts will be instantiated and then populated according to the contents of the headers.
Args: enums_dict: Nested mappings from {enum_name: {member_name: value}}. consts_dict: Mapping from {const_name: value}. typedefs_dict: Mapping from {type_name: ctypes_typename}. hints_dict: Mapping from {var_name: shape_tuple}. index_dict: Mapping from {lowercase_struct_name: {var_name: shape_tuple}}. """ self.enums_dict = (enums_dict if enums_dict is not None else codegen_util.UniqueOrderedDict()) self.consts_dict = (consts_dict if consts_dict is not None else codegen_util.UniqueOrderedDict()) self.typedefs_dict = (typedefs_dict if typedefs_dict is not None else codegen_util.UniqueOrderedDict()) self.hints_dict = (hints_dict if hints_dict is not None else codegen_util.UniqueOrderedDict()) self.index_dict = (index_dict if index_dict is not None else codegen_util.UniqueOrderedDict())
def get_consts_and_enums(self): consts_and_enums = self.consts_dict.copy() for enum in self.enums_dict.values(): consts_and_enums.update(enum) return consts_and_enums
def resolve_size(self, old_size): """Resolves an array size identifier.
The following conversions will be attempted:
* If `old_size` is an integer it will be returned as-is. * If `old_size` is a string of the form `"3"` it will be cast to an int. * If `old_size` is a string in `self.consts_dict` then the value of the constant will be returned. * If `old_size` is a string of the form `"3*constant_name"` then the result of `3*constant_value` will be returned. * If `old_size` is a string that does not specify an int constant and cannot be cast to an int (e.g. an identifier for a dynamic dimension, such as `"ncontact"`) then it will be returned as-is.
Args: old_size: An int or string.
Returns: An int or string. """ if isinstance(old_size, int): return old_size # If it's already an int then there's nothing left to do elif "*" in old_size: # If it's a string specifying a product (such as "2*mjMAXLINEPNT"), # recursively resolve the components to ints and calculate the result. size = 1 sizes = [] is_int = True for part in old_size.split("*"): dim = self.resolve_size(part) sizes.append(dim) if not isinstance(dim, int): is_int = False else: size *= dim if is_int: return size else: return tuple(sizes) else: # Recursively dereference any sizes declared in header macros size = codegen_util.recursive_dict_lookup(old_size, self.get_consts_and_enums()) # Try to coerce the result to an int, return a string if this fails return codegen_util.try_coerce_to_num(size, try_types=(int,))
def get_shape_tuple(self, old_size, squeeze=False): """Generates a shape tuple from parser results.
Args: old_size: Either a `pyparsing.ParseResults`, or a valid int or string input to `self.resolve_size` (see method docstring for further details). squeeze: If True, any dimensions that are statically defined as 1 will be removed from the shape tuple.
Returns: A shape tuple containing ints for dimensions that are statically defined, and string size identifiers for dimensions that can only be determined at runtime. """ if isinstance(old_size, pyparsing.ParseResults): # For multi-dimensional arrays, convert each dimension separately shape = tuple(self.resolve_size(dim) for dim in old_size) else: shape = (self.resolve_size(old_size),) if squeeze: shape = tuple(d for d in shape if d != 1) # Remove singleton dimensions return shape
def resolve_typename(self, old_ctypes_typename): """Gets a qualified ctypes typename from typedefs_dict and C_TO_CTYPES."""
# Recursively dereference any typenames declared in self.typedefs_dict new_ctypes_typename = codegen_util.recursive_dict_lookup( old_ctypes_typename, self.typedefs_dict)
# Try to convert to a ctypes native typename new_ctypes_typename = header_parsing.C_TO_CTYPES.get( new_ctypes_typename, new_ctypes_typename)
if new_ctypes_typename == old_ctypes_typename: logging.warning("Could not resolve typename '%s'", old_ctypes_typename)
return new_ctypes_typename
# Parsing functions. # ----------------------------------------------------------------------------
def parse_hints(self, xmacro_src): """Parses mjxmacro.h, update self.hints_dict.""" parser = header_parsing.XMACRO for tokens, _, _ in parser.scanString(xmacro_src): for xmacro in tokens: if not ( xmacro.name.startswith("MJMODEL") or xmacro.name.startswith("MJDATA") ): continue for member in xmacro.members: if not hasattr(member, "name") or not member.name: continue # "Squeeze out" singleton dimensions. shape = self.get_shape_tuple(member.dims, squeeze=True) self.hints_dict.update({member.name: shape})
if codegen_util.is_macro_pointer(xmacro.name): struct_name = codegen_util.macro_struct_name(xmacro.name) if struct_name not in self.index_dict: self.index_dict[struct_name] = {}
self.index_dict[struct_name].update({member.name: shape})
def parse_enums(self, src): """Parses mj*.h, update self.enums_dict.""" parser = header_parsing.ENUM_DECL for tokens, _, _ in parser.scanString(src): for enum in tokens: members = codegen_util.UniqueOrderedDict() value = 0 for member in enum.members: # Leftward bitshift if member.bit_lshift_a: value = int(member.bit_lshift_a) << int(member.bit_lshift_b) # Assignment elif member.value: value = int(member.value) # Implicit count else: value += 1 members.update({member.name: value}) self.enums_dict.update({enum.name: members})
def parse_consts_typedefs(self, src): """Updates self.consts_dict, self.typedefs_dict.""" parser = (header_parsing.COND_DECL | header_parsing.UNCOND_DECL) for tokens, _, _ in parser.scanString(src): self.recurse_into_conditionals(tokens)
def recurse_into_conditionals(self, tokens): """Called recursively within nested #if(n)def... #else... #endif blocks.""" for token in tokens: # Another nested conditional block if token.predicate: if (token.predicate in self.get_consts_and_enums() and self.get_consts_and_enums()[token.predicate]): self.recurse_into_conditionals(token.if_true) else: self.recurse_into_conditionals(token.if_false) # One or more declarations else: if token.typename: self.typedefs_dict.update({token.name: token.typename}) elif token.value: value = codegen_util.try_coerce_to_num(token.value) # Avoid adding function aliases. if isinstance(value, str): continue else: self.consts_dict.update({token.name: value}) else: self.consts_dict.update({token.name: True})
# Code generation methods # ----------------------------------------------------------------------------
def make_header(self, imports=()): """Returns a header string for an auto-generated Python source file.""" docstring = textwrap.dedent(""" \"\"\"Automatically generated by {scriptname:}.
MuJoCo header version: {mujoco_version:} \"\"\" """.format(scriptname=os.path.split(__file__)[-1], mujoco_version=self.consts_dict["mjVERSION_HEADER"])) docstring = docstring[1:] # Strip the leading line break. return "\n".join([docstring] + list(imports) + ["\n"])
def write_consts(self, fname): """Write constants.""" imports = [ "# pylint: disable=invalid-name", ] with open(fname, "w") as f: f.write(self.make_header(imports)) f.write(codegen_util.comment_line("Constants") + "\n") for name, value in self.consts_dict.items(): f.write("{0} = {1}\n".format(name, value)) f.write("\n" + codegen_util.comment_line("End of generated code"))
def write_enums(self, fname): """Write enum definitions.""" with open(fname, "w") as f: imports = [ "import collections", "# pylint: disable=invalid-name", "# pylint: disable=line-too-long", ] f.write(self.make_header(imports)) f.write(codegen_util.comment_line("Enums")) for enum_name, members in self.enums_dict.items(): fields = ["\"{}\"".format(name) for name in members.keys()] values = [str(value) for value in members.values()] s = textwrap.dedent(""" {0} = collections.namedtuple( "{0}", [{1}] )({2}) """).format(enum_name, ",\n ".join(fields), ", ".join(values)) f.write(s) f.write("\n" + codegen_util.comment_line("End of generated code"))
def write_index_dict(self, fname): """Write file containing array shape information for indexing.""" pp = pprint.PrettyPrinter() output_string = pp.pformat(dict(self.index_dict)) indent = codegen_util.Indenter() imports = [ "# pylint: disable=bad-continuation", "# pylint: disable=line-too-long", ] with open(fname, "w") as f: f.write(self.make_header(imports)) f.write("array_sizes = (\n") with indent: f.write(output_string) f.write("\n)") f.write("\n" + codegen_util.comment_line("End of generated code"))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119# Copyright 2017 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Misc helper functions needed by autowrap.py."""
import collections
_MJXMACRO_SUFFIX = "_POINTERS"
class Indenter: r"""Callable context manager for tracking string indentation levels.
Example usage:
```python idt = Indenter() s = idt("level 0\n") with idt: s += idt("level 1\n") with idt: s += idt("level 2\n") s += idt("level 1 again\n") s += idt("back to level 0\n") print(s) ``` """
def __init__(self, level=0, indent_str=" "): """Initializes an Indenter.
Args: level: The initial indentation level. indent_str: The string used to indent each line. """ self.indent_str = indent_str self.level = level
def __enter__(self): self.level += 1 return self
def __exit__(self, type_, value, traceback): self.level -= 1
def __call__(self, string): return indent(string, self.level, self.indent_str)
def indent(s, n=1, indent_str=" "): """Inserts `n * indent_str` at the start of each non-empty line in `s`.""" p = n * indent_str return "".join((p + l) if l.lstrip() else l for l in s.splitlines(True))
class UniqueOrderedDict(collections.OrderedDict): """Subclass of `OrderedDict` that enforces the uniqueness of keys."""
def __setitem__(self, k, v): existing_v = self.get(k) if existing_v is None: super().__setitem__(k, v) elif v != existing_v: raise ValueError("Key '{}' already exists.".format(k))
def macro_struct_name(name, suffix=None): """Converts mjxmacro struct names, e.g. "MJDATA_POINTERS" to "mjdata".""" if name.startswith("MJMODEL_POINTERS"): return "mjmodel" if suffix is None: suffix = _MJXMACRO_SUFFIX if name.endswith(suffix): return name[:-len(suffix)].lower() return name.lower()
def is_macro_pointer(name): """Returns True if the mjxmacro struct name contains pointer sizes.""" return name.endswith(_MJXMACRO_SUFFIX) or name.startswith("MJMODEL_POINTERS")
def try_coerce_to_num(s, try_types=(int, float)): """Try to coerce string to Python numeric type, return None if empty.""" if not s: return None for try_type in try_types: try: return try_type(s.rstrip("UuFf")) except (ValueError, AttributeError): continue return s
def recursive_dict_lookup(key, try_dict, max_depth=10): """Recursively map dictionary keys to values.""" if max_depth < 0: raise KeyError("Maximum recursion depth exceeded") while key in try_dict: key = try_dict[key] return recursive_dict_lookup(key, try_dict, max_depth - 1) return key
def comment_line(string, width=79, fill_char="-"): """Wraps `string` in a padded comment line.""" return "# {0:{2}^{1}}\n".format(string, width - 2, fill_char)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335# Copyright 2017 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""pyparsing definitions and helper functions for parsing MuJoCo headers."""
import pyparsing as pp
# NB: Don't enable parser memoization (`pp.ParserElement.enablePackrat()`),# since this results in a ~6x slowdown.
NONE = "None"CTYPES_CHAR = "ctypes.c_char"
C_TO_CTYPES = { # integers "int": "ctypes.c_int", "unsigned int": "ctypes.c_uint", "char": CTYPES_CHAR, "unsigned char": "ctypes.c_ubyte", "size_t": "ctypes.c_size_t", # floats "float": "ctypes.c_float", "double": "ctypes.c_double", # pointers "void": NONE,}
CTYPES_PTRS = {NONE: "ctypes.c_void_p"}
CTYPES_TO_NUMPY = { # integers "ctypes.c_int": "np.intc", "ctypes.c_uint": "np.uintc", "ctypes.c_ubyte": "np.ubyte", # floats "ctypes.c_float": "np.float32", "ctypes.c_double": "np.float64",}
# Helper functions for constructing recursive parsers.# ------------------------------------------------------------------------------
def _nested_scopes(opening, closing, body): """Constructs a parser for (possibly nested) scopes.""" scope = pp.Forward() scope << pp.Group( # pylint: disable=expression-not-assigned opening + pp.ZeroOrMore(body | scope)("members") + closing) return scope
def _nested_if_else(if_, pred, else_, endif, match_if_true, match_if_false): """Constructs a parser for (possibly nested) if...(else)...endif blocks.""" ifelse = pp.Forward() ifelse << pp.Group( # pylint: disable=expression-not-assigned if_ + pred("predicate") + pp.ZeroOrMore(match_if_true | ifelse)("if_true") + pp.Optional(else_ + pp.ZeroOrMore(match_if_false | ifelse)("if_false")) + endif) return ifelse
def _nested_ifn_else(ifn_, pred, else_, endif, match_if_true, match_if_false): """Constructs a parser for (possibly nested) if...(else)...endif blocks.""" ifnelse = pp.Forward() ifnelse << pp.Group( # pylint: disable=expression-not-assigned ifn_ + pred("predicate") + pp.ZeroOrMore(match_if_true | ifnelse)("if_false") + pp.Optional(else_ + pp.ZeroOrMore(match_if_false | ifnelse)("if_true")) + endif) return ifnelse
# Some common string patterns to suppress.# ------------------------------------------------------------------------------(LPAREN, RPAREN, LBRACK, RBRACK, LBRACE, RBRACE, SEMI, COMMA, EQUAL, FSLASH, BSLASH) = list(map(pp.Suppress, "()[]{};,=/\\"))X = (pp.Keyword("X") | pp.Keyword("XMJV") | pp.Keyword("XNV")).suppress()EOL = pp.LineEnd().suppress()
# Comments, continuation.# ------------------------------------------------------------------------------COMMENT = pp.Combine( pp.Suppress("//") + pp.Optional(pp.White()).suppress() + pp.SkipTo(pp.LineEnd()))
MULTILINE_COMMENT = pp.delimitedList( COMMENT.copy().setWhitespaceChars(" \t"), delim=EOL)
CONTINUATION = (BSLASH + pp.LineEnd()).suppress()
# Preprocessor directives.# ------------------------------------------------------------------------------DEFINE = pp.Keyword("#define").suppress()IFDEF = pp.Keyword("#ifdef").suppress()IFNDEF = pp.Keyword("#ifndef").suppress()ELSE = pp.Keyword("#else").suppress()ENDIF = pp.Keyword("#endif").suppress()
# Variable names, types, literals etc.# ------------------------------------------------------------------------------NAME = pp.Word(pp.alphanums + "_")INT = pp.Word(pp.nums + "UuLl")FLOAT = pp.Word(pp.nums + ".+-EeFf")NUMBER = FLOAT | INT
# Dimensions can be of the form `[3]`, `[constant_name]` or `[2*constant_name]`ARRAY_DIM = pp.Combine( LBRACK + (INT | NAME) + pp.Optional(pp.Literal("*")) + pp.Optional(INT | NAME) + RBRACK)
PTR = pp.Literal("*")EXTERN = pp.Keyword("extern")NATIVE_TYPENAME = pp.MatchFirst([pp.Keyword(n) for n in C_TO_CTYPES.keys()])
# Macros.# ------------------------------------------------------------------------------
HDR_GUARD = DEFINE + "THIRD_PARTY_MUJOCO_HDRS_"
# e.g. "#define mjUSEDOUBLE"DEF_FLAG = pp.Group( DEFINE + NAME("name") + (COMMENT("comment") | EOL)).ignore(HDR_GUARD)
# e.g. "#define mjMINVAL 1E-14 // minimum value in any denominator"DEF_CONST = pp.Group( DEFINE + NAME("name") + (NUMBER | NAME)("value") + (COMMENT("comment") | EOL))
# e.g. "X( mjtNum*, name_textadr, ntext, 1 )"XDIM = pp.delimitedList( ( pp.Suppress(pp.Keyword("MJ_M") + LPAREN) + NAME + pp.Suppress(RPAREN) ) | NAME | INT, delim="*", combine=True)XMEMBER = pp.Group( X + LPAREN + (NATIVE_TYPENAME | NAME)("typename") + pp.Optional(PTR("ptr")) + COMMA + NAME("name") + COMMA + pp.delimitedList(XDIM, delim=COMMA)("dims") + RPAREN)
XMACRO_LINE = XMEMBER | NAMEXMACRO = pp.Group( pp.Optional(COMMENT("comment")) + DEFINE + NAME("name") + CONTINUATION + pp.delimitedList(XMACRO_LINE, delim=CONTINUATION)("members"))
# Type/variable declarations.# ------------------------------------------------------------------------------TYPEDEF = pp.Keyword("typedef").suppress()STRUCT = pp.Keyword("struct")UNION = pp.Keyword("union")ENUM = pp.Keyword("enum").suppress()
# e.g. "typedef unsigned char mjtByte; // used for true/false"TYPE_DECL = pp.Group( TYPEDEF + pp.Optional(STRUCT) + (NATIVE_TYPENAME | NAME)("typename") + pp.Optional(PTR("ptr")) + NAME("name") + SEMI + pp.Optional(COMMENT("comment")))
# Declarations of flags/constants/types.UNCOND_DECL = DEF_FLAG | DEF_CONST | TYPE_DECL
# Declarations inside (possibly nested) #if(n)def... #else... #endif... blocks.COND_DECL = _nested_if_else( IFDEF, NAME, ELSE, ENDIF, UNCOND_DECL, UNCOND_DECL) | _nested_ifn_else(IFNDEF, NAME, ELSE, ENDIF, UNCOND_DECL, UNCOND_DECL)# Note: this doesn't work for '#if defined(FLAG)' blocks
# e.g. "mjtNum gravity[3]; // gravitational acceleration"STRUCT_MEMBER = pp.Group( pp.Optional(STRUCT("struct")) + (NATIVE_TYPENAME | NAME)("typename") + pp.Optional(PTR("ptr")) + NAME("name") + pp.ZeroOrMore(ARRAY_DIM)("size") + SEMI + pp.Optional(COMMENT("comment")))
# Struct declaration within a union (non-nested).UNION_STRUCT_DECL = pp.Group( STRUCT("struct") + pp.Optional(NAME("typename")) + pp.Optional(COMMENT("comment")) + LBRACE + pp.OneOrMore(STRUCT_MEMBER)("members") + RBRACE + pp.Optional(NAME("name")) + SEMI)
ANONYMOUS_UNION_DECL = pp.Group( pp.Optional(MULTILINE_COMMENT("comment")) + UNION("anonymous_union") + LBRACE + pp.OneOrMore( UNION_STRUCT_DECL | STRUCT_MEMBER | COMMENT.suppress())("members") + RBRACE + SEMI)
# Multiple (possibly nested) struct declarations.NESTED_STRUCTS = _nested_scopes( opening=(STRUCT + pp.Optional(NAME("typename")) + pp.Optional(COMMENT("comment")) + LBRACE), closing=(RBRACE + pp.Optional(NAME("name")) + SEMI), body=pp.OneOrMore( STRUCT_MEMBER | ANONYMOUS_UNION_DECL | COMMENT.suppress())("members"))
BIT_LSHIFT = INT("bit_lshift_a") + pp.Suppress("<<") + INT("bit_lshift_b")
ENUM_LINE = pp.Group( NAME("name") + pp.Optional(EQUAL + (INT("value") ^ BIT_LSHIFT)) + pp.Optional(COMMA) + pp.Optional(COMMENT("comment")))
ENUM_DECL = pp.Group( TYPEDEF + ENUM + NAME("typename") + pp.Optional(COMMENT("comment")) + LBRACE + pp.OneOrMore(ENUM_LINE | COMMENT.suppress())("members") + RBRACE + pp.Optional(NAME("name")) + SEMI)
# Function declarations.# ------------------------------------------------------------------------------MJAPI = pp.Keyword("MJAPI").suppress()CONST = pp.Keyword("const")VOID = pp.Group(pp.Keyword("void") + ~PTR).suppress()
ARG = pp.Group( pp.Optional(CONST("is_const")) + (NATIVE_TYPENAME | NAME)("typename") + pp.Optional(PTR("ptr")) + NAME("name") + pp.Optional(ARRAY_DIM("size")))
RET = pp.Group( pp.Optional(CONST("is_const")) + (NATIVE_TYPENAME | NAME)("typename") + pp.Optional(PTR("ptr")))
FUNCTION_DECL = ( (VOID | RET("return_value")) + NAME("name") + LPAREN + (VOID | pp.delimitedList(ARG, delim=COMMA)("arguments")) + RPAREN + SEMI)
MJAPI_FUNCTION_DECL = pp.Group( pp.Optional(MULTILINE_COMMENT("comment")) + pp.LineStart() + MJAPI + FUNCTION_DECL)
# e.g.# // predicate function: set enable/disable based on item category# typedef int (*mjfItemEnable)(int category, void* data);FUNCTION_PTR_TYPE_DECL = pp.Group( pp.Optional(MULTILINE_COMMENT("comment")) + TYPEDEF + RET("return_type") + LPAREN + PTR + NAME("typename") + RPAREN + LPAREN + (VOID | pp.delimitedList(ARG, delim=COMMA)("arguments")) + RPAREN + SEMI)
# Global variables.# ------------------------------------------------------------------------------
MJAPI_STRING_ARRAY = ( MJAPI + EXTERN + CONST + pp.Keyword("char") + PTR + NAME("name") + pp.OneOrMore(ARRAY_DIM)("dims") + SEMI)
MJAPI_FUNCTION_PTR = MJAPI + EXTERN + NAME("typename") + NAME("name") + SEMI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229# Copyright 2023 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Fake Blender bpy module."""
from __future__ import annotations # postponed evaluation of annotations
from typing import Any, Collection, Sequence
from dm_control.blender.fake_core import mathutils
# pylint: disable=invalid-name# pylint: disable=missing-class-docstring
class WindowManager:
def progress_begin(self, start: int, end: int): pass
def progress_update(self, steps_done: int): pass
def progress_end(self): pass
class context:
@property def window_manager(self) -> WindowManager: return WindowManager()
@staticmethod def evaluated_depsgraph_get(): pass
class types:
class Constraint:
@property def name(self): pass
@property def owner_space(self): pass
class Scene: pass
class Object:
@property def name(self) -> str: raise NotImplementedError()
@property def parent(self) -> types.Object | None: pass
@property def parent_bone(self) -> types.Bone | None: pass
@property def data(self): pass
@property def pose(self): pass
@property def matrix_world(self) -> mathutils.Matrix: raise NotImplementedError()
@matrix_world.setter def matrix_world(self, _) -> mathutils.Matrix: raise NotImplementedError()
def select_set(self, _): pass
def to_mesh(self): pass
def evaluated_get(self, _) -> types.Object: pass
@property def mode(self) -> str: return 'OBJECT'
@property def type(self): pass
def update_from_editmode(self): pass
class Bone:
@property def name(self) -> str: raise NotImplementedError()
@property def parent(self) -> types.Bone | None: pass
@property def matrix_local(self) -> mathutils.Matrix: raise NotImplementedError()
@property def matrix(self) -> mathutils.Matrix: raise NotImplementedError()
class bpy_struct: pass
class Context:
@property def scene(self) -> types.Scene: pass
class Light:
@property def type(self): pass
@property def use_shadow(self): pass
@property def color(self) -> mathutils.Color: raise NotImplementedError()
@property def linear_attenuation(self): pass
@property def quadratic_attenuation(self): pass
class LimitRotationConstraint(Constraint): pass
class LimitLocationConstraint(Constraint): pass
class Material:
@property def name(self) -> str: raise NotImplementedError()
@property def specular_intensity(self): pass
@property def metallic(self): pass
@property def roughness(self) -> float: raise NotImplementedError()
@property def diffuse_color(self) -> Sequence[float]: raise NotImplementedError()
class Mesh:
@property def name(self) -> str: raise NotImplementedError()
def calc_loop_triangles(self): pass
@property def uv_layers(self) -> Any: raise NotImplementedError()
@property def loop_triangles(self) -> Collection[Any]: raise NotImplementedError()
@property def vertices(self) -> Any: raise NotImplementedError()
class ops:
class object:
@staticmethod def select_all(action): pass
class export_mesh:
@classmethod def stl( cls, filepath, use_selection, use_mesh_modifiers, axis_forward, axis_up ): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123# Copyright 2023 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Fake Blender mathutils module."""# pylint: disable=invalid-name
import numpy as np
class Color: """Fake color class."""
def __init__(self, coords): self._coords = coords
@property def r(self) -> float: return self._coords[0]
@property def g(self) -> float: return self._coords[1]
@property def b(self) -> float: return self._coords[2]
@property def a(self) -> float: return self._coords[3]
class Vector: """Fake vector class."""
def __init__(self, coords): self._coords = np.asarray(coords)
@property def x(self) -> float: return self._coords[0]
@property def y(self) -> float: return self._coords[1]
@property def z(self) -> float: return self._coords[2]
@property def w(self) -> float: return self._coords[3]
def __eq__(self, rhs) -> bool: if not isinstance(rhs, Vector): return False return np.linalg.norm(self._coords - rhs._coords) < 1e-6
def __str__(self) -> str: return 'Vector({:.2f}, {:.2f}, {:.2f})'.format(self.x, self.y, self.z)
def __repr__(self) -> str: return 'Vector({:.2f}, {:.2f}, {:.2f})'.format(self.x, self.y, self.z)
class Quaternion: """Fake quaternion class."""
def __init__(self, coords): self._coords = coords
@property def x(self) -> float: return self._coords[1]
@property def y(self) -> float: return self._coords[2]
@property def z(self) -> float: return self._coords[3]
@property def w(self) -> float: return self._coords[0]
def __matmul__(self, rhs: Vector) -> Vector: return Vector((1, 0, 0))
class Matrix: """Fake matrix class."""
def __init__(self, coords): self._coords = coords
@classmethod def Diagonal(cls, _): return cls((1,))
@property def translation(self) -> Vector: return Vector((0.0, 0.0, 0.0))
def to_quaternion(self) -> Quaternion: return Quaternion((1.0, 0.0, 0.0, 0.0))
def to_scale(self) -> Vector: return Vector((0.0, 0.0, 0.0))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213# Export Mujoco models from Blender
## Prerequisites
The MuJoCo exporter works as Blender addon, tested with ver 3.4.1. You candownload Blender from [https://www.blender.org](https://www.blender.org/).
## Installation
### Preparing a plugin installer
The `install.sh` command will deploy the installable version of the plugin to`./addons/mujoco_model_exporter`. This folder should be zipped:
```shell$ cd ./addons && zip -r mujoco_model_exporter.zip mujoco_model_exporter/*```
### Installing the plugin in Blender
Open Blender and select `Edit/Preferences` menu option.
{style="display:block;margin:auto"}
Clicking the Install button will open a file selection dialog that will allowyou to select the .zip archive with the plugin.
The next window will follow, listing the installed plugin and allowing you toenable it.
{style="display:block;margin:auto"}
Check the checkbox next to its name to enable it.
## Modelling for Mujoco.
The plugin was designed to allow the artists to keep using core Blender featureswhen building models for Mujoco.
feature | Mujoco | Blender-------------- | ------------------------- | -----------------------------------kinematic tree | hierarchy of Bodies | Armatures or hierarchies of Objectsgeometry | Geoms | Meshesmaterials | Material + Texture assets | Material + Texture definitionslighting | Lights | Lights
### Node naming
The exporter will copy the names of the bones, meshes and lights. Mujoco jointswill be named after the bone that owns the respective constraint, with a postfixdenoting the degree of freedom they enable.
### Modelling kinematic trees using Armatures and IK
Blender Armatures allow to model kinematic capabilities of a Blender model. Theycomprise a tree of bones, each of which can be further extended with IKConstraints.
Only the bones affected by an IK chain will receive appropriate degrees offreedom. This means that if you export a model without any IK chains, it will beexported as a static model.
#### IK Constraints and bone limits
IK constraints offer the easiest way to verify how a kinematic chain wouldbehave in a physical environment. For that reason we chose to use them, alongwith IK bone limits, to model Mujoco joints.

* Select the bone at the end of a kinematic chain,

* Add an IK Bone Constraint to it. [This webpage](https://docs.blender.org/manual/en/latest/animation/constraints/tracking/ik_solver.html) contains detailed instructions.

* Add a target bone to the scene and use it as the IK constraint's target.

* Adjust the `Chain Length` value to reflect the number of parent bones that should become a part of this IK chain.

* For each of the bones in the chain, visit the `Bone/Inverse Kinematics` tab and adjust the locks and bone limits.

*NOTE*: you can take advantage of a helpful limit visualization gizmo.
### Armature free joints.
Armatures form the kinematic trees, so it makes sense to give their roots all 6degrees of freedom.
This behavior can be changed by disabling the `Armature freejoint` exportoption.
### Modelling the geometry
Mujoco uses parametric geometry comprised of primitive shapes suchas cubes, spheres and capsules. It does support triangle based mesh geometryhowever.
Blender on the other hand deals exclusively in meshes, and even though itcontains a palette of such primitive shapes, these are not parametric.
#### MSH files
The exporter therefore exports the geometry as meshes. All meshes referenced bythe scene are exported into Mujoco's native .msh format.
When this plugin was created, the native .msh format was the only format tosupport texture mapping. Since MuJoCo 2.1.2, `.obj` files are supported. The`.msh` format is expected to be deprecated and removed soon. Until this pluginis updated to output `.obj` files we recommend all user to convert their `.msh`files to `.obj` files using [this](https://github.com/google-deepmind/mujoco/blob/main/python/mujoco/msh2obj.py) utility.
#### Phong lighting model and lack of support for Cycles nodes
Mujoco implements a forward rendering model with Phong lightning and support forreflective surfaces.
[Mujoco material definition](http://www.mujoco.org/book/XMLreference.html#material)is fixed and limited to:
* base color (diffuse color)* specularity coefficient* smoothness coefficient* reflectiveness coefficient
These parameters translate well to Blender's default material definition, whichshould be used to model the materials exported to Mujoco.
Due to the diversity and open-ended nature of Cycle's material nodes, the choicewas made not to support materials defined using them.
#### Division of meshes that employ multiple materials
Mujoco renderer supports a single material per mesh, in contrast to Blender'smulti material model. In order to support meshes with multiple materials, theexporter divides them into submeshes, each of which uses a single material.
Since Blender materials are applied to faces, and a single face may only have asingle material assigned, there is no risk that the subdivided mesh will exhibitany overlapping artifacts.
#### Effect of mesh division on inertia and mass.
The exported submeshes will have different geometry and volume than theoriginal. This will affect the mass and inertia of the geom that uses theexported mesh.
Please note that Mujoco derives these quantities not from the mesh itself, butrather from the convex hull calculated for it. The sum of hulls of subdividedmeshes are not guaranteed to be equal to the hull of the original mesh.
This phenomenon is illustrated on the image below.
Blender | Mujoco renderer | Mujoco convex hulls----------------------------- | ------------------------------- | ------------------- |  | 
A different material was assigned to 2 out of 6 rectangular faces of the rightcube, causing that mesh to be split into two submeshes.
While they render well in Mujoco, the Moiré effect visible on the convex hullcomes from two overlapping hulls, each with a different volume.
#### Double-sided materials
Double sided materials cause the meshes (or faces) that use them to be exportedwith the faces duplicated with the reverse face winding order. This is becauseMujoco renderer does not support any other face culling modes than back faceculling.
*CAUTION*: Because this operation affects the exported geometry, it mayindirectly affect the physical properties of a geom that references that mesh,such as its mass and inertia. Please use this feature with caution.
#### Scaling
*CAUTION*: If you are using the scaling transform, the exporter will modify yourscene!
The exporter will by default reset the scaling transform on all bones and meshesto ensure affine reference frame transformations.
This operation can be undo'ed after the exporter is completed, but the exporterdoesn't undo it automatically!
### Textures
*NOTE*: This feature will be added in the next version of the exporter.
#### One texture channel
Mujoco renderer supports a single texture channel. It's therefore advised to usea single UV map for meshes that are to be exported to Mujoco.
#### Choice between atlases and individual textures
Mujoco's fixed rendering pipeline is quite fast, and handles both variants well.Therefore we leave it up to the artist to decide which it prefers using.
Please keep in mind that the exporter doesn't export the texture assets. Thoseshould be copied into the folder with the exported model manually.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170# Copyright 2023 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Blender 3.4 plugin for exporting models to MuJoCo native format."""
import contextlibimport osfrom xml.dom import minidom
import bpyfrom bpy_extras.io_utils import ExportHelper
from . import blender_scenefrom . import mujoco_assetsfrom . import mujoco_scene
bl_info = { 'name': 'Export MuJoCo', 'author': 'The dm_control authors', 'version': (2, 0), 'blender': (3, 3, 1), 'location': 'File > Export > MuJoCo', 'warning': '', 'description': 'Export articulated MuJoCo model', 'doc_url': '', 'category': 'Import-Export',}
@contextlib.contextmanagerdef context_settings_cacher(context: bpy.types.Context): """Preserves the pose of exported objects and the scene mode.""" # Cache the mode prev_mode = context.mode
# Set the Object mode required by the exporter bpy.ops.object.mode_set(mode='OBJECT')
# Set the armatures in their neutral pose pose_positions = [] for o in context.scene.objects: if o.type == 'ARMATURE': pose_positions.append((o, o.data.pose_position)) o.data.pose_position = 'REST' context.view_layer.update()
try: yield finally: # Restore the poses. for armature, pose_position in pose_positions: armature.data.pose_position = pose_position context.view_layer.update()
# Restore the mode bpy.ops.object.mode_set(mode=prev_mode)
def apply_scale(): bpy.ops.object.select_all(action='SELECT') bpy.ops.object.transform_apply(location=False, scale=True, rotation=False) bpy.ops.object.select_all(action='DESELECT')
class ExportMjcf(bpy.types.Operator, ExportHelper): """Export to MJCF file format."""
bl_idname = 'export_scene.mjcf' bl_label = 'Export MJCF'
filename_ext = '.xml' filter_glob = bpy.props.StringProperty(default='*.xml', options={'HIDDEN'})
# Export settings armature_freejoint: bpy.props.BoolProperty( name='Armature freejoint', description='Add a freejoint to armature body', default=False, ) apply_mesh_modifiers: bpy.props.BoolProperty( name='Apply modifiers', description='Apply mesh modifiers', default=False, )
def _export_mjcf(self, context: bpy.types.Context) -> None: """Converts a Blender scene to Mujoco XML format.""" # Create a new XML document xml_doc = minidom.Document() mujoco = xml_doc.createElement('mujoco') xml_doc.appendChild(mujoco)
# Create a list of blender objects, arranged according to their hierarchy, # where parents precede the children. blender_objects = blender_scene.map_blender_tree( context, lambda o: o if o.is_visible else None ) # Remove None entries that correspond to invisible objects. blender_objects = [o for o in blender_objects if o]
export_settings = self.as_keywords()
# Build the scene tree worldbody_el = mujoco_scene.export_to_xml( doc=xml_doc, objects=blender_objects, armature_freejoint=export_settings['armature_freejoint'], ) mujoco.appendChild(worldbody_el)
# Build the asset tree asset_el = mujoco_assets.export_to_xml( doc=xml_doc, objects=blender_objects, folder=os.path.dirname(export_settings['filepath']), apply_mesh_modifiers=export_settings['apply_mesh_modifiers'], ) mujoco.appendChild(asset_el)
# Add compiler options that would allow to export small feature meshes. compiler_el = xml_doc.createElement('compiler') mujoco.appendChild(compiler_el) compiler_el.setAttribute('boundmass', '1e-3') compiler_el.setAttribute('boundinertia', '1e-9') # TODO(b/266818670): support assets export into subdirectory # compiler_el.setAttribute('meshdir', 'assets')
# Write the XML to a file. with open(export_settings['filepath'], 'w') as file: file.write(xml_doc.toprettyxml(indent=' '))
def execute(self, context: bpy.types.Context): """Export the scene.""" with context_settings_cacher(context): apply_scale() self._export_mjcf(context)
return {'FINISHED'}
def menu_func_export(self, context: bpy.types.Context): del context self.layout.operator(ExportMjcf.bl_idname, text='MuJoCo (.xml)')
def register(): bpy.utils.register_class(ExportMjcf) bpy.types.TOPBAR_MT_file_export.append(menu_func_export)
def unregister(): bpy.utils.unregister_class(ExportMjcf) bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)
if __name__ == '__main__': register()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428# Copyright 2023 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Blender scene parsers."""
# disable: pytype=strict-noneimport dataclassesimport mathfrom typing import Any, Callable, Sequence, Tuple, cast
from dm_control.blender.fake_core import bpyfrom dm_control.blender.fake_core import mathutils
_ARMATURE = 'ARMATURE'_CAMERA = 'CAMERA'_EMPTY = 'EMPTY'_LIGHT = 'LIGHT'_MESH = 'MESH'_VEC_ZERO = mathutils.Vector((0, 0, 0))_OX = mathutils.Vector((1, 0, 0))_OY = mathutils.Vector((0, 1, 0))_OZ = mathutils.Vector((0, 0, 1))
def _check_that_parent_bone_exists(obj: bpy.types.Object) -> None: """Checks if the bone the object was supposed to be parented exists.""" assert obj is not None if obj.parent is None: raise ValueError( 'Armature object "{}" was parented to does not exist'.format(obj.name) )
armature = obj.parent if armature.type != _ARMATURE: raise ValueError( 'Parent of object "{}" - "{}", is not an armature, but a "{}"'.format( obj.name, armature.name, armature.type ) )
if obj.parent_bone not in armature.data.bones: raise ValueError( 'Object "{}" is parented to a non-existing bone "{}" from ' 'armature "{}"'.format(obj.name, obj.parent_bone, armature.name) )
def _check_constraint_in_local_space( constraint: bpy.types.Constraint, owner: 'ObjectRef') -> None: if constraint and constraint.owner_space != 'LOCAL': raise ValueError( 'Constraint "{}" (bone "{}", armature "{}") uses an unsupported ' 'owner_mode "{}". Only "LOCAL" mode is supported at the ' 'moment'.format( type(constraint), owner.bone_name(), owner.obj_name(), constraint.owner_space, ) )
def _angle_distance(lhs_deg: float, rhs_deg: float) -> float: """Calculates distance between two angles, in degrees.""" x_2 = math.cos(math.radians(lhs_deg)) * math.cos(math.radians(rhs_deg)) y_2 = math.sin(math.radians(lhs_deg)) * math.sin(math.radians(rhs_deg)) return math.degrees(math.acos(x_2 + y_2))
@dataclasses.dataclass(frozen=True)class AffineTransform: pos: mathutils.Vector rot: mathutils.Quaternion
@dataclasses.dataclass(frozen=True)class Dof: """Degree of freedom description."""
name: str axis: mathutils.Vector limited: bool = False limits: Tuple[float, float] = (0, 0)
@dataclasses.dataclass(frozen=True)class ObjectRef: """References a Blender object, be that a scene object or a bone.
Object reference is hashable and comparable. Equality is based on the names of the underlying objects. Blender's API guarantees that a combination of object/bone name will be unique across the scene. We're leveraging that rule. """
native_obj: bpy.types.Object | None native_bone: bpy.types.Bone | None = None
def __hash__(self) -> int: return hash(self.name)
def __eq__(self, rhs) -> bool: if not isinstance(rhs, ObjectRef): return False return self.name == rhs.name
@property def is_none(self) -> bool: return self.native_bone is None
@property def is_armature(self) -> bool: return ( # pytype: disable=bad-return-type self.native_obj and self.native_obj.type == _ARMATURE and not self.native_bone )
@property def is_bone(self) -> bool: return bool( self.native_obj and self.native_obj.type == _ARMATURE and self.native_bone )
@property def is_mesh(self) -> bool: return self.native_obj and self.native_obj.type == _MESH # pytype: disable=bad-return-type
@property def is_light(self) -> bool: return self.native_obj and self.native_obj.type == _LIGHT # pytype: disable=bad-return-type
@property def is_camera(self) -> bool: return self.native_obj and self.native_obj.type == _CAMERA # pytype: disable=bad-return-type
@property def is_empty(self) -> bool: return self.native_obj and self.native_obj.type == _EMPTY # pytype: disable=bad-return-type
@property def name(self) -> str: if not self.native_obj: return '' if self.native_bone: return '{}_{}'.format(self.native_bone.name, self.native_obj.name) else: return self.native_obj.name
def as_light(self) -> bpy.types.Light: return cast(bpy.types.Light, self.obj_data())
def get_local_transform(self) -> AffineTransform: """Returns a transform wrt. the local reference frame."""
def get_bone_local_mtx(bone: bpy.types.Bone) -> mathutils.Matrix: """Derives a local matrix of an armature bone.""" assert isinstance(bone, bpy.types.Bone) if bone.parent: return bone.parent.matrix_local.inverted() @ bone.matrix_local else: return bone.matrix_local
def get_object_local_mtx(obj: bpy.types.Object) -> mathutils.Matrix: """Derives a local matrix of an object, such as a mesh or armature.""" assert isinstance(obj, bpy.types.Object) if obj.parent: local_mtx = obj.parent.matrix_world.inverted() @ obj.matrix_world if obj.parent_bone: assert obj.parent.type == _ARMATURE armature = obj.parent bone = armature.data.bones[obj.parent_bone] return bone.matrix_local.inverted() @ local_mtx else: return local_mtx else: return obj.matrix_world
if self.is_bone: local_mtx = get_bone_local_mtx(self.native_bone) else: local_mtx = get_object_local_mtx(self.native_obj)
rot_quat = local_mtx.to_quaternion() pos = local_mtx.translation return AffineTransform(pos, rot_quat)
@property def is_visible(self) -> bool: """Checks if an object is visible.""" if not self.native_obj: return False if hasattr(self.native_obj, 'visible_get'): return self.native_obj.visible_get() else: return True
@property def parent(self) -> 'ObjectRef': """Returns a reference to the parent of this object.""" if self.native_obj is None: return ObjectRef(None)
def bone_parent( armature: bpy.types.Object, bone: bpy.types.Bone ) -> 'ObjectRef': if bone.parent: # Parent of a child bone is its parent bone in the same armature assert isinstance(bone.parent, bpy.types.Bone) return ObjectRef.new_bone(armature, bone.parent) else: # Parent of the root bone is the armature. return ObjectRef.new_object(armature)
def object_parent(obj: bpy.types.Object) -> 'ObjectRef': if obj.parent_bone: # The object is parented to an armature, and the .parent field must # contain a reference the armature. assert obj.parent and obj.parent.type == _ARMATURE _check_that_parent_bone_exists(obj) armature = obj.parent parent_bone = armature.data.bones[obj.parent_bone] return ObjectRef.new_bone(armature, parent_bone) elif obj.parent: # The object is parented to another object. return ObjectRef.new_object(obj.parent) else: # This is a root object return ObjectRef(None)
if self.native_bone: return bone_parent(self.native_obj, self.native_bone) else: return object_parent(self.native_obj)
def get_rotation_dofs(self) -> Sequence[Dof]: """Returns the rotation degrees of freedom in the subtractive mode.
The method returns the degrees of freedom present from the point of view of Blender. These are modeled such that in absence of constraints, all degrees of freedom are present.
Returns: A sequence of degree of freedom definitions. """ if not self.is_bone: raise ValueError( 'Rotation degrees of freedom are defined only for bones.' ) assert self.native_obj assert self.native_obj.type == _ARMATURE armature = self.native_obj bone = armature.pose.bones[self.native_bone.name] if not bone.is_in_ik_chain: # Bones not in an IK chain don't receive any degrees of freedom. return []
is_locked = [bone.lock_ik_x, bone.lock_ik_y, bone.lock_ik_z] use_limits = [bone.use_ik_limit_x, bone.use_ik_limit_y, bone.use_ik_limit_z] limits = [ (math.degrees(bone.ik_min_x), math.degrees(bone.ik_max_x)), (math.degrees(bone.ik_min_y), math.degrees(bone.ik_max_y)), (math.degrees(bone.ik_min_z), math.degrees(bone.ik_max_z)), ] axes = [_OX, _OY, _OZ] names = [ 'rx_{}'.format(self.name), 'ry_{}'.format(self.name), 'rz_{}'.format(self.name), ] axis_names = ['X', 'Y', 'Z']
def build_dof(idx): if limits[idx][0] >= limits[idx][1]: raise ValueError( 'Bone "{}" uses incorrect IK limits for {} axis. ' '{} < {} is violated'.format( self.name, axis_names[idx], limits[idx][0], limits[idx][1] ) ) return Dof( name=names[idx], axis=axes[idx], limited=use_limits[idx], limits=limits[idx], )
return [build_dof(i) for i in range(3) if not is_locked[i]]
def obj_data(self) -> bpy.types.Object | None: if self.native_obj is not None: return self.native_obj.data else: return None
def obj_name(self) -> str | None: if self.native_obj is not None: return self.native_obj.name else: return None
def bone_name(self) -> str | None: if self.native_bone is not None: return self.native_bone.name else: return None
@property def mesh(self) -> bpy.types.Mesh: """Returns the mesh associated with this object.""" assert self.is_mesh return cast(bpy.types.Mesh, self.obj_data())
def get_modified_mesh(self) -> bpy.types.Mesh | None: """Returns a mesh with modifiers applied to it.""" assert self.is_mesh assert self.native_obj is not None if self.native_obj.mode == 'EDIT': self.native_obj.update_from_editmode()
# get the modifiers depsgraph = bpy.context.evaluated_depsgraph_get() mesh_owner = self.native_obj.evaluated_get(depsgraph)
return mesh_owner.to_mesh()
@property def materials(self) -> Sequence[bpy.types.Material]: """Returns the materials assigned to this object.""" data = self.obj_data() if hasattr(data, 'materials'): return data.materials else: return []
@classmethod def new_object(cls, obj: bpy.types.Object) -> 'ObjectRef': assert isinstance(obj, bpy.types.Object) or obj is None return cls(obj)
@classmethod def new_bone( cls, armature: bpy.types.Object, bone: bpy.types.Bone | None, ) -> 'ObjectRef': assert isinstance(armature, bpy.types.Object) assert armature.type == _ARMATURE assert isinstance(bone, bpy.types.Bone) or bone is None return cls(armature, bone)
NoneRef = ObjectRef(None, None)
def map_blender_tree( context: bpy.types.Context, callback: Callable[[ObjectRef], Any]) -> Sequence[Any]: """Returns a list of scene objects in the breadth-first order.""" # Collect all nodes to explore - objects and bones alike assert context.scene is not None to_explore = [ObjectRef.new_object(o) for o in context.scene.objects] armatures = [o for o in context.scene.objects if o.type == 'ARMATURE'] for armature in armatures: for bone in armature.data.bones: to_explore.append(ObjectRef.new_bone(armature, bone))
explored = set() explored.add(NoneRef) result = []
while to_explore: obj_ref: ObjectRef = to_explore[0] to_explore = to_explore[1:]
if obj_ref.parent in explored: explored.add(obj_ref) result.append(callback(obj_ref)) else: to_explore.append(obj_ref)
return result
def get_material_mesh_pair_name(mesh_name: str, mat_name: str) -> str: """Build the name for a mesh-material pair.""" return '{}_{}'.format(mesh_name, mat_name) if mat_name else mesh_name
def is_material_mesh_pair_valid(mesh: bpy.types.Mesh, mat_idx: int) -> bool: """Tests the mesh-material pair whether it contains any geometry.""" mesh.calc_loop_triangles() faces = [f for f in mesh.loop_triangles if f.material_index == mat_idx] return bool(faces)
def map_materials( func: Callable[[bpy.types.Material], Any], materials: Sequence[bpy.types.Material],) -> Sequence[Any]: """Maps a collection of materials, adjusting for empty collections.
In case of an empty collection, a substitute for a default material is passed to the mapping callback.
Args: func: Mapping callback. materials: Collection of materials.
Returns: An arbitrary collection of data mapped out of the materials collection. """ materials = materials or [] return [func(material) for material in materials]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244# Copyright 2023 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Tests for blender_scene.py."""
import mathfrom unittest import mockfrom absl.testing import absltestfrom absl.testing import parameterizedfrom dm_control.blender.fake_core import bpyfrom dm_control.blender.fake_core import mathutilsfrom dm_control.blender.mujoco_exporter import blender_scenefrom dm_control.blender.mujoco_exporter import testingimport numpy as np
class AngleDistanceTest(parameterized.TestCase):
@parameterized.parameters([ [0, 0, 0], [90, 90, 0], [-90, -90, 0], [-90, 0, 90], [0, 90, 90], [-90, 90, 180], [-180, 180, 0], [-270, 90, 0], [-90, 270, 0], [-90, 360, 90], ]) def test_angle_distance(self, lhs, rhs, result): self.assertAlmostEqual(blender_scene._angle_distance(lhs, rhs), result, 2)
class ObjectRefTest(absltest.TestCase):
def test_hashing_and_comparison(self): mesh_a = blender_scene.ObjectRef.new_object( testing.build_mesh_object('mesh_a') ) mesh_a_copy = blender_scene.ObjectRef.new_object( testing.build_mesh_object('mesh_a') ) mesh_b = blender_scene.ObjectRef.new_object( testing.build_mesh_object('mesh_b') )
self.assertEqual(hash(mesh_a), hash(mesh_a_copy)) self.assertNotEqual(hash(mesh_a), hash(mesh_b))
self.assertEqual(mesh_a, mesh_a_copy) self.assertNotEqual(mesh_a, mesh_b)
def test_parent_of_root_object_is_noneref(self): obj_ref = blender_scene.ObjectRef.new_object( testing.build_mesh_object('mesh') ) self.assertEqual(obj_ref.parent, blender_scene.NoneRef)
def test_parent_of_object_parented_to_another_object(self): parent_obj = testing.build_mesh_object('parent_obj') child_obj = testing.build_mesh_object('child_obj', parent=parent_obj)
parent_ref = blender_scene.ObjectRef.new_object(parent_obj) child_ref = blender_scene.ObjectRef.new_object(child_obj) self.assertEqual(child_ref.parent, parent_ref)
def test_parent_of_object_parented_to_bone(self): bone = testing.build_bone('bone') armature = testing.build_armature('armature', bones=[bone]) child_obj = testing.build_mesh_object( 'child_obj', parent=armature, parent_bone=bone.name )
parent_ref = blender_scene.ObjectRef.new_bone(armature, bone) child_ref = blender_scene.ObjectRef.new_object(child_obj) self.assertEqual(child_ref.parent, parent_ref)
def test_parent_of_root_bone_is_armature(self): bone = testing.build_bone('bone') armature = testing.build_armature('armature', bones=[bone])
armature_ref = blender_scene.ObjectRef.new_object(armature) bone_ref = blender_scene.ObjectRef.new_bone(armature, bone) self.assertEqual(bone_ref.parent, armature_ref)
class BlenderTreeMapperTest(parameterized.TestCase):
@parameterized.parameters([ [['obj1']], [['obj1', 'obj2']], [['obj2', 'obj1']], [['obj2', 'obj1', 'obj3']], ]) def test_object_without_hierarchy(self, object_names): context = mock.MagicMock(spec=bpy.types.Context) context.scene.objects = [ testing.build_mesh_object(name) for name in object_names ]
objects = blender_scene.map_blender_tree(context, lambda x: x) self.assertEqual([o.native_obj.name for o in objects], object_names)
@parameterized.parameters([ # A hierarchy with 2 objects dict( parent_child_tuples=[('obj_1', 'obj_1_1')], expected_order=['obj_1', 'obj_1_1'], ), # Shallow hierarchy with 3 objects dict( parent_child_tuples=[('obj_1', 'obj_1_1'), ('obj_1', 'obj_1_2')], expected_order=['obj_1', 'obj_1_1', 'obj_1_2'], ), # Deep hierarchy with 3 objects dict( parent_child_tuples=[('obj_1', 'obj_1_1'), ('obj_1_1', 'obj_1_2')], expected_order=['obj_1', 'obj_1_1', 'obj_1_2'], ), # 2 hierarchies, 2 objects each dict( parent_child_tuples=[('obj_1', 'obj_1_1'), ('obj_2', 'obj_2_1')], expected_order=['obj_1', 'obj_1_1', 'obj_2', 'obj_2_1'], ), ]) def test_object_with_hierarchy(self, parent_child_tuples, expected_order): objects = {} for parent_name, child_name in parent_child_tuples: parent = objects.get(parent_name, None) if not parent: parent = testing.build_mesh_object(parent_name) objects[parent_name] = parent
child = testing.build_mesh_object(child_name, parent=parent) objects[child_name] = child
context = mock.MagicMock(spec=bpy.types.Context) context.scene.objects = [o for o in objects.values()]
object_names = blender_scene.map_blender_tree(context, lambda x: x.name) self.assertEqual(object_names, expected_order)
def test_boneless_armature(self): armature = testing.build_armature('armature')
context = mock.MagicMock(spec=bpy.types.Context) context.scene.objects = [armature]
objects = blender_scene.map_blender_tree(context, lambda x: x) self.assertLen(objects, 1)
def test_armature_with_bones(self): root = testing.build_bone('root') r_arm = testing.build_bone('r_arm', parent=root) l_arm = testing.build_bone('l_arm', parent=root) r_finger = testing.build_bone('r_finger', parent=r_arm) armature = testing.build_armature( 'armature', bones=[r_finger, l_arm, root, r_arm] ) expected_order = [ 'armature', 'root_armature', 'r_arm_armature', 'r_finger_armature', 'l_arm_armature', ]
context = mock.MagicMock(spec=bpy.types.Context) # Randomize the order of objects to test the sorting mechanism. context.scene.objects = [armature]
object_names = blender_scene.map_blender_tree(context, lambda x: x.name) self.assertEqual(object_names, expected_order)
class DegreesOfFreedomTest(parameterized.TestCase):
def test_ik_with_unlimited_dofs_adds_all_dofs(self): constraint = testing.build_rotation_constraint( use_limit_x=False, use_limit_y=False, use_limit_z=False ) bone = testing.build_bone('bone', constraint=constraint) armature = testing.build_armature('bone', bones=[bone]) bone_ref = blender_scene.ObjectRef.new_bone(armature, bone)
dofs = bone_ref.get_rotation_dofs() self.assertLen(dofs, 3) self.assertEqual(dofs[0].axis, mathutils.Vector((1, 0, 0))) self.assertEqual(dofs[1].axis, mathutils.Vector((0, 1, 0))) self.assertEqual(dofs[2].axis, mathutils.Vector((0, 0, 1))) self.assertFalse(dofs[0].limited) self.assertFalse(dofs[1].limited) self.assertFalse(dofs[2].limited)
def test_ik_with_removed_dofs(self): constraint = testing.build_rotation_constraint( lock_x=False, lock_y=True, lock_z=False, use_limit_x=True, use_limit_z=False, ) bone = testing.build_bone('bone', constraint=constraint) armature = testing.build_armature('bone', bones=[bone]) bone_ref = blender_scene.ObjectRef.new_bone(armature, bone)
dofs = bone_ref.get_rotation_dofs() self.assertLen(dofs, 2) self.assertEqual(dofs[0].axis, mathutils.Vector((1, 0, 0))) self.assertEqual(dofs[1].axis, mathutils.Vector((0, 0, 1))) self.assertTrue(dofs[0].limited) self.assertFalse(dofs[1].limited)
def test_limiting_dof(self): constraint = testing.build_rotation_constraint( use_limit_x=True, min_x=math.radians(-15), max_x=math.radians(30) ) bone = testing.build_bone('bone', constraint=constraint) armature = testing.build_armature('bone', bones=[bone]) bone_ref = blender_scene.ObjectRef.new_bone(armature, bone)
dofs = bone_ref.get_rotation_dofs() self.assertLen(dofs, 3) self.assertTrue(dofs[0].limited) self.assertFalse(dofs[1].limited) self.assertFalse(dofs[2].limited) np.testing.assert_array_almost_equal(dofs[0].limits, (-15, 30), 1e-2)
if __name__ == '__main__': absltest.main()12345678910111213#!/bin/bash
set -euo pipefail
export output_dir="./addons/mujoco_model_exporter"rm -rf "${output_dir}"mkdir -p "${output_dir}"
cp ./*.py "${output_dir}"find "${output_dir}" -name "*.py" -exec sed -i "s/from dm_control.blender.fake_core //g" "{}" +;find "${output_dir}" -name "*.py" -exec sed -i "s/from dm_control.blender.mujoco_exporter/from ./g" "{}" +;echo "Add-on exported to ${output_dir}."echo "Copy this to Blender ./scripts/addons - see https://docs.blender.org/manual/en/latest/advanced/blender_directory_layout.html"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175# Copyright 2023 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Mujoco asset exporters.
Note about Materials.Material nodes are not supported, so please use basic Blender materials."""
import osimport structfrom typing import Sequencefrom xml.dom import minidom
from dm_control.blender.fake_core import bpyfrom dm_control.blender.mujoco_exporter import blender_scene
_MESH = 'MESH'
class MujocoMesh: """Mujoco representation of a mesh.
Mujoco can't handle meshes that reference multiple materials. Therefore an instance of this class represents a submesh that uses a specific material. """
def __init__(self, mesh: bpy.types.Mesh, material_idx: int, two_sided: bool): if mesh.uv_layers.active is None: raise ValueError(f'Mesh {mesh.name} does not have an active UV layer.')
mesh.calc_loop_triangles()
indices = [] for face in mesh.loop_triangles: if face.material_index == material_idx: indices.extend([i for i in face.vertices])
uv_layer = mesh.uv_layers.active.data # pylint: disable=g-complex-comprehension self.vertices = [c for i in indices for c in mesh.vertices[i].co] self.normals = [c for i in indices for c in mesh.vertices[i].normal] self.uvs = [c for i in indices for c in uv_layer[i].uv] # pylint: enable=g-complex-comprehension self.faces = list(range(len(self.vertices) // 3))
if two_sided: # For two-sided meshes, duplicate the geometry with flipped normals # and reversed triangle winding order. base_vertex = len(self.vertices) // 3 self.vertices += list(self.vertices) self.normals += [n * -1.0 for n in self.normals] self.uvs += list(self.uvs) self.faces += [i + base_vertex for i in reversed(self.faces)]
def save(self, filepath: str) -> None: """Save the data in the MSH format.""" nvertex = len(self.vertices) nnormal = len(self.normals) ntexcoord = len(self.uvs) nface = len(self.faces) assert nvertex % 3 == 0 assert nnormal % 3 == 0 assert ntexcoord % 2 == 0 assert nface % 3 == 0
fmt_msh = '4i{}f{}f{}f{}i'.format(nvertex, nnormal, ntexcoord, nface) with open(filepath, 'wb') as f: f.write( struct.pack( fmt_msh, nvertex // 3, nnormal // 3, ntexcoord // 2, nface // 3, *self.vertices, *self.normals, *self.uvs, *self.faces, ) )
def mesh_asset_builder( doc: minidom.Document, mesh: bpy.types.Mesh, materials: Sequence[bpy.types.Material], folder: str,) -> Sequence[minidom.Element]: """Exports a mesh associated with the object and creates an 'asset' node.""" mat_names = blender_scene.map_materials(lambda m: m.name, materials) twosidedness = blender_scene.map_materials( lambda m: not m.use_backface_culling, materials ) mat_names = mat_names or [''] twosidedness = twosidedness or [False]
elements = [] for mat_idx, (mat_name, twosided) in enumerate(zip(mat_names, twosidedness)): el_name = blender_scene.get_material_mesh_pair_name(mesh.name, mat_name) filename = '{}.msh'.format(el_name) filepath = os.path.join(folder, filename)
if blender_scene.is_material_mesh_pair_valid(mesh, mat_idx): mesh_to_export = MujocoMesh(mesh, mat_idx, twosided) mesh_to_export.save(filepath)
el = doc.createElement('mesh') el.setAttribute('name', el_name) el.setAttribute('file', filename) elements.append(el) return elements
def clip01(value): return min(1.0, max(0.0, value))
def material_asset_builder( doc: minidom.Document, mat: bpy.types.Material) -> minidom.Element: """Builds a material asset node.""" el = doc.createElement('material') el.setAttribute('name', mat.name) # el.setAttribute('texture', '') el.setAttribute('specular', str(clip01(mat.specular_intensity))) el.setAttribute('shininess', str(clip01(1.0 - mat.roughness))) el.setAttribute('reflectance', str(clip01(mat.metallic))) el.setAttribute('rgba', ' '.join([str(c) for c in mat.diffuse_color])) return el
def export_to_xml( doc: minidom.Document, objects: Sequence[blender_scene.ObjectRef], folder: str, apply_mesh_modifiers: bool,) -> minidom.Element: """converts Blender scene objects to Mujoco assets.""" asset_el = doc.createElement('asset')
unique = set() for obj in objects: if obj.is_mesh and obj.mesh not in unique: # Use the base mesh object as a reference, because that's the reference # that will be shared between objects. unique.add(obj.mesh) if apply_mesh_modifiers: # Make sure to export the mesh with modifiers applied, and if that's not # possible (it may not be possible and None will be returned), default # to the base mesh. mesh_for_export = obj.get_modified_mesh() or obj.mesh else: mesh_for_export = obj.mesh for el in mesh_asset_builder(doc, mesh_for_export, obj.materials, folder): asset_el.appendChild(el)
for material in obj.materials: if material not in unique: unique.add(material) asset_el.appendChild(material_asset_builder(doc, material))
return asset_el123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225# Copyright 2023 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Tests for mujoco_assets.py."""
import collectionsfrom unittest import mockfrom xml.dom import minidom
from absl.testing import absltestfrom absl.testing import parameterizedfrom dm_control.blender.mujoco_exporter import blender_scenefrom dm_control.blender.mujoco_exporter import mujoco_assetsfrom dm_control.blender.mujoco_exporter import testing
_DEFAULT_SETTINGS = dict(folder='', apply_mesh_modifiers=False)
class MujocoAssetsTest(parameterized.TestCase):
def test_building_mesh_asset(self): mesh_object = testing.build_mesh_object('mesh')
xml_root = mock.MagicMock(spec=minidom.Document) xml_root.createElement = mock.MagicMock(spec=minidom.Element)
obj = blender_scene.ObjectRef(mesh_object) with mock.patch(mujoco_assets.__name__ + '.open', mock.mock_open()): element = mujoco_assets.export_to_xml( xml_root, [obj], **_DEFAULT_SETTINGS )
xml_root.createElement.assert_any_call('mesh') element.setAttribute.assert_any_call('name', 'mesh') # Note there's no folder in the name. # The asset is assumed to be exported into the same folder as the .xml file. element.setAttribute.assert_any_call('file', 'mesh.msh')
def test_exporting_mesh_asset(self): mesh = testing.build_mesh(name='mesh.001') mesh_object = testing.build_mesh_object('mesh', mesh=mesh) xml_root = mock.MagicMock(spec=minidom.Document)
obj = blender_scene.ObjectRef(mesh_object) mock_open = mock.mock_open() with mock.patch(mujoco_assets.__name__ + '.open', mock_open): mujoco_assets.export_to_xml(xml_root, [obj], '/folder', False) mock_open.assert_called_once_with('/folder/mesh.001.msh', 'wb')
def test_exporting_material_asset(self): material = testing.build_material( 'mat', color=(0.1, 0.2, 0.3, 0.4), specular=0.5, metallic=0.6 ) xml_root = mock.MagicMock(spec=minidom.Document)
result = mujoco_assets.material_asset_builder(xml_root, material) result.setAttribute.assert_any_call('name', 'mat') result.setAttribute.assert_any_call('specular', '0.5') result.setAttribute.assert_any_call('reflectance', '0.6') result.setAttribute.assert_any_call('rgba', '0.1 0.2 0.3 0.4')
@parameterized.parameters([ [0.0, 1.0], [0.25, 0.75], [0.5, 0.5], [1.0, 0.0], [5.0, 0.0], [-5.0, 1.0], ]) def test_shininess_is_inverse_of_blender_mat_roughness(self, blender, mujoco): material = testing.build_material('mat', roughness=blender) xml_root = mock.MagicMock(spec=minidom.Document)
result = mujoco_assets.material_asset_builder(xml_root, material) result.setAttribute.assert_any_call('shininess', str(mujoco))
def test_export_unique_asset_instances(self): num_objects = 10 shared_material = testing.build_material('mat_1') shared_mesh = testing.build_mesh('mesh.001', materials=[shared_material])
objects = [ blender_scene.ObjectRef( testing.build_mesh_object('mesh', mesh=shared_mesh) ) for _ in range(num_objects) ] xml_root = mock.MagicMock(spec=minidom.Document) with mock.patch(mujoco_assets.__name__ + '.open', mock.mock_open()): mujoco_assets.export_to_xml(xml_root, objects, **_DEFAULT_SETTINGS)
create_element_call_counts = collections.Counter( [m_[0][0] for m_ in xml_root.createElement.call_args_list] ) self.assertEqual(create_element_call_counts['mesh'], 1) self.assertEqual(create_element_call_counts['material'], 1)
def test_mesh_with_multiple_materials_split(self): mat_1 = testing.build_material('mat_1') mat_2 = testing.build_material('mat_2') mesh = testing.build_mesh( 'mesh', materials=[mat_1, mat_2], faces=[[0, 1, 2], [3, 4, 5]], vert_co=[ [0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.3, 0.3, 0.3], [0.4, 0.4, 0.4], [0.5, 0.5, 0.5], [0.6, 0.6, 0.6], ], mat_ids=[0, 1], )
mesh_obj = blender_scene.ObjectRef( testing.build_mesh_object('mesh', mesh=mesh) )
with mock.patch(mujoco_assets.__name__ + '.open', mock.mock_open()): xml_root = mock.MagicMock(spec=minidom.Document) xml_elem = mock.MagicMock(spec=minidom.Element) xml_root.createElement.return_value = xml_elem mujoco_assets.export_to_xml(xml_root, [mesh_obj], **_DEFAULT_SETTINGS)
# Verify that two mesh elements were created... create_element_call_counts = collections.Counter( [m_[0][0] for m_ in xml_root.createElement.call_args_list] ) self.assertEqual(create_element_call_counts['mesh'], 2)
# ...and that their names reflect the mesh-material pairing. xml_elem.setAttribute.assert_any_call('file', 'mesh_mat_1.msh') xml_elem.setAttribute.assert_any_call('file', 'mesh_mat_2.msh') xml_elem.setAttribute.assert_any_call('name', 'mesh_mat_1') xml_elem.setAttribute.assert_any_call('name', 'mesh_mat_2')
class MujocoMeshTests(parameterized.TestCase):
def test_splitting_mesh_with_multiple_materials_into_submeshes(self): mat_0 = testing.build_material('mat_0') mat_1 = testing.build_material('mat_1') mesh = testing.build_mesh( 'mesh', materials=[mat_0, mat_1], faces=[[0, 1, 2], [3, 4, 5]], vert_co=[ [0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.3, 0.3, 0.3], [0.4, 0.4, 0.4], [0.5, 0.5, 0.5], [0.6, 0.6, 0.6], ], mat_ids=[0, 1], )
mesh_mat_0 = mujoco_assets.MujocoMesh(mesh, material_idx=0, two_sided=False) mesh_mat_1 = mujoco_assets.MujocoMesh(mesh, material_idx=1, two_sided=False)
self.assertEqual( mesh_mat_0.vertices, [0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3] ) self.assertEqual( mesh_mat_1.vertices, [0.4, 0.4, 0.4, 0.5, 0.5, 0.5, 0.6, 0.6, 0.6] ) self.assertEqual(mesh_mat_0.faces, [0, 1, 2]) self.assertEqual(mesh_mat_1.faces, [0, 1, 2])
def test_one_sided_mesh(self): mesh = testing.build_mesh( 'mesh', materials=[testing.build_material('mat')], faces=[[0, 1, 2]], vert_co=[[0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.3, 0.3, 0.3]], normals=[[0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.3, 0.3, 0.3]], mat_ids=[0], )
mesh = mujoco_assets.MujocoMesh(mesh, material_idx=0, two_sided=False) self.assertEqual(mesh.faces, [0, 1, 2]) self.assertEqual( mesh.vertices, [0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3] ) self.assertEqual( mesh.normals, [0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3] )
def test_two_sided_mesh(self): mesh = testing.build_mesh( 'mesh', materials=[testing.build_material('mat')], faces=[[0, 1, 2]], vert_co=[[0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.3, 0.3, 0.3]], normals=[[0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.3, 0.3, 0.3]], mat_ids=[0], )
mesh = mujoco_assets.MujocoMesh(mesh, material_idx=0, two_sided=True) self.assertEqual(mesh.faces, [0, 1, 2, 5, 4, 3]) self.assertEqual( mesh.vertices, [.1, .1, .1, .2, .2, .2, .3, .3, .3, .1, .1, .1, .2, .2, .2, .3, .3, .3,]) self.assertEqual( mesh.normals, [.1, .1, .1, .2, .2, .2, .3, .3, .3, -.1, -.1, -.1, -.2, -.2, -.2, -.3, -.3, -.3,])
if __name__ == '__main__': absltest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188# Copyright 2023 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Mujoco scene element builders and utilities."""
from typing import Sequencefrom xml.dom import minidom
from dm_control.blender.fake_core import mathutilsfrom dm_control.blender.mujoco_exporter import blender_scene
_ARMATURE = 'ARMATURE'_MESH = 'MESH'_VEC_ZERO = mathutils.Vector((0, 0, 0))_OZ = mathutils.Vector((0, 0, 1))
def color_to_mjcf(color: mathutils.Color) -> str: return '{} {} {}'.format(color.r, color.g, color.b)
def vec_to_mjcf(vec: mathutils.Vector) -> str: return '{} {} {}'.format(vec.x, vec.y, vec.z)
def quat_to_mjcf(quat: mathutils.Quaternion) -> str: return '{} {} {} {}'.format(quat.w, quat.x, quat.y, quat.z)
def bool_to_mjcf(bool_val: bool): return 'true' if bool_val else 'false'
def body_builder( doc: minidom.Document, blender_obj: blender_scene.ObjectRef) -> minidom.Element: """Builds a mujoco body element.""" transform = blender_obj.get_local_transform()
el = doc.createElement('body') el.setAttribute('name', blender_obj.name) el.setAttribute('pos', vec_to_mjcf(transform.pos)) el.setAttribute('quat', quat_to_mjcf(transform.rot)) return el
def light_builder( doc: minidom.Document, light_obj: blender_scene.ObjectRef) -> minidom.Element: """Builds an mjcf element that describes a light.""" assert light_obj.is_light light = light_obj.as_light()
directional = bool_to_mjcf(light.type == 'SUN' or light.type == 'SPOT') attenuation = '0 {} {}'.format( light.linear_attenuation, light.quadratic_attenuation ) transform = light_obj.get_local_transform()
el = doc.createElement('light') el.setAttribute('name', light_obj.name) el.setAttribute('pos', vec_to_mjcf(transform.pos)) el.setAttribute('dir', vec_to_mjcf(transform.rot @ _OZ)) el.setAttribute('directional', directional) el.setAttribute('castshadow', bool_to_mjcf(light.use_shadow)) # pytype: disable=wrong-arg-types el.setAttribute('diffuse', color_to_mjcf(light.color)) el.setAttribute('attenuation', attenuation) return el
def mesh_geom_builder( doc: minidom.Document, mesh_obj: blender_scene.ObjectRef) -> Sequence[minidom.Element]: """Builds a mujoco node for a mesh geom.""" mesh = mesh_obj.mesh transform = mesh_obj.get_local_transform()
elements = [] mat_names = blender_scene.map_materials(lambda m: m.name, mesh_obj.materials) # It might be the case that the mesh doesn't have any materials assigned. # We still want to export such geom, but we don't want to make a reference to # the material in the node. # So in that case we're using a fake material without a name mat_names = mat_names or [''] for mat_idx, mat_name in enumerate(mat_names): if not blender_scene.is_material_mesh_pair_valid(mesh, mat_idx): continue
obj_name = blender_scene.get_material_mesh_pair_name( mesh_obj.name, mat_name ) mesh_name = blender_scene.get_material_mesh_pair_name(mesh.name, mat_name)
el = doc.createElement('geom') el.setAttribute('name', obj_name) el.setAttribute('mesh', mesh_name) el.setAttribute('pos', vec_to_mjcf(transform.pos)) el.setAttribute('quat', quat_to_mjcf(transform.rot)) el.setAttribute('type', 'mesh') if mat_name: el.setAttribute('material', mat_name)
elements.append(el)
return elements
def joint_builder( doc: minidom.Document, dof: blender_scene.Dof, dof_type: str,) -> minidom.Element: """Builds a mujoco hinge definition.""" el = doc.createElement('joint') el.setAttribute('name', dof.name) el.setAttribute('type', dof_type) el.setAttribute('limited', bool_to_mjcf(dof.limited)) el.setAttribute('pos', vec_to_mjcf(_VEC_ZERO)) el.setAttribute('axis', vec_to_mjcf(dof.axis)) el.setAttribute('range', '{} {}'.format(dof.limits[0], dof.limits[1])) return el
def export_to_xml( doc: minidom.Document, objects: Sequence[blender_scene.ObjectRef], armature_freejoint: bool,) -> minidom.Element: """Converts Blender scene objects to Mujoco scene tree nodes.""" root = doc.createElement('worldbody') parent_elements = {blender_scene.NoneRef: root}
for obj in objects: # Build a subtree corresponding to this Blender object. element = None if obj.is_armature: element = body_builder(doc, obj) if armature_freejoint: element.appendChild(doc.createElement('freejoint')) elif obj.is_mesh: if not obj.parent.is_none and not obj.parent.is_bone: raise RuntimeError( 'Mesh "{}" is parented to an object "{}", which is not a bone. ' 'Only mesh->bone parenting is supported at the moment'.format( obj.name, obj.parent.name ) ) geom_elements = mesh_geom_builder(doc, obj) if len(geom_elements) > 1: # If there's more than one geom, introduce a body to aggregate them # under a single element. That element will then be associated with this # blender object should other blender elements be parented to it. element = doc.createElement('body') for geom_el in geom_elements: element.appendChild(geom_el) elif len(geom_elements) == 1: # Since there's only one geom, consider it the main element element = geom_elements[0] elif obj.is_light: element = light_builder(doc, obj) elif obj.is_bone: element = body_builder(doc, obj) for dof in obj.get_rotation_dofs(): element.appendChild(joint_builder(doc, dof, 'hinge'))
# Inject it into the scene tree. if element: parent = obj.parent if parent: parent_el = parent_elements[parent] parent_el.appendChild(element) parent_elements[obj] = element else: root.appendChild(element)
return root123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195# Copyright 2023 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Tests for mujoco_scene.py."""
import collectionsfrom unittest import mockfrom xml.dom import minidomfrom absl.testing import absltestfrom absl.testing import parameterizedfrom dm_control.blender.mujoco_exporter import blender_scenefrom dm_control.blender.mujoco_exporter import mujoco_scenefrom dm_control.blender.mujoco_exporter import testing
_DEFAULT_PARAMS = dict(armature_freejoint=False)
class ConverterTest(parameterized.TestCase):
def test_convert_armature(self): armature = testing.build_armature('armature') xml_root = mock.MagicMock(spec=minidom.Document) xml_root.createElement = mock.MagicMock(spec=minidom.Element)
obj = blender_scene.ObjectRef(armature) created_element = mujoco_scene.export_to_xml( xml_root, [obj], **_DEFAULT_PARAMS )
xml_root.createElement.assert_any_call('body') created_element.setAttribute.assert_any_call('name', 'armature')
def test_convert_bone_without_constraints_creates_a_body(self): bone = testing.build_bone('bone') armature = testing.build_armature('armature', bones=[bone])
xml_root = mock.MagicMock(spec=minidom.Document) xml_root.createElement.side_effect = mock.MagicMock(spec=minidom.Element)
bone_obj = blender_scene.ObjectRef(armature, bone) armature_obj = blender_scene.ObjectRef(armature) created_element = mujoco_scene.export_to_xml( xml_root, [armature_obj, bone_obj], **_DEFAULT_PARAMS )
xml_root.createElement.assert_any_call('body') created_element.setAttribute.assert_any_call('name', 'bone_armature')
@parameterized.parameters([ # Point light dict( args=dict(lin_att=1, quad_att=2, shadow=True, light_type='POINT'), out=dict(castshadow='true', attenuation='0 1 2', directional='false'), ), # Spot light dict( args=dict(lin_att=3, quad_att=4, shadow=True, light_type='SPOT'), out=dict(castshadow='true', attenuation='0 3 4', directional='true'), ), # Directional light dict( args=dict(lin_att=5, quad_att=6, shadow=True, light_type='SUN'), out=dict(castshadow='true', attenuation='0 5 6', directional='true'), ), # Shadows off dict( args=dict(lin_att=7, quad_att=8, shadow=False, light_type='SUN'), out=dict(castshadow='false', attenuation='0 7 8', directional='true'), ), ]) def test_convert_light(self, args, out): light = testing.build_light('light', **args)
xml_root = mock.MagicMock(spec=minidom.Document) xml_root.createElement = mock.MagicMock(spec=minidom.Element)
obj = blender_scene.ObjectRef(light) created_element = mujoco_scene.export_to_xml( xml_root, [obj], **_DEFAULT_PARAMS )
xml_root.createElement.assert_any_call('light') created_element.setAttribute.assert_any_call('name', 'light') for k, v in out.items(): created_element.setAttribute.assert_any_call(k, v)
def test_exported_mesh_references_mesh_asset_by_name(self): mesh = testing.build_mesh('mesh_asset_name') mesh_obj = testing.build_mesh_object('mesh_object_name', mesh=mesh)
xml_root = mock.MagicMock(spec=minidom.Document) xml_root.createElement = mock.MagicMock(spec=minidom.Element)
obj = blender_scene.ObjectRef(mesh_obj) created_element = mujoco_scene.export_to_xml( xml_root, [obj], **_DEFAULT_PARAMS )
xml_root.createElement.assert_any_call('geom') created_element.setAttribute.assert_any_call('name', 'mesh_object_name') created_element.setAttribute.assert_any_call('mesh', 'mesh_asset_name')
def test_mesh_with_no_material_keeps_its_name(self): mesh = testing.build_mesh('mesh') mesh_obj = testing.build_mesh_object('mesh_obj', mesh=mesh) obj = blender_scene.ObjectRef(mesh_obj)
xml_root = mock.MagicMock(spec=minidom.Document) xml_elem = mock.MagicMock(spec=minidom.Element) xml_root.createElement.return_value = xml_elem mujoco_scene.export_to_xml(xml_root, [obj], **_DEFAULT_PARAMS)
xml_elem.setAttribute.assert_any_call('name', 'mesh_obj') xml_elem.setAttribute.assert_any_call('mesh', 'mesh')
def test_mesh_with_materials_builds_multiple_geoms(self): mesh = testing.build_mesh( 'mesh', materials=[ testing.build_material('mat_1'), testing.build_material('mat_2'), ], faces=[[0, 1, 2], [3, 4, 5]], vert_co=[ [0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.3, 0.3, 0.3], [0.4, 0.4, 0.4], [0.5, 0.5, 0.5], [0.6, 0.6, 0.6], ], mat_ids=[0, 1], ) mesh_obj = testing.build_mesh_object('mesh_obj', mesh=mesh)
xml_root = mock.MagicMock(spec=minidom.Document) xml_elem = mock.MagicMock(spec=minidom.Element) xml_root.createElement.return_value = xml_elem
obj = blender_scene.ObjectRef(mesh_obj) mujoco_scene.export_to_xml(xml_root, [obj], **_DEFAULT_PARAMS)
xml_elem.setAttribute.assert_any_call('name', 'mesh_obj_mat_1') xml_elem.setAttribute.assert_any_call('name', 'mesh_obj_mat_2') xml_elem.setAttribute.assert_any_call('mesh', 'mesh_mat_1') xml_elem.setAttribute.assert_any_call('mesh', 'mesh_mat_2')
def test_empty_submeshes_are_not_exported(self): mesh = testing.build_mesh( 'mesh', materials=[ testing.build_material('mat_1'), testing.build_material('mat_2'), ], faces=[[0, 1, 2], [3, 4, 5]], vert_co=[ [0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.3, 0.3, 0.3], [0.4, 0.4, 0.4], [0.5, 0.5, 0.5], [0.6, 0.6, 0.6], ], mat_ids=[0, 0], ) # All faces reference material 0 mesh_obj = testing.build_mesh_object('mesh_obj', mesh=mesh)
xml_root = mock.MagicMock(spec=minidom.Document) xml_elem = mock.MagicMock(spec=minidom.Element) xml_root.createElement.return_value = xml_elem
obj = blender_scene.ObjectRef(mesh_obj) mujoco_scene.export_to_xml(xml_root, [obj], **_DEFAULT_PARAMS)
create_element_call_counts = collections.Counter( [m_[0][0] for m_ in xml_root.createElement.call_args_list] ) self.assertEqual(create_element_call_counts['geom'], 1) xml_elem.setAttribute.assert_any_call('name', 'mesh_obj_mat_1')
if __name__ == '__main__': absltest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198# Copyright 2023 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Testing utilities."""from typing import Any, Optional, Sequencefrom unittest import mock
from dm_control.blender.fake_core import bpy
class FakePropCollection: """Collection that simulates bpy_prop_collection.
Armature's bone collection is modeled using it, and the tested code depends on some of its features - namely the conversion to list produces dict values instead of its keys, as well as the collection behaving like a dict otherwise.
@see blender_scene.py : map_blender_tree - iterating over armature.data.bones blender_scene.py : ObjectRef.parent.object_parent - dereferencing bone by its name armature.data.bones[obj.parent_bone] """
def __init__(self, objects_with_name): if objects_with_name: self._keys = [i.name for i in objects_with_name] else: self._keys = [] self._values = objects_with_name or []
def __len__(self): return len(self._values)
def __getitem__(self, idx): if isinstance(idx, str): idx = self._keys.index(idx) return self._values[idx]
def __iter__(self): return iter(self._values)
def __contains__(self, key): return key in self._keys
def keys(self): return self._keys
def values(self): return self._values
def items(self): return list(zip(self._keys, self._values))
def build_armature( name: str, parent: Optional[Any] = None, parent_bone: Optional[str] = None, bones: Optional[Any] = None,): """TBD.""" obj = mock.MagicMock(spec=bpy.types.Object, type='ARMATURE') obj.name = name obj.parent = parent obj.parent_bone = parent_bone obj.data = mock.MagicMock() obj.data.bones = FakePropCollection(bones) obj.pose = mock.MagicMock() obj.pose.bones = FakePropCollection(bones) return obj
def build_bone(name, parent=None, constraint=None): """Builds a mock bone.""" bone = mock.MagicMock(spec=bpy.types.Bone) bone.name = name bone.parent = parent bone.is_in_ik_chain = constraint is not None bone.lock_ik_x = constraint.lock_x if constraint else False bone.use_ik_limit_x = constraint.use_limit_x if constraint else False bone.ik_min_x = constraint.min_x if constraint else 0.0 bone.ik_max_x = constraint.max_x if constraint else 0.0 bone.lock_ik_y = constraint.lock_y if constraint else False bone.use_ik_limit_y = constraint.use_limit_y if constraint else False bone.ik_min_y = constraint.min_y if constraint else 0.0 bone.ik_max_y = constraint.max_y if constraint else 0.0 bone.lock_ik_z = constraint.lock_z if constraint else False bone.use_ik_limit_z = constraint.use_limit_z if constraint else False bone.ik_min_z = constraint.min_z if constraint else 0.0 bone.ik_max_z = constraint.max_z if constraint else 0.0 return bone
def build_rotation_constraint( lock_x=False, use_limit_x=False, min_x=0, max_x=1, lock_y=False, use_limit_y=False, min_y=0, max_y=1, lock_z=False, use_limit_z=False, min_z=0, max_z=1): """Builds a mock rotation constraint.""" c = mock.MagicMock() c.lock_x = lock_x c.use_limit_x = use_limit_x c.min_x = min_x c.max_x = max_x c.lock_y = lock_y c.use_limit_y = use_limit_y c.min_y = min_y c.max_y = max_y c.lock_z = lock_z c.use_limit_z = use_limit_z c.min_z = min_z c.max_z = max_z return c
def build_mesh( name, materials=None, faces=None, vert_co=None, normals=None, mat_ids=None): """Builds a mock triangle mesh.""" materials = materials or [] faces = faces or [[0, 1, 2]] vert_co = vert_co or [[0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.3, 0.3, 0.3]] normals = normals or vert_co mat_ids = mat_ids or [0] * len(faces)
obj = mock.MagicMock(spec=bpy.types.Mesh) obj.name = name obj.materials = materials obj.uv_layers = mock.MagicMock() obj.loop_triangles = [ mock.MagicMock(vertices=f, material_index=i) for f, i in zip(faces, mat_ids) ] obj.vertices = [ mock.MagicMock(co=c, normal=n) for c, n in zip(vert_co, normals) ]
return obj
def build_mesh_object( name: str, mesh: Optional[Any] = None, parent: Optional[Any] = None, parent_bone: Optional[str] = None,): """Builds a mock object with a mesh assigned to it.""" obj = mock.MagicMock(spec=bpy.types.Object, type='MESH') obj.name = name obj.parent = parent obj.parent_bone = parent_bone obj.data = mesh or build_mesh(name) return obj
def build_light(name, light_type, lin_att, quad_att, shadow): """Builds a mock light.""" obj = mock.MagicMock(spec=bpy.types.Object, type='LIGHT') obj.name = name obj.parent = None obj.parent_bone = None obj.data = mock.MagicMock(spec=bpy.types.Light) obj.data.type = light_type obj.data.linear_attenuation = lin_att obj.data.quadratic_attenuation = quad_att obj.data.use_shadow = shadow return obj
def build_material( name: str, color: Sequence[int] = (1, 1, 1, 1), specular: float = 0.5, metallic: float = 0.0, roughness: float = 0.5, use_backface_culling: bool = False,): """Builds a mock material definition.""" obj = mock.MagicMock(spec=bpy.types.Material) obj.name = name obj.diffuse_color = color obj.specular_intensity = specular obj.metallic = metallic obj.roughness = roughness obj.use_backface_culling = use_backface_culling return obj123456789101112131415161718192021222324252627282930313233# Copyright 2018-2019 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""Module containing abstract base classes for Composer environments."""
from dm_control.composer.arena import Arenafrom dm_control.composer.constants import * # pylint: disable=wildcard-importfrom dm_control.composer.define import cached_propertyfrom dm_control.composer.define import observablefrom dm_control.composer.entity import Entityfrom dm_control.composer.entity import FreePropObservableMixinfrom dm_control.composer.entity import ModelWrapperEntityfrom dm_control.composer.entity import Observablesfrom dm_control.composer.environment import Environmentfrom dm_control.composer.environment import EpisodeInitializationErrorfrom dm_control.composer.environment import HOOK_NAMESfrom dm_control.composer.environment import ObservationPaddingfrom dm_control.composer.initializer import Initializerfrom dm_control.composer.robot import Robotfrom dm_control.composer.task import NullTaskfrom dm_control.composer.task import Task12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970# Copyright 2018 The dm_control Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.# ============================================================================
"""The base empty arena that defines global settings for Composer."""
import os
from dm_control import mjcffrom dm_control.composer import entity as entity_module
_ARENA_XML_PATH = os.path.join(os.path.dirname(__file__), 'arena.xml')
class Arena(entity_module.Entity): """The base empty arena that defines global settings for Composer."""
def __init__(self, *args, **kwargs): self._mjcf_root = None # Declare that _mjcf_root exists to allay pytype. super().__init__(*args, **kwargs)
# _build uses *args and **kwargs rather than named arguments, to get # around a signature-mismatch error from pytype in derived classes.
def _build(self, *args, **kwargs) -> None: """Initializes this arena.
The function takes two arguments through args, kwargs: name: A string, the name of this arena. If `None`, use the model name defined in the MJCF file. xml_path: An optional path to an XML file that will override the default composer arena MJCF.
Args: *args: See above. **kwargs: See above. """ if args: name = args[0] else: name = kwargs.get('name', None) if len(args) > 1: xml_path = args[1] else: xml_path = kwargs.get('xml_path', None)
self._mjcf_root = mjcf.from_path(xml_path or _ARENA_XML_PATH) if name: self._mjcf_root.model = name
def add_free_entity(self, entity): """Includes an entity in the arena as a free-moving body.""" frame = self.attach(entity) frame.add('freejoint') return frame
@property def mjcf_model(self): return self._mjcf_root.gitattributes+170
data/AUTHORSAdded+7
data/CONTRIBUTING.mdAdded+23
data/LICENSEAdded+202
data/README.mdAdded+138
data/dm_control/__init__.pyAdded+14
data/dm_control/_render/__init__.pyAdded+109
data/dm_control/_render/base.pyAdded+166
data/dm_control/_render/base_test.pyAdded+162
data/dm_control/_render/constants.pyAdded+33
data/dm_control/_render/executor/__init__.pyAdded+51
data/dm_control/_render/executor/render_executor.pyAdded+218
data/dm_control/_render/executor/render_executor_test.pyAdded+205
data/dm_control/_render/glfw_renderer.pyAdded+68
data/dm_control/_render/glfw_renderer_test.pyAdded+68
data/dm_control/_render/pyopengl/__init__.pyAdded+14
data/dm_control/_render/pyopengl/egl_ext.pyAdded+74
data/dm_control/_render/pyopengl/egl_renderer.pyAdded+140
data/dm_control/_render/pyopengl/osmesa_renderer.pyAdded+86
data/dm_control/_render/pyopengl/osmesa_renderer_test.pyAdded+70
data/dm_control/autowrap/__init__.pyAdded+15
data/dm_control/autowrap/autowrap.pyAdded+126
data/dm_control/autowrap/binding_generator.pyAdded+296
data/dm_control/autowrap/codegen_util.pyAdded+119
data/dm_control/autowrap/header_parsing.pyAdded+335
data/dm_control/blender/fake_core/bpy.pyAdded+229
data/dm_control/blender/fake_core/mathutils.pyAdded+123
data/dm_control/blender/mujoco_exporter/README.mdAdded+213
data/dm_control/blender/mujoco_exporter/__init__.pyAdded+170
data/dm_control/blender/mujoco_exporter/blender_scene.pyAdded+428
data/dm_control/blender/mujoco_exporter/blender_scene_test.pyAdded+244
data/dm_control/blender/mujoco_exporter/doc/add_ik_constraint.pngAdded

Large File Pointer Details
- SHA256: 827539984a8696966de3e8cd74bf490574fae0a41e741122512ed261ed4859b7
- Pointer size: 131 Bytes
- Size of remote file: 124 kB
data/dm_control/blender/mujoco_exporter/doc/convhull_blend.pngAdded

Large File Pointer Details
- SHA256: 9dce9ffeb823f6bb427bab4daa4257f763670424ddcb8b66b15aec14c0466e56
- Pointer size: 130 Bytes
- Size of remote file: 58 kB
data/dm_control/blender/mujoco_exporter/doc/convhull_mj_hull.pngAdded

Large File Pointer Details
- SHA256: 92ae5482e2fa75e20a1b202e0200bebf10d03bb744c57fe59146a09661ee2769
- Pointer size: 129 Bytes
- Size of remote file: 8.85 kB
data/dm_control/blender/mujoco_exporter/doc/convhull_mj_rend.pngAdded

Large File Pointer Details
- SHA256: d502c2af50033107da06d581b03987a253b82b485f13c8f556ddc1cd4d281d81
- Pointer size: 130 Bytes
- Size of remote file: 21 kB
data/dm_control/blender/mujoco_exporter/doc/enable_plugin.pngAdded

Large File Pointer Details
- SHA256: d508011ce578fedb03e8d0b1d020b5b751767d8c7f032a911df9c6e411c296e1
- Pointer size: 130 Bytes
- Size of remote file: 50.2 kB
data/dm_control/blender/mujoco_exporter/doc/end_effector_selection.pngAdded

Large File Pointer Details
- SHA256: fc942988ff433843f7ea15455283c3fc28a7b150005a20acfaf23b1fa5dc996b
- Pointer size: 130 Bytes
- Size of remote file: 70.8 kB
data/dm_control/blender/mujoco_exporter/doc/gizmo.pngAdded

Large File Pointer Details
- SHA256: 30739e264fbfda7763a5544ebbab8ebe826926e3af43f2bcb54ba7a2d813d991
- Pointer size: 131 Bytes
- Size of remote file: 124 kB
data/dm_control/blender/mujoco_exporter/doc/ik_chain_length.pngAdded

Large File Pointer Details
- SHA256: 121ab68439a7a1c22cd5fb927c5cfd5300ce9c368d69bac513dc3f89ce8d464e
- Pointer size: 130 Bytes
- Size of remote file: 68.5 kB
data/dm_control/blender/mujoco_exporter/doc/ik_target.pngAdded

Large File Pointer Details
- SHA256: 8f7a28207cdee6fdf4b09f1eee4ba42627cefbcf2041ee07b942f0bf74768078
- Pointer size: 131 Bytes
- Size of remote file: 159 kB
data/dm_control/blender/mujoco_exporter/doc/install_plugin.pngAdded

Large File Pointer Details
- SHA256: bd745eaefe02f528bd07b731c1a361a5fc1434e987039e3085426138c525113d
- Pointer size: 130 Bytes
- Size of remote file: 98.1 kB
data/dm_control/blender/mujoco_exporter/doc/limits.pngAdded

Large File Pointer Details
- SHA256: 864a921e2655f30515dd53acb9b763cfe8f47f596394f9e1772303f48b021141
- Pointer size: 131 Bytes
- Size of remote file: 123 kB
data/dm_control/blender/mujoco_exporter/install.shAdded+13
data/dm_control/blender/mujoco_exporter/mujoco_assets.pyAdded+175
data/dm_control/blender/mujoco_exporter/mujoco_assets_test.pyAdded+225
data/dm_control/blender/mujoco_exporter/mujoco_scene.pyAdded+188
data/dm_control/blender/mujoco_exporter/mujoco_scene_test.pyAdded+195
data/dm_control/blender/mujoco_exporter/testing.pyAdded+198
data/dm_control/composer/__init__.pyAdded+33
data/dm_control/composer/arena.pyAdded+70