Add viewer.launch_passive and a mjpython launcher for macOS.

The `launch_passive` function launches the GUI viewer in a non-blocking manner, allowing the Python script or REPL to continue execution. The viewer is automatically kept up to date with any subsequent modifications to mjModel and mjData.

Note that when run inside a REPL (including IPython), `launch_passive` is functionally identical to `launch_repl`.

On Linux and Windows, this is achieved by spawning a new thread and launching the GUI there.

On macOS, this is not possible as all Cocoa API calls must be made on the "macOS main thread", which is always the first thread launched in a process and carries the `com.apple.main-thread` dispatch queue. We also cannot simply trampoline from a Python script on the main thread into the user's script on a side thread because CPython's signal handler can only be installed on the "Python main thread". Putting the user's script in a side thread means that it cannot e.g. gracefully handle SIGINT by catching a KeyboardInterrupt exception. To work around this, we ship a custom Python launcher on macOS called `mjpython`. This launcher is a native binary that spawns a pthread and initialize the Python interpreter on that thread, thus allowing "Python main thread" and "macOS main thread" to represent two distinct threads. From Python's point of view, the "macOS main thread" is a secondary thread that runs a loop that continuously empties a Queue of (mjModel, mjData) and launches a viewer.

PiperOrigin-RevId: 517167868
Change-Id: Icac9d2126bbb4760d47e0b9300e0a979cffa4338
This commit is contained in:
Saran Tunyasuvunakool
2023-03-16 10:52:22 -07:00
committed by Copybara-Service
parent 9a97674e1e
commit 230e2780de
8 changed files with 509 additions and 8 deletions
+69 -3
View File
@@ -15,6 +15,7 @@
"""Install script for MuJoCo."""
import fnmatch
import logging
import os
import platform
import random
@@ -29,6 +30,7 @@ import setuptools
from setuptools import find_packages
from setuptools import setup
from setuptools.command import build_ext
from setuptools.command import install_scripts
__version__ = '2.3.2'
@@ -70,6 +72,7 @@ def get_external_lib_patterns():
else:
return ['libmujoco.so.*']
def get_plugin_lib_patterns():
if platform.system() == 'Windows':
return ['*.dll']
@@ -159,6 +162,8 @@ class BuildCMakeExtension(build_ext.build_ext):
self._copy_external_libraries()
self._copy_mujoco_headers()
self._copy_plugin_libraries()
if self._is_apple:
self._copy_mjpython()
def _find_mujoco(self):
if MUJOCO_PATH not in os.environ:
@@ -213,6 +218,26 @@ class BuildCMakeExtension(build_ext.build_ext):
shutil.copyfile(os.path.join(directory, filename),
os.path.join(dst, filename))
def _copy_mjpython(self):
src_dir = os.path.join(os.path.dirname(__file__), 'mujoco/mjpython')
dst_contents_dir = os.path.join(
os.path.dirname(self.get_ext_fullpath(self.extensions[0].name)),
'MuJoCo (mjpython).app/Contents')
os.makedirs(dst_contents_dir)
shutil.copyfile(os.path.join(src_dir, 'Info.plist'),
os.path.join(dst_contents_dir, 'Info.plist'))
dst_bin_dir = os.path.join(dst_contents_dir, 'MacOS')
os.makedirs(dst_bin_dir)
shutil.copyfile(os.path.join(self.build_temp, 'mjpython'),
os.path.join(dst_bin_dir, 'mjpython'))
os.chmod(os.path.join(dst_bin_dir, 'mjpython'), 0o755)
dst_resources_dir = os.path.join(dst_contents_dir, 'Resources')
os.makedirs(dst_resources_dir)
shutil.copyfile(os.path.join(src_dir, 'mjpython.icns'),
os.path.join(dst_resources_dir, 'mjpython.icns'))
def _configure_cmake(self):
"""Check for CMake."""
cmake = os.environ.get(MUJOCO_CMAKE, 'cmake')
@@ -276,6 +301,40 @@ class BuildCMakeExtension(build_ext.build_ext):
build_path = os.path.join(self.build_temp, os.path.basename(dest_path))
shutil.copyfile(build_path, dest_path)
class InstallScripts(install_scripts.install_scripts):
"""Strips file extension from executable scripts whose names end in `.py`."""
def run(self):
super().run()
oldfiles = self.outfiles
files = set(oldfiles)
self.outfiles = []
for oldfile in oldfiles:
if oldfile.endswith('.py'):
newfile = oldfile[:-3]
else:
newfile = oldfile
renamed = False
if newfile not in files and not os.path.exists(newfile):
if not self.dry_run:
os.rename(oldfile, newfile)
renamed = True
if renamed:
logging.info(
'Renaming %s script to %s',
os.path.basename(oldfile),
os.path.basename(newfile),
)
self.outfiles.append(newfile)
files.remove(oldfile)
files.add(newfile)
else:
self.outfiles.append(oldfile)
def find_data_files(package_dir, patterns):
"""Recursively finds files whose names match the given shell patterns."""
paths = set()
@@ -287,8 +346,7 @@ def find_data_files(package_dir, patterns):
paths.add(os.path.join(relative_dirpath, filename))
return list(paths)
setup(
SETUP_KWARGS = dict(
name='mujoco',
version=__version__,
author='DeepMind',
@@ -312,7 +370,10 @@ setup(
'Programming Language :: Python :: 3.11',
'Topic :: Scientific/Engineering',
],
cmdclass=dict(build_ext=BuildCMakeExtension),
cmdclass=dict(
build_ext=BuildCMakeExtension,
install_scripts=InstallScripts,
),
ext_modules=[
CMakeExtension('mujoco._callbacks'),
CMakeExtension('mujoco._constants'),
@@ -351,3 +412,8 @@ setup(
]),
},
)
if platform.system() == 'Darwin':
SETUP_KWARGS['scripts'] = ['mujoco/mjpython/mjpython.py']
setup(**SETUP_KWARGS)