diff --git a/examples/pybullet/gym/pybullet_utils/bullet_client.py b/examples/pybullet/gym/pybullet_utils/bullet_client.py new file mode 100644 index 000000000..8fc1fcd5c --- /dev/null +++ b/examples/pybullet/gym/pybullet_utils/bullet_client.py @@ -0,0 +1,50 @@ +"""A wrapper for pybullet to manage different clients.""" +from __future__ import absolute_import +from __future__ import division +import functools +import inspect +import pybullet + + +class BulletClient(object): + """A wrapper for pybullet to manage different clients.""" + + def __init__(self, connection_mode=None): + """Creates a Bullet client and connects to a simulation. + + Args: + connection_mode: + `None` connects to an existing simulation or, if fails, creates a + new headless simulation, + `pybullet.GUI` creates a new simulation with a GUI, + `pybullet.DIRECT` creates a headless simulation, + `pybullet.SHARED_MEMORY` connects to an existing simulation. + """ + self._shapes = {} + + if connection_mode is None: + self._client = pybullet.connect(pybullet.SHARED_MEMORY) + if self._client >= 0: + return + else: + connection_mode = pybullet.DIRECT + self._client = pybullet.connect(connection_mode) + + def __del__(self): + """Clean up connection if not already done.""" + try: + pybullet.disconnect(physicsClientId=self._client) + except pybullet.error: + pass + + def __getattr__(self, name): + """Inject the client id into Bullet functions.""" + attribute = getattr(pybullet, name) + if inspect.isbuiltin(attribute): + if name not in [ + "invertTransform", "multiplyTransforms", "getMatrixFromQuaternion", + "getEulerFromQuaternion", "computeViewMatrixFromYawPitchRoll", + "computeProjectionMatrixFOV", "getQuaternionFromEuler", + ]: # A temporary hack for now. + attribute = functools.partial(attribute, physicsClientId=self._client) + return attribute diff --git a/examples/pybullet/gym/pybullet_utils/examples/multipleScenes.py b/examples/pybullet/gym/pybullet_utils/examples/multipleScenes.py new file mode 100644 index 000000000..7018cfead --- /dev/null +++ b/examples/pybullet/gym/pybullet_utils/examples/multipleScenes.py @@ -0,0 +1,20 @@ +import pybullet_utils.bullet_client as bc +import pybullet +import pybullet_data + +p0 = bc.BulletClient(connection_mode=pybullet.DIRECT) +p0.setAdditionalSearchPath(pybullet_data.getDataPath()) + +p1 = bc.BulletClient(connection_mode=pybullet.DIRECT) +p1.setAdditionalSearchPath(pybullet_data.getDataPath()) + +#can also connect using different modes, GUI, SHARED_MEMORY, TCP, UDP, SHARED_MEMORY_SERVER, GUI_SERVER +#pgui = bc.BulletClient(connection_mode=pybullet.GUI) + +p0.loadURDF("r2d2.urdf") +p1.loadSDF("stadium.sdf") +print(p0._client) +print(p1._client) +print("p0.getNumBodies()=",p0.getNumBodies()) +print("p1.getNumBodies()=",p1.getNumBodies()) +