Example #1
0
	def __init__(self, *args, **kwargs):
		print("Hello from __init__")
		self.loader = Loader(self)
		panda = self.loader.loadModel("panda")
		# `render` here is a global variable injected from C++
		panda.reparentTo(render)
		panda.setPos(0, 50, 0)
Example #2
0
    def __init__(self):
        ShowBase.__init__(self)
        props = WindowProperties()
        props.setTitle("Big Bang")
        self.win.requestProperties(props)
        self.win.setClearColor((0, 0, 0, 1))
        self.disableMouse()
        self.locked = False
        lens = PerspectiveLens()
        lens.set_fov(70)
        lens.setNear(0.01)
        self.cam.node().setLens(lens)    
        render.setAntialias(AntialiasAttrib.MMultisample)
        b=OnscreenImage(parent=render2d, image="space.png")
        base.cam.node().getDisplayRegion(0).setSort(20)

        loader = Loader(self)
        bang = loader.loadModel("sphere.obj")
        bang.setScale((0.15, 0.15, 0.15))
        pos = (0, 4, 0)
        bang.setPos(pos)
        bang.reparentTo(render)
        sizeInterval1 = bang.scaleInterval(3,
        							 Point3(5, 5, 5),
        							 startScale=Point3(0.001, 0.001, 0.001))
        sizeInterval2 = bang.scaleInterval(0.1,
        							 Point3(0.001, 0.001, 0.001),
        							 startScale=Point3(5,5,5))
        sizeInterval3 = bang.scaleInterval(1,
        							 Point3(0.001, 0.001, 0.001),
        							 startScale=Point3(0.001, 0.001, 0.001))
        sizeInterval4 = bang.scaleInterval(0.1,
        							 Point3(0.1, 0.1, 1),
        							 startScale=Point3(0.1, 0.1, 0.1))
        sizeInterval5 = bang.scaleInterval(0.1,
        							 Point3(1, 0.1, 0.1),
        							 startScale=Point3(0.1, 0.1, 0.1))
        #posInterval1 = bang.posInterval(3,
        #							 Point3(0, 8, 0),
        #							 startPos=Point3(pos))
        #posInterval2 = bang.posInterval(0.1,
        #							 Point3(pos),
        #							 startPos=Point3(0, 8, 0))
        #posInterval3 = bang.posInterval(1,
        #							 Point3(pos),
        #							 startPos=Point3(pos))
        #posInterval4 = bang.posInterval(0.1,
        #							 Point3(pos),
        #							 startPos=Point3(pos))
        grow = Sequence(sizeInterval1, sizeInterval2, sizeInterval3, sizeInterval4, sizeInterval5,
        						  name="grow")
        grow.loop()
        #move = Sequence(posInterval1, posInterval2, posInterval3, posInterval4, posInterval4,
        #						  name="move")
        #move.loop()

        self.accept("e", self.lockMouse)
        # Add the spinCameraTask procedure to the task manager.
        self.taskMgr.add(self.cameraControl, "CameraControl")
Example #3
0
    def prepare(self, curr_cond, stim_period=''):
        self.curr_cond = curr_cond if stim_period == '' else curr_cond[
            stim_period]
        self.period = stim_period

        if not self.curr_cond:
            self.isrunning = False
        self.background_color = self.curr_cond['background_color']

        # set background color
        self.set_background_color(*self.curr_cond['background_color'])

        # Set Ambient Light
        self.ambientLight.setColor(self.curr_cond['ambient_color'])

        # Set Directional Light
        self.lights = dict()
        self.lightsNP = dict()
        for idx, light_idx in enumerate(iterable(self.curr_cond['light_idx'])):
            self.lights[idx] = core.DirectionalLight('directionalLight_%d' %
                                                     idx)
            self.lightsNP[idx] = self.render.attachNewNode(self.lights[idx])
            self.render.setLight(self.lightsNP[idx])
            self.lights[idx].setColor(tuple(
                self.curr_cond['light_color'][idx]))
            self.lightsNP[idx].setHpr(*self.curr_cond['light_dir'][idx])

        # Set Object tasks
        self.objects = dict()
        for idx, obj in enumerate(iterable(self.curr_cond['obj_id'])):
            self.objects[idx] = Agent(self, self.get_cond('obj_', idx))

        if 'movie_name' in self.curr_cond:
            self.movie = True
            loader = Loader(self)
            file_name = self.get_clip_info(self.curr_cond, 'file_name')
            self.mov_texture = loader.loadTexture(self.movie_path +
                                                  file_name[0])
            cm = CardMaker("card")
            tx_scale = self.mov_texture.getTexScale()
            cm.setFrame(-1, 1, -tx_scale[1] / tx_scale[0],
                        tx_scale[1] / tx_scale[0])
            self.movie_node = NodePath(cm.generate())
            self.movie_node.setTexture(self.mov_texture, 1)
            self.movie_node.setPos(0, 100, 0)
            self.movie_node.setTexScale(TextureStage.getDefault(),
                                        self.mov_texture.getTexScale())
            self.movie_node.setScale(48)
            self.movie_node.reparentTo(self.render)

        if not self.isrunning:
            self.timer.start()
            self.isrunning = True
Example #4
0
    def __init__(self):
        self.loadDefaultConfig()
        self.loadLocalConfig()

        if ConfigVariableBool("want-pstats", False):
            PStatClient.connect()

        # Set up some global objects
        self.globalClock = ClockObject.getGlobalClock()
        # We will manually manage the clock
        self.globalClock.setMode(ClockObject.MSlave)
        builtins.globalClock = self.globalClock

        self.vfs = VirtualFileSystem.getGlobalPtr()

        # For tasks that run every application frame
        self.taskMgr = TaskManagerGlobal.taskMgr
        builtins.taskMgr = self.taskMgr

        # For tasks that run every simulation tick
        self.simTaskMgr = Task.TaskManager()
        self.simTaskMgr.mgr = AsyncTaskManager("sim")
        builtins.simTaskmgr = self.simTaskMgr

        self.eventMgr = EventManagerGlobal.eventMgr
        builtins.eventMgr = self.eventMgr

        self.messenger = MessengerGlobal.messenger
        builtins.messenger = self.messenger

        self.loader = Loader(self)
        builtins.loader = self.loader

        builtins.base = self

        # What is the current frame number?
        self.frameCount = 0
        # Time at beginning of current frame
        self.frameTime = self.globalClock.getRealTime()
        # How long did the last frame take.
        self.deltaTime = 0

        #
        # Variables pertaining to simulation ticks.
        #

        self.prevRemainder = 0
        self.remainder = 0
        # What is the current overall simulation tick?
        self.tickCount = 0
        # How many ticks are we going to run this frame?
        self.totalTicksThisFrame = 0
        # How many ticks have we run so far this frame?
        self.currentTicksThisFrame = 0
        # What tick are we currently on this frame?
        self.currentFrameTick = 0
        # How many simulations ticks are we running per-second?
        self.ticksPerSec = 60
        self.intervalPerTick = 1.0 / self.ticksPerSec
Example #5
0
def draw_cicle(x, y, r, col=None, parent=None):
    base = app.get_show_base()
    loader = Loader(base)
    model = loader.loadModel("data/geom/circle.egg")

    col = draw_get_color(col, color_format="rgba")

    if parent is None:
        parent = builtins.pixel2d

    model.reparentTo(parent)

    model.setPos(x, 0, -y)
    model.setScale(r, 1, r)

    # model.setColorScale(1, 0, 0, 1)
    model.setColor(col)

    return model
Example #6
0
    def __init__(self, base):
        # Load texture
        tex = Loader(base).loadTexture((Path(path.realpath(__file__)).parent.parent.parent / "res/images/checkerboard.png").absolute())
        tex.setMagfilter(SamplerState.FT_nearest)
        tex.setMinfilter(SamplerState.FT_nearest)

        # Set up vertex data
        vdata = GeomVertexData("floor_data", GeomVertexFormat.get_v3t2(), Geom.UHStatic)
        vdata.setNumRows(6)
        vertex = GeomVertexWriter(vdata, "vertex")
        texcoord = GeomVertexWriter(vdata, "texcoord")

        vertex.addData3(-5, -5, 0)
        texcoord.addData3(0, 0, 0)
        vertex.addData3(-5, 5, 0)
        texcoord.addData3(0, 10, 0)
        vertex.addData3(5, 5, 0)
        texcoord.addData3(10, 10, 0)

        vertex.addData3(5, 5, 0)
        texcoord.addData3(10, 10, 0)
        vertex.addData3(5, -5, 0)
        texcoord.addData3(10, 0, 0)
        vertex.addData3(-5, -5, 0)
        texcoord.addData3(0, 0, 0)

        # Create primitive
        prim = GeomTriangles(Geom.UHStatic)
        prim.addVertices(0, 1, 2)
        prim.addVertices(3, 4, 5)
        geom = Geom(vdata)
        geom.add_primitive(prim)

        # Initialize geometry node
        GeomNode.__init__(self, "floor")
        attrib = TextureAttrib.make(tex)
        state = RenderState.make(attrib)
        self.addGeom(geom, state)
Example #7
0
    def gen_geom(self, mesh_json):
        # Create vertex format
        geom_array = GeomVertexArrayFormat()
        geom_array.add_column("vertex", 3, Geom.NTFloat32, Geom.CPoint)
        has_normals = False
        has_texcoords = False
        has_weights = False
        if "normals" in mesh_json:
            geom_array.add_column("normal", 3, Geom.NTFloat32, Geom.CNormal)
            has_normals = True
        if "texcoords" in mesh_json:
            geom_array.add_column("texcoord", 3, Geom.NTFloat32,
                                  Geom.CTexcoord)
            has_texcoords = True
        if "weights" in mesh_json:
            geom_array.add_column("joint", 4, Geom.NTUint8, Geom.CIndex)
            geom_array.add_column("weight", 4, Geom.NTFloat32, Geom.COther)
            has_weights = True
        geom_format = GeomVertexFormat()
        geom_format.add_array(geom_array)
        geom_format = GeomVertexFormat.register_format(geom_format)

        # Set up vertex data
        vdata = GeomVertexData(
            str(random.randint(0, 255)) + "_vdata", geom_format, Geom.UHStatic)
        vcount = len(mesh_json["vertices"]) // 3
        vdata.setNumRows(vcount)
        vertex = GeomVertexWriter(vdata, "vertex")

        for i in range(vcount):
            vertex.addData3(mesh_json["vertices"][3 * i],
                            mesh_json["vertices"][3 * i + 1],
                            mesh_json["vertices"][3 * i + 2])
        if has_normals:
            normal = GeomVertexWriter(vdata, "normal")
            for i in range(vcount):
                normal.addData3(mesh_json["normals"][3 * i],
                                mesh_json["normals"][3 * i + 1],
                                mesh_json["normals"][3 * i + 2])
        if has_texcoords:
            texcoord = GeomVertexWriter(vdata, "texcoord")
            for i in range(vcount):
                texcoord.addData2(mesh_json["texcoords"][2 * i],
                                  mesh_json["texcoords"][2 * i + 1])
        if has_weights:
            joint = GeomVertexWriter(vdata, "joint")
            weight = GeomVertexWriter(vdata, "weight")
            for i in range(vcount):
                joint_count = len(mesh_json["joints"][i])
                joint.addData4(
                    0 if joint_count < 1 else mesh_json["joints"][i][0],
                    0 if joint_count < 2 else mesh_json["joints"][i][1],
                    0 if joint_count < 3 else mesh_json["joints"][i][2],
                    0 if joint_count < 4 else mesh_json["joints"][i][3])
                weight.addData4(
                    0 if joint_count < 1 else mesh_json["weights"][i][0],
                    0 if joint_count < 2 else mesh_json["weights"][i][1],
                    0 if joint_count < 3 else mesh_json["weights"][i][2],
                    0 if joint_count < 4 else mesh_json["weights"][i][3])

        # Create primitive
        prim = GeomTriangles(Geom.UHStatic)
        for i in range(vcount // 3):
            prim.addVertices(3 * i, 3 * i + 1, 3 * i + 2)
        geom = Geom(vdata)
        geom.add_primitive(prim)

        # Load texture
        tex = None
        if "texture" in mesh_json:
            tex = Loader(EComponent.base).loadTexture(
                (Path("resources") / mesh_json["texture"]).absolute())
            tex.setMagfilter(SamplerState.FT_nearest)
            tex.setMinfilter(SamplerState.FT_nearest)

        # Create new geometry node
        geom_node = GeomNode(str(random.randint(0, 255)) + "_node")
        if tex is None:
            geom_node.addGeom(geom)
        else:
            attrib = TextureAttrib.make(tex)
            state = RenderState.make(attrib)
            geom_node.addGeom(geom, state)
        if EComponent.panda_root_node is not None:
            self.geom_path = EComponent.panda_root_node.attach_new_node(
                geom_node)
            self.geom_path.set_shader_input("object_id", self.object_id)

        # Set shader
        if has_weights and self.geom_path is not None:
            self.geom_path.setTag("shader type", "skinned")
            bone_mats = PTA_LMatrix4f()
            for _ in range(100):
                bone_mats.push_back(helper.np_mat4_to_panda(np.identity(4)))
            self.geom_path.set_shader_input(f"boneMats", bone_mats)

            # Disable culling
            self.geom_path.node().setBounds(OmniBoundingVolume())
            self.geom_path.node().setFinal(True)
Example #8
0
                joint.append(index)
                weight.append(value)
            #we need 4 of each
            while len(weight) < 4:
                joint.append(0)
                weight.append(0)
            weight = weight[:4]
            #sum of weights should be == 1.0
            f = 1.0 / sum(weight)
            for i, v in enumerate(weight):
                weight[i] = v * f
            print('        <Aux> joint {{ {0} {1} {2} {3} }}'.format(*joint))
            print('        <Aux> weight {{ {0} {1} {2} {3} }}'.format(*weight))
            print('      }')
        else:
            print(line, end='')
            write_here = False
            membership = {}

if bam_file_name:
    print('Writing bam file...')
    loader = Loader(None)
    egg = loader.load_model(model_file)
    egg.write_bam_file(bam_file_name)
    output_file = bam_file_name

if output_pfm:
    print('Starting animation sampling...')
    app = AnimSampler(output_file)
    app.run()
Example #9
0
def loader():
    return Loader(base=None)
Example #10
0
    def __init__(
        self,
        agent_interfaces,
        traffic_sim,
        envision: EnvisionClient = None,
        visdom: VisdomClient = None,
        timestep_sec=0.1,
        reset_agents_only=False,
        zoo_workers=None,
        auth_key=None,
    ):
        '''
        try:
            super().__init__(self, windowType="offscreen")
        except Exception as e:
            # Known reasons for this failing:
            raise Exception(
                "Display is not found. Try running with different configurations of "
                "`export Display=` using `:0`, `:1`... If this does not work please consult "
                "the documentation."
            ) from e
        '''

        self.loader = Loader(self)
        gltf.patch_loader(self.loader)

        self._log = logging.getLogger(self.__class__.__name__)
        self.__configAspectRatio = ConfigVariableDouble('aspect-ratio',
                                                        0).getValue()
        self._is_setup = False
        self._scenario: Scenario = None
        self._envision: EnvisionClient = envision
        self._visdom: VisdomClient = visdom
        self._timestep_sec = timestep_sec
        self._traffic_sim = traffic_sim
        self._motion_planner_provider = MotionPlannerProvider()
        self._traffic_history_provider = TrafficHistoryProvider()
        self._providers = [
            self._traffic_sim,
            self._motion_planner_provider,
            self._traffic_history_provider,
        ]

        # We buffer provider state between steps to compensate for TRACI's timestep delay
        self._last_provider_state = None
        self._reset_agents_only = reset_agents_only  # a.k.a "teleportation"
        self._imitation_learning_mode = False

        self.finalExitCallbacks = []

        # Global clock always proceeds by a fixed dt on each tick
        from direct.task.TaskManagerGlobal import taskMgr
        self.taskMgr = taskMgr
        self.task_mgr = taskMgr
        self.taskMgr.clock.setMode(ClockObject.M_non_real_time)
        self.taskMgr.clock.setDt(timestep_sec)
        self._elapsed_sim_time = 0

        self.engine = GraphicsEngine.get_global_ptr()

        self.graphicsEngine = self.engine
        fb_prop = FrameBufferProperties()
        fb_prop.rgb_color = 1
        fb_prop.color_bits = 3 * 8
        fb_prop.back_buffers = 1
        self.pipe = GraphicsPipeSelection.get_global_ptr().make_default_pipe()

        flags = GraphicsPipe.BFFbPropsOptional
        flags = flags | GraphicsPipe.BFRefuseWindow
        self.win = self.engine.make_output(
            self.pipe,
            name="window",
            sort=0,
            fb_prop=fb_prop,
            win_prop=WindowProperties(size=(800, 600)),
            flags=flags)

        #self.setBackgroundColor(0, 0, 0, 1)
        #self.win.set_clear_color_active(True)
        #self.win.set_clear_clolor((0.5,0.5,0.5,1))

        self.frameRateMeter = None
        # Displayed framerate is misleading since we are not using a realtime clock
        self.setFrameRateMeter(False)

        self.render = NodePath("render")
        #self.cam = self.render.attach_new_node(Camera("camera"))
        #self.cam.node().set_lens(PerspectiveLens())
        self.camera = None
        self.camList = []
        self.mouse2cam = NodePath(Transform2SG('mouse2cam'))

        self.render.setAttrib(RescaleNormalAttrib.makeDefault())

        self.render.setTwoSided(0)
        self.backfaceCullingEnabled = 1
        self.textureEnabled = 1
        self.wireframeEnabled = 0

        # For macOS GUI. See our `BulletClient` docstring for details.
        # from .utils.bullet import BulletClient
        # self._bullet_client = BulletClient(pybullet.GUI)
        self._bullet_client = bc.BulletClient(pybullet.DIRECT)
        self._pybullet_action_spaces = {
            ActionSpaceType.Continuous,
            ActionSpaceType.Lane,
            ActionSpaceType.ActuatorDynamic,
            ActionSpaceType.LaneWithContinuousSpeed,
            ActionSpaceType.Trajectory,
            ActionSpaceType.MPC,
        }

        # Set up indices
        self._agent_manager = AgentManager(agent_interfaces, zoo_workers,
                                           auth_key)
        self._vehicle_index = VehicleIndex()

        # TODO: Should not be stored in SMARTS
        self._vehicle_collisions = defaultdict(
            list)  # list of `Collision` instances
        self._vehicle_states = []

        self._bubble_manager = None
        self._trap_manager: TrapManager = None

        # SceneGraph-related setup
        self._root_np = None
        self._vehicles_np = None
        self._road_network_np = None
        self._ground_bullet_id = None
Example #11
0
class SMARTS(DirectObject):
    def __init__(
        self,
        agent_interfaces,
        traffic_sim,
        envision: EnvisionClient = None,
        visdom: VisdomClient = None,
        timestep_sec=0.1,
        reset_agents_only=False,
        zoo_workers=None,
        auth_key=None,
    ):
        '''
        try:
            super().__init__(self, windowType="offscreen")
        except Exception as e:
            # Known reasons for this failing:
            raise Exception(
                "Display is not found. Try running with different configurations of "
                "`export Display=` using `:0`, `:1`... If this does not work please consult "
                "the documentation."
            ) from e
        '''

        self.loader = Loader(self)
        gltf.patch_loader(self.loader)

        self._log = logging.getLogger(self.__class__.__name__)
        self.__configAspectRatio = ConfigVariableDouble('aspect-ratio',
                                                        0).getValue()
        self._is_setup = False
        self._scenario: Scenario = None
        self._envision: EnvisionClient = envision
        self._visdom: VisdomClient = visdom
        self._timestep_sec = timestep_sec
        self._traffic_sim = traffic_sim
        self._motion_planner_provider = MotionPlannerProvider()
        self._traffic_history_provider = TrafficHistoryProvider()
        self._providers = [
            self._traffic_sim,
            self._motion_planner_provider,
            self._traffic_history_provider,
        ]

        # We buffer provider state between steps to compensate for TRACI's timestep delay
        self._last_provider_state = None
        self._reset_agents_only = reset_agents_only  # a.k.a "teleportation"
        self._imitation_learning_mode = False

        self.finalExitCallbacks = []

        # Global clock always proceeds by a fixed dt on each tick
        from direct.task.TaskManagerGlobal import taskMgr
        self.taskMgr = taskMgr
        self.task_mgr = taskMgr
        self.taskMgr.clock.setMode(ClockObject.M_non_real_time)
        self.taskMgr.clock.setDt(timestep_sec)
        self._elapsed_sim_time = 0

        self.engine = GraphicsEngine.get_global_ptr()

        self.graphicsEngine = self.engine
        fb_prop = FrameBufferProperties()
        fb_prop.rgb_color = 1
        fb_prop.color_bits = 3 * 8
        fb_prop.back_buffers = 1
        self.pipe = GraphicsPipeSelection.get_global_ptr().make_default_pipe()

        flags = GraphicsPipe.BFFbPropsOptional
        flags = flags | GraphicsPipe.BFRefuseWindow
        self.win = self.engine.make_output(
            self.pipe,
            name="window",
            sort=0,
            fb_prop=fb_prop,
            win_prop=WindowProperties(size=(800, 600)),
            flags=flags)

        #self.setBackgroundColor(0, 0, 0, 1)
        #self.win.set_clear_color_active(True)
        #self.win.set_clear_clolor((0.5,0.5,0.5,1))

        self.frameRateMeter = None
        # Displayed framerate is misleading since we are not using a realtime clock
        self.setFrameRateMeter(False)

        self.render = NodePath("render")
        #self.cam = self.render.attach_new_node(Camera("camera"))
        #self.cam.node().set_lens(PerspectiveLens())
        self.camera = None
        self.camList = []
        self.mouse2cam = NodePath(Transform2SG('mouse2cam'))

        self.render.setAttrib(RescaleNormalAttrib.makeDefault())

        self.render.setTwoSided(0)
        self.backfaceCullingEnabled = 1
        self.textureEnabled = 1
        self.wireframeEnabled = 0

        # For macOS GUI. See our `BulletClient` docstring for details.
        # from .utils.bullet import BulletClient
        # self._bullet_client = BulletClient(pybullet.GUI)
        self._bullet_client = bc.BulletClient(pybullet.DIRECT)
        self._pybullet_action_spaces = {
            ActionSpaceType.Continuous,
            ActionSpaceType.Lane,
            ActionSpaceType.ActuatorDynamic,
            ActionSpaceType.LaneWithContinuousSpeed,
            ActionSpaceType.Trajectory,
            ActionSpaceType.MPC,
        }

        # Set up indices
        self._agent_manager = AgentManager(agent_interfaces, zoo_workers,
                                           auth_key)
        self._vehicle_index = VehicleIndex()

        # TODO: Should not be stored in SMARTS
        self._vehicle_collisions = defaultdict(
            list)  # list of `Collision` instances
        self._vehicle_states = []

        self._bubble_manager = None
        self._trap_manager: TrapManager = None

        # SceneGraph-related setup
        self._root_np = None
        self._vehicles_np = None
        self._road_network_np = None
        self._ground_bullet_id = None

    def setFrameRateMeter(self, flag):
        """
        Turns on or off (according to flag) a standard frame rate
        meter in the upper-right corner of the main window.
        """
        if flag:
            if not self.frameRateMeter:
                self.frameRateMeter = FrameRateMeter('frameRateMeter')
                self.frameRateMeter.setupWindow(self.win)
        else:
            if self.frameRateMeter:
                self.frameRateMeter.clearWindow()
                self.frameRateMeter = None

    def setBackgroundColor(self, r=None, g=None, b=None, a=0.0, win=None):
        """
        Sets the window background color to the indicated value.
        This assumes the window is set up to clear the color each
        frame (this is the normal setting).

        The color may be either a VBase3 or a VBase4, or a 3-component
        tuple, or the individual r, g, b parameters.
        """
        if g is not None:
            color = VBase4(r, g, b, a)
        else:
            arg = r
            if isinstance(arg, VBase4):
                color = arg
            else:
                color = VBase4(arg[0], arg[1], arg[2], a)

        if win is None:
            win = self.win

        if win:
            win.setClearColor(color)

    def step(self, agent_actions):
        if not self._is_setup:
            raise SMARTSNotSetupError(
                "Must call reset() or setup() before stepping.")

        try:
            return self._step(agent_actions)
        except (KeyboardInterrupt, SystemExit):
            # ensure we clean-up if the user exits the simulation
            self._log.info("Simulation was interrupted by the user.")
            self.destroy()
            raise  # re-raise the KeyboardInterrupt
        except Exception as e:
            self._log.error(
                "Simulation crashed with exception. Attempting to cleanly shutdown."
            )
            self._log.exception(e)
            self.destroy()
            raise  # re-raise

    def _step(self, agent_actions):
        """Steps through the simulation while applying the given agent actions.
        Returns the observations, rewards, and done signals.
        """

        # Due to a limitation of our traffic simulator(SUMO) interface(TRACI), we can
        # only observe traffic state of the previous simulation step.
        #
        # To compensate for this, we:
        #
        # 1. Fetch social agent actions
        # 2. Step all providers and harmonize state
        # 3. Step bubble manager
        # 4. Calculate observation and reward
        # 5. Send observations to social agents
        # 6. Clear done agents
        # 7. Perform visualization
        #
        # In this way, observations and reward are computed with data that is
        # consistently with one step of latencey and the agent will observe consistent
        # data.
        dt = self.taskMgr.clock.get_dt()
        self._elapsed_sim_time = self.taskMgr.clock.get_frame_time()

        # 1. Fetch agent actions
        all_agent_actions = self._agent_manager.fetch_agent_actions(
            self, agent_actions)

        # 2. Step all providers and harmonize state
        provider_state = self._step_providers(all_agent_actions, dt)

        # 3. Step bubble manager and trap manager
        self._vehicle_index.sync()
        self._bubble_manager.step(self)
        self._trap_manager.step(self)

        # 4. Calculate observation and reward
        # We pre-compute vehicle_states here because we *think* the users will
        # want these during their observation/reward computations.
        # This is a hack to give us some short term perf wins. Longer term we
        # need to expose better support for batched computations
        self._vehicle_states = [v.state for v in self._vehicle_index.vehicles]

        # Agents
        self._agent_manager.step_sensors(self)

        # Panda3D
        # runs through the render pipeline
        # MUST perform this after step_sensors() above, and before observe() below,
        # so that all updates are ready before rendering happens per frame
        self.taskMgr.mgr.poll()

        observations, rewards, scores, dones = self._agent_manager.observe(
            self)

        response_for_ego = self._agent_manager.filter_response_for_ego(
            (observations, rewards, scores, dones))

        # 5. Send observations to social agents
        self._agent_manager.send_observations_to_social_agents(observations)

        # 6. Clear done agents
        self._teardown_done_agents_and_vehicles(dones)

        # 7. Perform visualization
        self._try_emit_envision_state(provider_state, observations, scores)
        self._try_emit_visdom_obs(observations)

        observations, rewards, scores, dones = response_for_ego
        extras = dict(scores=scores)
        return observations, rewards, dones, extras

    def _teardown_done_agents_and_vehicles(self, dones):
        def done_vehicle_ids(dones):
            vehicle_ids = set()
            for agent_id, done in dones.items():
                if self._agent_manager.is_boid_agent(agent_id):
                    vehicle_ids.update(id_ for id_ in done if done[id_])
                elif done:
                    ids = self._vehicle_index.vehicle_ids_by_actor_id(agent_id)
                    # 0 if shadowing, 1 if active
                    assert len(ids) <= 1, f"{len(ids)} <= 1"
                    vehicle_ids.update(ids)

            return vehicle_ids

        def done_agent_ids(dones):
            agent_ids = set()
            for agent_id, done in dones.items():
                if self._agent_manager.is_boid_agent(agent_id):
                    if not self.agent_manager.is_boid_keep_alive_agent(
                            agent_id) and all(dones[agent_id].values()):
                        agent_ids.add(agent_id)
                elif done:
                    agent_ids.add(agent_id)

            return agent_ids

        # XXX: These can not be put inline because we do queries that must proceed
        #      the actual teardown.
        vehicles_to_teardown = done_vehicle_ids(dones)
        agents_to_teardown = done_agent_ids(dones)

        self._agent_manager.teardown_ego_agents(agents_to_teardown)
        self._agent_manager.teardown_social_agents(agents_to_teardown)
        self._teardown_vehicles(vehicles_to_teardown)

    def reset(self, scenario: Scenario):
        if scenario == self._scenario and self._reset_agents_only:
            vehicle_ids_to_teardown = []
            agent_ids = self._agent_manager.teardown_ego_agents()
            for agent_id in agent_ids:
                ids = self._vehicle_index.vehicle_ids_by_actor_id(agent_id)
                vehicle_ids_to_teardown.extend(ids)
            self._teardown_vehicles(set(vehicle_ids_to_teardown))
            self._trap_manager.init_traps(scenario.road_network,
                                          scenario.waypoints,
                                          scenario.missions)
            self._agent_manager.init_ego_agents(self)
            self._sync_panda3d()
        else:
            self.teardown()
            self.setup(scenario)

        # Tell history provide to ignore vehicles if we have assigned mission to them
        self._traffic_history_provider.set_replaced_ids(
            scenario.missions.keys())

        self.taskMgr.clock.reset()
        self._elapsed_sim_time = 0

        self._vehicle_states = [v.state for v in self._vehicle_index.vehicles]
        observations, _, _, _ = self._agent_manager.observe(self)
        observations_for_ego = self._agent_manager.reset_agents(observations)

        # Visualization
        self._try_emit_visdom_obs(observations)

        if len(self._agent_manager.ego_agent_ids):
            while len(observations_for_ego) < 1:
                observations_for_ego, _, _, _ = self.step({})

        self._reset_providers()

        return observations_for_ego

    def setup(self, scenario: Scenario):
        self._scenario = scenario

        self._root_np = NodePath("sim")
        self._root_np.reparentTo(self.render)

        with pkg_resources.path(
                glsl, "unlit_shader.vert") as vshader_path, pkg_resources.path(
                    glsl, "unlit_shader.frag") as fshader_path:
            unlit_shader = Shader.load(
                Shader.SL_GLSL,
                vertex=str(vshader_path.absolute()),
                fragment=str(fshader_path.absolute()),
            )
        self._root_np.setShader(unlit_shader)
        self._setup_road_network()
        self._vehicles_np = self._root_np.attachNewNode("vehicles")

        self._bubble_manager = BubbleManager(scenario.bubbles,
                                             scenario.road_network)
        self._trap_manager = TrapManager(scenario)

        self._setup_bullet_client(self._bullet_client)
        provider_state = self._setup_providers(self._scenario)
        self._agent_manager.setup_agents(self)

        self._harmonize_providers(provider_state)
        self._last_provider_state = provider_state

        self._is_setup = True

    def add_provider(self, provider):
        self._providers.append(provider)

    def _setup_road_network(self):
        glb_path = self.scenario.map_glb_filepath
        if self._road_network_np:
            self._log.debug(
                "road_network={} already exists. Removing and adding a new "
                "one from glb_path={}".format(self._road_network_np, glb_path))
        model_np = self.loader.loadModel(glb_path, noCache=True)

        np = self._root_np.attachNewNode("road_network")
        model_np.reparent_to(np)
        np.hide(RenderMasks.OCCUPANCY_HIDE)
        np.setColor(SceneColors.Road.value)
        self._road_network_np = np

    def _setup_bullet_client(self, client: bc.BulletClient):
        client.resetSimulation()
        client.configureDebugVisualizer(pybullet.COV_ENABLE_GUI, 0)

        # PyBullet defaults the timestep to 240Hz. Several parameters are tuned with
        # this value in mind. For example the number of solver iterations and the error
        # reduction parameters (erp) for contact, friction and non-contact joints.
        # Attempting to get around this we set the number of substeps so that
        # timestep * substeps = 240Hz. Bullet (C++) does something to this effect as
        # well (https://git.io/Jvf0M), but PyBullet does not expose it.
        client.setPhysicsEngineParameter(
            fixedTimeStep=self._timestep_sec,
            numSubSteps=int(self._timestep_sec * 240),
            numSolverIterations=10,
            solverResidualThreshold=0.001,
            # warmStartingFactor=0.99
        )

        client.setGravity(0, 0, -9.8)

        plane_path = self._scenario.plane_filepath

        # 1e6 is the default value for plane length and width.
        plane_scale = (max(self._scenario.map_bounding_box[0],
                           self._scenario.map_bounding_box[1]) / 1e6)
        if not os.path.exists(plane_path):
            with pkg_resources.path(models, "plane.urdf") as path:
                plane_path = str(path.absolute())

        self._ground_bullet_id = client.loadURDF(
            plane_path,
            useFixedBase=True,
            basePosition=self._scenario.map_bounding_box[2],
            globalScaling=1.1 * plane_scale,
        )

    def makeCamera(self,
                   win,
                   sort=0,
                   scene=None,
                   displayRegion=(0, 1, 0, 1),
                   stereo=None,
                   aspectRatio=None,
                   clearDepth=0,
                   clearColor=None,
                   lens=None,
                   camName='cam',
                   mask=None,
                   useCamera=None):
        """
        Makes a new 3-d camera associated with the indicated window,
        and creates a display region in the indicated subrectangle.

        If stereo is True, then a stereo camera is created, with a
        pair of DisplayRegions.  If stereo is False, then a standard
        camera is created.  If stereo is None or omitted, a stereo
        camera is created if the window says it can render in stereo.

        If useCamera is not None, it is a NodePath to be used as the
        camera to apply to the window, rather than creating a new
        camera.

        :rtype: panda3d.core.NodePath
        """
        # self.camera is the parent node of all cameras: a node that
        # we can move around to move all cameras as a group.
        if self.camera is None:
            # We make it a ModelNode with the PTLocal flag, so that
            # a wayward flatten operations won't attempt to mangle the
            # camera.
            self.camera = self.render.attachNewNode(ModelNode('camera'))
            self.camera.node().setPreserveTransform(ModelNode.PTLocal)
            builtins.camera = self.camera

            self.mouse2cam.node().setNode(self.camera.node())

        if useCamera:
            # Use the existing camera node.
            cam = useCamera
            camNode = useCamera.node()
            assert (isinstance(camNode, Camera))
            lens = camNode.getLens()
            cam.reparentTo(self.camera)

        else:
            # Make a new Camera node.
            camNode = Camera(camName)
            if lens is None:
                lens = PerspectiveLens()

                if aspectRatio is None:
                    aspectRatio = self.getAspectRatio(win)
                lens.setAspectRatio(aspectRatio)

            cam = self.camera.attachNewNode(camNode)

        if lens is not None:
            camNode.setLens(lens)

        if scene is not None:
            camNode.setScene(scene)

        if mask is not None:
            if (isinstance(mask, int)):
                mask = BitMask32(mask)
            camNode.setCameraMask(mask)

        if self.cam is None:
            self.cam = cam
            self.camNode = camNode
            self.camLens = lens

        self.camList.append(cam)

        # Now, make a DisplayRegion for the camera.
        if stereo is not None:
            if stereo:
                dr = win.makeStereoDisplayRegion(*displayRegion)
            else:
                dr = win.makeMonoDisplayRegion(*displayRegion)
        else:
            dr = win.makeDisplayRegion(*displayRegion)

        dr.setSort(sort)

        # By default, we do not clear 3-d display regions (the entire
        # window will be cleared, which is normally sufficient).  But
        # we will if clearDepth is specified.
        if clearDepth:
            dr.setClearDepthActive(1)

        if clearColor:
            dr.setClearColorActive(1)
            dr.setClearColor(clearColor)

        dr.setCamera(cam)

        return cam

    def getAspectRatio(self, win=None):
        # Returns the actual aspect ratio of the indicated (or main
        # window), or the default aspect ratio if there is not yet a
        # main window.

        # If the config it set, we return that
        if self.__configAspectRatio:
            return self.__configAspectRatio

        aspectRatio = 1

        if win is None:
            win = self.win

        if win is not None and win.hasSize() and win.getSbsLeftYSize() != 0:
            aspectRatio = float(win.getSbsLeftXSize()) / float(
                win.getSbsLeftYSize())
        else:
            if win is None or not hasattr(win, "getRequestedProperties"):
                props = WindowProperties.getDefault()
            else:
                props = win.getRequestedProperties()
                if not props.hasSize():
                    props = WindowProperties.getDefault()

            if props.hasSize() and props.getYSize() != 0:
                aspectRatio = float(props.getXSize()) / float(props.getYSize())

        if aspectRatio == 0:
            return 1

        return aspectRatio

    def makeCamera2d(self,
                     win,
                     sort=10,
                     displayRegion=(0, 1, 0, 1),
                     coords=(-1, 1, -1, 1),
                     lens=None,
                     cameraName=None):
        """
        Makes a new camera2d associated with the indicated window, and
        assigns it to render the indicated subrectangle of render2d.

        :rtype: panda3d.core.NodePath
        """
        dr = win.makeMonoDisplayRegion(*displayRegion)
        dr.setSort(sort)

        # Enable clearing of the depth buffer on this new display
        # region (see the comment in setupRender2d, above).
        dr.setClearDepthActive(1)

        # Make any texture reloads on the gui come up immediately.
        dr.setIncompleteRender(False)

        left, right, bottom, top = coords

        # Now make a new Camera node.
        if (cameraName):
            cam2dNode = Camera('cam2d_' + cameraName)
        else:
            cam2dNode = Camera('cam2d')

        if lens is None:
            lens = OrthographicLens()
            lens.setFilmSize(right - left, top - bottom)
            lens.setFilmOffset((right + left) * 0.5, (top + bottom) * 0.5)
            lens.setNearFar(-1000, 1000)
        cam2dNode.setLens(lens)

        # self.camera2d is the analog of self.camera, although it's
        # not as clear how useful it is.
        if self.camera2d is None:
            self.camera2d = self.render2d.attachNewNode('camera2d')

        camera2d = self.camera2d.attachNewNode(cam2dNode)
        dr.setCamera(camera2d)

        if self.cam2d is None:
            self.cam2d = camera2d

        return camera2d

    def makeCamera2dp(self,
                      win,
                      sort=20,
                      displayRegion=(0, 1, 0, 1),
                      coords=(-1, 1, -1, 1),
                      lens=None,
                      cameraName=None):
        """
        Makes a new camera2dp associated with the indicated window, and
        assigns it to render the indicated subrectangle of render2dp.

        :rtype: panda3d.core.NodePath
        """
        dr = win.makeMonoDisplayRegion(*displayRegion)
        dr.setSort(sort)

        # Unlike render2d, we don't clear the depth buffer for
        # render2dp.  Caveat emptor.

        if hasattr(dr, 'setIncompleteRender'):
            dr.setIncompleteRender(False)

        left, right, bottom, top = coords

        # Now make a new Camera node.
        if (cameraName):
            cam2dNode = Camera('cam2dp_' + cameraName)
        else:
            cam2dNode = Camera('cam2dp')

        if lens is None:
            lens = OrthographicLens()
            lens.setFilmSize(right - left, top - bottom)
            lens.setFilmOffset((right + left) * 0.5, (top + bottom) * 0.5)
            lens.setNearFar(-1000, 1000)
        cam2dNode.setLens(lens)

        # self.camera2d is the analog of self.camera, although it's
        # not as clear how useful it is.
        if self.camera2dp is None:
            self.camera2dp = self.render2dp.attachNewNode('camera2dp')

        camera2dp = self.camera2dp.attachNewNode(cam2dNode)
        dr.setCamera(camera2dp)

        if self.cam2dp is None:
            self.cam2dp = camera2dp

        return camera2dp

    '''
    def destroy(self):
        """ Call this function to destroy the ShowBase and stop all
        its tasks, freeing all of the Panda resources.  Normally, you
        should not need to call it explicitly, as it is bound to the
        exitfunc and will be called at application exit time
        automatically.

        This function is designed to be safe to call multiple times."""

        for cb in self.finalExitCallbacks[:]:
            cb()

        # Remove the built-in base reference
        if getattr(builtins, 'base', None) is self:
            del builtins.run
            del builtins.base
            del builtins.loader
            del builtins.taskMgr
            import sys
            ShowBaseGlobal = sys.modules.get('direct.showbase.ShowBaseGlobal', None)
            if ShowBaseGlobal:
                del ShowBaseGlobal.base

        #self.aspect2d.node().removeAllChildren()
        #self.render2d.node().removeAllChildren()
        #self.aspect2d.reparent_to(self.render2d)

        # [gjeon] restore sticky key settings
        if self.config.GetBool('disable-sticky-keys', 0):
            allowAccessibilityShortcutKeys(True)

        #self.ignoreAll()
        self.shutdown()

        if getattr(self, 'musicManager', None):
            self.musicManager.shutdown()
            self.musicManager = None
            for sfxManager in self.sfxManagerList:
                sfxManager.shutdown()
            self.sfxManagerList = []
        if getattr(self, 'loader', None):
            self.loader.destroy()
            self.loader = None
        if getattr(self, 'graphicsEngine', None):
            self.graphicsEngine.removeAllWindows()

        try:
            self.direct.panel.destroy()
        except:
            pass

        if hasattr(self, 'win'):
            del self.win
            #del self.winList
            del self.pipe
    '''

    def shutdown(self):
        self.taskMgr.remove('audioLoop')
        self.taskMgr.remove('igLoop')
        self.taskMgr.remove('shadowCollisionLoop')
        self.taskMgr.remove('collisionLoop')
        self.taskMgr.remove('dataLoop')
        self.taskMgr.remove('resetPrevTransform')
        self.taskMgr.remove('ivalLoop')
        self.taskMgr.remove('garbageCollectStates')
        #self.eventMgr.shutdown()

    def teardown(self):
        self._agent_manager.teardown()
        self._vehicle_index.teardown()

        self._bullet_client.resetSimulation()
        self._traffic_sim.teardown()
        self._teardown_providers()

        if self._root_np is not None:
            self._root_np.clearLight()
            self._root_np.removeNode()

        if self._bubble_manager is not None:
            self._bubble_manager.teardown()
            self._bubble_manager = None

        if self._trap_manager is not None:
            self._trap_manager.teardown()
            self._trap_manager = None

        self._vehicles_np = None
        self._ground_bullet_id = None
        self._road_network_np = None
        self._is_setup = False

    def destroy(self):
        self.teardown()

        if self._envision:
            self._envision.teardown()

        if self._visdom:
            self._visdom.teardown()

        self._agent_manager.destroy()
        self._bullet_client.disconnect()

        self.loader.destroy()

    def _teardown_vehicles(self, vehicle_ids):
        self._vehicle_index.teardown_vehicles_by_vehicle_ids(vehicle_ids)
        self._clear_collisions(vehicle_ids)

    def attach_sensors_to_vehicles(self, agent_spec, vehicle_ids):
        self._agent_manager.attach_sensors_to_vehicles(self,
                                                       agent_spec.interface,
                                                       vehicle_ids)

    def observe_from(self, vehicle_ids):
        return self._agent_manager.observe_from(self, vehicle_ids)

    @property
    def road_stiffness(self):
        return self._bullet_client.getDynamicsInfo(self._ground_bullet_id,
                                                   -1)[9]

    @property
    def traffic_sim(self) -> SumoTrafficSimulation:
        return self._traffic_sim

    @property
    def waypoints(self) -> Waypoints:
        return self.scenario.waypoints

    @property
    def road_network(self) -> SumoRoadNetwork:
        return self.scenario.road_network

    @property
    def np(self):
        return self._root_np

    @property
    def vehicles_np(self):
        return self._vehicles_np

    @property
    def bc(self):
        return self._bullet_client

    @property
    def envision(self):
        return self._envision

    @property
    def elapsed_sim_time(self):
        return self._elapsed_sim_time

    def teardown_agents_without_vehicles(self, agent_ids: Sequence):
        """
        Teardown agents in the given list that have no vehicles registered as
        controlled-by or shadowed-by

        Params:
            agent_ids: Sequence of agent ids
        """
        agents_to_teardown = {
            agent_id
            for agent_id in agent_ids
            # Only clean-up when there are no controlled agents left (e.g. boids)
            if len(
                self._vehicle_index.vehicles_by_actor_id(
                    agent_id, include_shadowers=True)) == 0
        }

        agents_to_teardown = {
            id_
            for id_ in agents_to_teardown
            if not self.agent_manager.is_boid_keep_alive_agent(id_)
        }
        self.agent_manager.teardown_social_agents(
            filter_ids=agents_to_teardown)

    def _teardown_vehicles_and_agents(self, vehicle_ids):
        shadow_and_controlling_agents = set()
        for vehicle_id in vehicle_ids:
            agent_id = self._vehicle_index.actor_id_from_vehicle_id(vehicle_id)
            if agent_id:
                shadow_and_controlling_agents.add(agent_id)

            shadow_agent_id = self._vehicle_index.shadow_actor_id_from_vehicle_id(
                vehicle_id)
            if shadow_agent_id:
                shadow_and_controlling_agents.add(shadow_agent_id)

        self._vehicle_index.teardown_vehicles_by_vehicle_ids(vehicle_ids)
        self.teardown_agents_without_vehicles(shadow_and_controlling_agents)

    def _pybullet_provider_sync(self, provider_state: ProviderState):
        current_vehicle_ids = {v.vehicle_id for v in provider_state.vehicles}
        previous_sv_ids = self._vehicle_index.social_vehicle_ids()
        exited_vehicles = previous_sv_ids - current_vehicle_ids
        self._teardown_vehicles_and_agents(exited_vehicles)

        # Update our pybullet world given this provider state
        for vehicle in provider_state.vehicles:
            vehicle_id = vehicle.vehicle_id
            # either this is a pybullet agent vehicle, or it is a social vehicle
            if vehicle_id in self._vehicle_index.agent_vehicle_ids():
                # this is an agent vehicle
                agent_id = self._vehicle_index.actor_id_from_vehicle_id(
                    vehicle_id)
                agent_interface = self._agent_manager.agent_interface_for_agent_id(
                    agent_id)
                agent_action_space = agent_interface.action_space
                if agent_action_space in self._pybullet_action_spaces:
                    # This is a pybullet agent, we were the source of this vehicle state.
                    # No need to make any changes
                    continue
                else:
                    # This is not a pybullet agent, but it has an avatar in this world
                    # to make it's observations. Update the avatar to match the new
                    # state of this vehicle
                    pybullet_vehicle = self._vehicle_index.vehicle_by_id(
                        vehicle_id)
                    pybullet_vehicle.set_pose(vehicle.pose)
                    pybullet_vehicle.set_speed(vehicle.speed)
            else:
                # This vehicle is a social vehicle
                if vehicle_id in self._vehicle_index.social_vehicle_ids():
                    social_vehicle = self._vehicle_index.vehicle_by_id(
                        vehicle_id)
                else:
                    # It is a new social vehicle we have not seen yet.
                    # Create it's avatar.
                    social_vehicle = self._vehicle_index.build_social_vehicle(
                        sim=self,
                        vehicle_state=vehicle,
                        actor_id=vehicle_id,
                        vehicle_id=vehicle_id,
                        vehicle_type=vehicle.vehicle_type,
                    )
                # Update the social vehicle avatar to match the vehicle state
                social_vehicle.control(pose=vehicle.pose, speed=vehicle.speed)

    def _pybullet_provider_step(self, agent_actions) -> ProviderState:
        self._perform_agent_actions(agent_actions)

        self._bullet_client.stepSimulation()

        self._process_collisions()

        provider_state = ProviderState()
        pybullet_agent_ids = {
            agent_id
            for agent_id, interface in
            self._agent_manager.agent_interfaces.items()
            if interface.action_space in self._pybullet_action_spaces
        }

        for vehicle_id in self._vehicle_index.agent_vehicle_ids():
            agent_id = self._vehicle_index.actor_id_from_vehicle_id(vehicle_id)
            if agent_id not in pybullet_agent_ids:
                continue

            vehicle = self._vehicle_index.vehicle_by_id(vehicle_id)
            vehicle.step(self._elapsed_sim_time)
            provider_state.vehicles.append(
                VehicleState(
                    vehicle_id=vehicle.id,
                    vehicle_type="passenger",
                    pose=vehicle.pose,
                    dimensions=vehicle.chassis.dimensions,
                    speed=vehicle.speed,
                    source="PYBULLET",
                ))

        return provider_state

    @property
    def vehicle_index(self):
        return self._vehicle_index

    @property
    def agent_manager(self):
        return self._agent_manager

    @property
    def providers(self):
        # TODO: Add check to ensure that action spaces are disjoint between providers
        # TODO: It's inconsistent that pybullet is not here
        return self._providers

    def _setup_providers(self, scenario) -> ProviderState:
        provider_state = ProviderState()
        for provider in self.providers:
            provider_state.merge(provider.setup(scenario))

        return provider_state

    def _teardown_providers(self):
        for provider in self.providers:
            provider.teardown()

        self._last_provider_state = None

    def _harmonize_providers(self, provider_state: ProviderState):
        for provider in self.providers:
            provider.sync(provider_state)

        self._pybullet_provider_sync(provider_state)
        self._sync_panda3d()

    def _reset_providers(self):
        for provider in self.providers:
            provider.reset()

    def _step_providers(self, actions, dt) -> List[VehicleState]:
        accumulated_provider_state = ProviderState()

        def agent_controls_vehicles(agent_id):
            vehicles = self._vehicle_index.vehicles_by_actor_id(agent_id)
            return len(vehicles) > 0

        def matches_provider_action_spaces(agent_id, action_spaces):
            interface = self._agent_manager.agent_interface_for_agent_id(
                agent_id)
            return interface.action_space in action_spaces

        # PyBullet
        pybullet_actions = {
            agent_id: action
            for agent_id, action in actions.items()
            if agent_controls_vehicles(agent_id)
            and matches_provider_action_spaces(agent_id,
                                               self._pybullet_action_spaces)
        }
        accumulated_provider_state.merge(
            self._pybullet_provider_step(pybullet_actions))

        for provider in self.providers:
            provider_state = self._step_provider(provider, actions, dt,
                                                 self._elapsed_sim_time)
            if provider == self._traffic_sim:
                # Remove agent vehicles from provider vehicles
                provider_state.filter(self._vehicle_index.agent_vehicle_ids())

            accumulated_provider_state.merge(provider_state)

        self._harmonize_providers(accumulated_provider_state)
        return accumulated_provider_state

    def _step_provider(self, provider, actions, dt, elapsed_sim_time):
        def agent_controls_vehicles(agent_id):
            vehicles = self._vehicle_index.vehicles_by_actor_id(agent_id)
            return len(vehicles) > 0

        provider_actions = {}
        for agent_id, action in actions.items():
            agent_interface = self._agent_manager.agent_interface_for_agent_id(
                agent_id)
            if (agent_interface and agent_controls_vehicles(agent_id) and
                    agent_interface.action_space in provider.action_spaces):
                vehicle_ids = [
                    v.id for v in self._vehicle_index.vehicles_by_actor_id(
                        agent_id, include_shadowers=True)
                ]

                if self._agent_manager.is_boid_agent(agent_id):
                    for vehicle_id, vehicle_action in action.items():
                        assert vehicle_id in vehicle_ids
                        provider_actions[vehicle_id] = vehicle_action
                else:
                    assert len(vehicle_ids) == 1
                    provider_actions[vehicle_ids[0]] = action

        provider_state = provider.step(provider_actions, dt, elapsed_sim_time)
        return provider_state

    @property
    def scenario(self):
        return self._scenario

    @property
    def traffic_sim(self):
        return self._traffic_sim

    @property
    def np(self):
        return self._root_np

    @property
    def timestep_sec(self):
        return self._timestep_sec

    @property
    def road_stiffness(self):
        return self._bullet_client.getDynamicsInfo(self._ground_bullet_id,
                                                   -1)[9]

    def neighborhood_vehicles_around_vehicle(self, vehicle, radius=None):
        other_states = [
            v for v in self._vehicle_states if v.vehicle_id != vehicle.id
        ]
        if radius is None:
            return other_states

        other_positions = [state.pose.position for state in other_states]
        if not other_positions:
            return []

        distances = euclidean_distances(other_positions,
                                        [vehicle.position]).reshape(-1, )
        indices = numpy.argwhere(distances <= radius).flatten()
        return [other_states[i] for i in indices]

    def vehicle_did_collide(self, vehicle_id):
        return (len([
            c for c in self._vehicle_collisions[vehicle_id]
            if c.collidee_id != self._ground_bullet_id
        ]) > 0)

    def vehicle_collisions(self, vehicle_id):
        return [
            c for c in self._vehicle_collisions[vehicle_id]
            if c.collidee_id != self._ground_bullet_id
        ]

    def _clear_collisions(self, vehicle_ids):
        for vehicle_id in vehicle_ids:
            self._vehicle_collisions.pop(vehicle_id, None)

    def _perform_agent_actions(self, agent_actions):
        for agent_id, action in agent_actions.items():
            agent_vehicles = self._vehicle_index.vehicles_by_actor_id(agent_id)
            if len(agent_vehicles) == 0:
                self._log.warning(
                    f"{agent_id} doesn't have a vehicle, is the agent done? (dropping action)"
                )
            else:
                agent_interface = self._agent_manager.agent_interface_for_agent_id(
                    agent_id)
                is_boid_agent = self._agent_manager.is_boid_agent(agent_id)

                for vehicle in agent_vehicles:
                    vehicle_action = action[
                        vehicle.id] if is_boid_agent else action

                    controller_state = self._vehicle_index.controller_state_for_vehicle_id(
                        vehicle.id)
                    sensor_state = self._vehicle_index.sensor_state_for_vehicle_id(
                        vehicle.id)
                    # TODO: Support performing batched actions
                    Controllers.perform_action(
                        self,
                        agent_id,
                        vehicle,
                        vehicle_action,
                        controller_state,
                        sensor_state,
                        agent_interface.action_space,
                        agent_interface.vehicle_type,
                    )

    def _sync_panda3d(self):
        for vehicle in self._vehicle_index.vehicles:
            vehicle.sync_to_panda3d()

    def _process_collisions(self):
        self._vehicle_collisions = defaultdict(
            list)  # list of `Collision` instances

        for vehicle_id in self._vehicle_index.agent_vehicle_ids():
            vehicle = self._vehicle_index.vehicle_by_id(vehicle_id)
            # We are only concerned with vehicle-vehicle collisions
            collidee_bullet_ids = set(
                [p.bullet_id for p in vehicle.chassis.contact_points])
            collidee_bullet_ids.discard(self._ground_bullet_id)

            if not collidee_bullet_ids:
                continue

            for bullet_id in collidee_bullet_ids:
                collidee = self._bullet_id_to_vehicle(bullet_id)
                collision = self._node_to_collision(collidee.np.node())
                self._vehicle_collisions[vehicle_id].append(collision)

    def _bullet_id_to_vehicle(self, bullet_id):
        for vehicle in self._vehicle_index.vehicles:
            if bullet_id == vehicle.chassis.bullet_id:
                return vehicle

        assert False, "Only collisions with agent or social vehicles is supported"

    def _node_to_collision(self, node):
        for vehicle in self._vehicle_index.vehicles:
            if node == vehicle.np.node():
                actor_id = self._vehicle_index.actor_id_from_vehicle_id(
                    vehicle.id)
                # TODO: Should we specify the collidee as the vehicle ID instead of
                #       the agent/social ID?
                return Collision(collidee_id=actor_id)

        assert False, "Only collisions with agent or social vehicles is supported"

    def _try_emit_envision_state(self, provider_state, obs, scores):
        if not self._envision:
            return

        traffic = {}
        for v in provider_state.vehicles:
            if v.vehicle_id in self._vehicle_index.agent_vehicle_ids():
                # this is an agent controlled vehicle
                agent_id = self._vehicle_index.actor_id_from_vehicle_id(
                    v.vehicle_id)
                agent_obs = obs[agent_id]
                is_boid_agent = self._agent_manager.is_boid_agent(agent_id)
                vehicle_obs = agent_obs[
                    v.vehicle_id] if is_boid_agent else agent_obs

                if self._agent_manager.is_ego(agent_id):
                    actor_type = envision_types.TrafficActorType.Agent
                    mission_route_geometry = self._vehicle_index.sensor_state_for_vehicle_id(
                        v.vehicle_id).mission_planner.route.geometry
                else:
                    actor_type = envision_types.TrafficActorType.SocialAgent
                    mission_route_geometry = None

                point_cloud = vehicle_obs.lidar_point_cloud or ([], [], [])
                point_cloud = point_cloud[
                    0]  # (points, hits, rays), just want points

                # TODO: driven path should be read from vehicle_obs
                driven_path = self._vehicle_index.vehicle_by_id(
                    v.vehicle_id).driven_path_sensor()

                road_waypoints = []
                if vehicle_obs.road_waypoints:
                    road_waypoints = [
                        path
                        for paths in vehicle_obs.road_waypoints.lanes.values()
                        for path in paths
                    ]
                traffic[v.vehicle_id] = envision_types.TrafficActorState(
                    name=self._agent_manager.agent_name(agent_id),
                    actor_type=actor_type,
                    vehicle_type=envision_types.VehicleType.Car,
                    position=v.pose.position,
                    heading=v.pose.heading,
                    speed=v.speed,
                    actor_id=envision_types.format_actor_id(
                        agent_id,
                        v.vehicle_id,
                        is_multi=is_boid_agent,
                    ),
                    events=vehicle_obs.events,
                    waypoint_paths=(vehicle_obs.waypoint_paths or []) +
                    road_waypoints,
                    point_cloud=point_cloud,
                    driven_path=driven_path,
                    mission_route_geometry=mission_route_geometry,
                )
            elif v.vehicle_id in self._vehicle_index.social_vehicle_ids():
                # this is a social vehicle
                traffic[v.vehicle_id] = envision_types.TrafficActorState(
                    actor_type=envision_types.TrafficActorType.SocialVehicle,
                    vehicle_type=v.vehicle_type,
                    position=list(v.pose.position),
                    heading=v.pose.heading,
                    speed=v.speed,
                )

        bubble_geometry = [
            list(bubble.geometry.exterior.coords)
            for bubble in self._bubble_manager.bubbles
        ]

        state = envision_types.State(
            traffic=traffic,
            scenario_id=self.scenario.scenario_hash,
            bubbles=bubble_geometry,
            scene_colors=SceneColors.EnvisionColors.value,
            scores=scores,
        )
        self._envision.send(state)

    def _try_emit_visdom_obs(self, obs):
        if not self._visdom:
            return

        self._visdom.send(obs)
Example #12
0
    def __init__(self):
        DirectObject.__init__(self)

        if ConfigVariableBool("want-pstats", False):
            PStatClient.connect()

        self.docTitle = ""
        self.viewportName = ""

        self.renderRequested = False

        ###################################################################
        # Minimal emulation of ShowBase glue code. Note we're not using
        # ShowBase because there's too much going on in there that assumes
        # too much (one camera, one lens, one aspect2d, lots of bloat).

        self.graphicsEngine = GraphicsEngine.getGlobalPtr()
        self.pipe = GraphicsPipeSelection.getGlobalPtr().makeDefaultPipe()
        if not self.pipe:
            self.notify.error("No graphics pipe is available!")
            return

        self.globalClock = ClockObject.getGlobalClock()
        # Since we have already started up a TaskManager, and probably
        # a number of tasks; and since the TaskManager had to use the
        # TrueClock to tell time until this moment, make sure the
        # globalClock object is exactly in sync with the TrueClock.
        trueClock = TrueClock.getGlobalPtr()
        self.globalClock.setRealTime(trueClock.getShortTime())
        self.globalClock.tick()
        builtins.globalClock = self.globalClock

        self.loader = Loader(self)
        self.graphicsEngine.setDefaultLoader(self.loader.loader)
        builtins.loader = self.loader

        self.taskMgr = taskMgr
        builtins.taskMgr = self.taskMgr

        self.dgTrav = DataGraphTraverser()

        self.dataRoot = NodePath("data")
        self.hidden = NodePath("hidden")

        self.aspect2d = NodePath("aspect2d")
        builtins.aspect2d = self.aspect2d

        # Messages that are sent regardless of the active document.
        self.messenger = messenger
        builtins.messenger = self.messenger

        self.eventMgr = eventMgr
        builtins.eventMgr = self.eventMgr
        self.eventMgr.restart()

        builtins.base = self
        builtins.hidden = self.hidden

        ###################################################################

        self.clickTrav = CollisionTraverser()

        # All open documents.
        self.documents = []
        # The focused document.
        self.document = None

        TextNode.setDefaultFont(loader.loadFont("models/fonts/consolas.ttf"))

        self.initialize()
Example #13
0
    def __init__(self):
        ShowBase.__init__(self)
        props = WindowProperties()
        props.setTitle("The Rat Cave")
        self.win.requestProperties(props)
        self.win.setClearColor((0.5, 0.5, 0.9, 1.0))
        self.disableMouse()
        self.locked = False
        lens = PerspectiveLens()
        lens.set_fov(70)
        self.cam.node().setLens(lens)
        self.position = [30, 30, 30]
        self.velocity = [0, 0, 0]
        self.setFrameRateMeter(True)
        self.myFog = Fog("Fog Name")
        self.myFog.setColor(0.5, 0.5, 0.9)
        self.myFog.setExpDensity(0.005)
        render.setFog(self.myFog)
        #cool bg
        #b=OnscreenImage(parent=render2d, image="space.png")
        #base.cam.node().getDisplayRegion(0).setSort(20)

        render.setAntialias(AntialiasAttrib.MMultisample)

        debugNode = BulletDebugNode('Debug')
        debugNode.showWireframe(True)
        debugNode.showConstraints(True)
        debugNode.showBoundingBoxes(False)
        debugNode.showNormals(False)
        debugNP = render.attachNewNode(debugNode)
        debugNP.show()

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -80))
        #self.world.setDebugNode(debugNP.node())

        loader = Loader(self)
        myShader = Shader.load(Shader.SL_GLSL,
                               vertex="vertshader.vert",
                               fragment="fragshader.frag")
        floorMesh = BulletTriangleMesh()

        texs = [
            loader.loadTexture("flatstone.png"),
            loader.loadTexture("flatstone2.png"),
            loader.loadTexture("flatgrass.png"),
            loader.loadTexture("flatgrass2.png"),
            loader.loadTexture("flatrock.png"),
            loader.loadTexture("flatrock2.png"),
            loader.loadTexture("flatsnow.png"),
            loader.loadTexture("flatsand.png"),
            loader.loadTexture("flatsand2.png")
        ]
        hmap = generator.generate(200, 200, 50, 0.01, 5)
        groundTypes = [[] for x in range(9)]
        for thing in hmap:
            groundTypes[thing[3]].append(thing[0:3])
        for i in range(len(groundTypes)):
            if len(groundTypes[i]) == 0:
                continue
            format = GeomVertexFormat.get_v3n3t2()
            format = GeomVertexFormat.registerFormat(format)
            vdata = GeomVertexData('name', format, Geom.UHStatic)
            vdata.setNumRows(3)
            vertex = GeomVertexWriter(vdata, 'vertex')
            normal = GeomVertexWriter(vdata, 'normal')
            texcoord = GeomVertexWriter(vdata, 'texcoord')
            prim = GeomTriangles(Geom.UHStatic)
            for grid in groundTypes[i]:
                v0 = (grid[0][0], grid[0][2], grid[0][1])
                vertex.addData3(v0)
                if grid[1][2] < 0:
                    normal.addData3(grid[1][0], grid[1][2], grid[1][1])
                else:
                    normal.addData3(-grid[1][0], -grid[1][2], -grid[1][1])
                texcoord.addData2(grid[2][0], grid[2][1])
                v1 = (grid[0][3], grid[0][5], grid[0][4])
                vertex.addData3(v1)
                if grid[1][5] < 0:
                    normal.addData3(grid[1][3], grid[1][5], grid[1][4])
                else:
                    normal.addData3(-grid[1][3], -grid[1][5], -grid[1][4])
                texcoord.addData2(grid[2][2], grid[2][3])
                v2 = (grid[0][6], grid[0][8], grid[0][7])
                vertex.addData3(v2)
                if grid[1][8] < 0:
                    normal.addData3(grid[1][6], grid[1][8], grid[1][7])
                else:
                    normal.addData3(-grid[1][6], -grid[1][8], -grid[1][7])
                texcoord.addData2(grid[2][4], grid[2][5])
                floorMesh.addTriangle(v0, v1, v2)
                prim.add_next_vertices(3)
            geom = Geom(vdata)
            geom.addPrimitive(prim)
            node = GeomNode('gnode')
            node.addGeom(geom)
            nodePath = render.attachNewNode(node)
            nodePath.setTexture(texs[i])
            nodePath.setShader(myShader)
        vdata2 = GeomVertexData('wata', format, Geom.UHStatic)
        vdata2.setNumRows(3)
        prim2 = GeomTriangles(Geom.UHStatic)
        vertex2 = GeomVertexWriter(vdata2, 'vertex')
        normal2 = GeomVertexWriter(vdata2, 'normal')
        texcoord2 = GeomVertexWriter(vdata2, 'texcoord')
        vertex2.addData3((0, 0, 0))
        vertex2.addData3((200, 0, 0))
        vertex2.addData3((0, 200, 0))
        normal2.addData3((0, 0, 1))
        normal2.addData3((0, 0, 1))
        normal2.addData3((0, 0, 1))
        texcoord2.addData2((0, 0))
        texcoord2.addData2((1, 0))
        texcoord2.addData2((0, 1))
        prim2.addNextVertices(3)
        vertex2.addData3((200, 200, 0))
        vertex2.addData3((0, 200, 0))
        vertex2.addData3((200, 0, 0))
        normal2.addData3((0, 0, 1))
        normal2.addData3((0, 0, 1))
        normal2.addData3((0, 0, 1))
        texcoord2.addData2((1, 1))
        texcoord2.addData2((0, 1))
        texcoord2.addData2((1, 0))
        prim2.addNextVertices(3)
        water = Geom(vdata2)
        water.addPrimitive(prim2)
        waterNode = GeomNode('water')
        waterNode.addGeom(water)
        waterNodePath = render.attachNewNode(waterNode)
        waterNodePath.setTransparency(True)
        waterNodePath.setTexture(loader.loadTexture("water.png"))
        floorMeshShape = BulletTriangleMeshShape(floorMesh, dynamic=False)
        fNode = BulletRigidBodyNode('floor')
        fNode.addShape(floorMeshShape)
        self.floorPhysNode = render.attachNewNode(fNode)
        self.world.attachRigidBody(fNode)
        for i in range(25):
            rat = loader.loadModel("deer.obj")
            rat.setScale((0.003, 0.003, 0.003))
            rat.setHpr((0, 90, 0))
            rat.setPos((0, 0, -0.8))
            rat.setTexture(texs[5])

            shape = BulletSphereShape(1)
            node = BulletRigidBodyNode('ratBox')
            #node.setAngularFactor((0,0,1))
            node.setMass(10.0)
            node.addShape(shape)
            node.setActive(False)
            #node.friction = 1
            np = render.attachNewNode(node)
            np.setPos((i % 5) * 2 + 40, int(i / 5) * 2 + 40, 50)
            self.world.attachRigidBody(node)
            rat.flattenLight()
            rat.reparentTo(np)
            #posInterval1 = rat.hprInterval(0.1,
            #							 Point3(10, 90, 0),
            #							 startHpr=Point3(-10, 90, 0))
            #posInterval2 = rat.hprInterval(0.1,
            #							 Point3(-10, 90, 0),
            #							 startHpr=Point3(10,90,0))
            #pandaPace = Sequence(posInterval1, posInterval2,
            #						  name="pandaPace" + str(i))
            #pandaPace.loop()
            self.ratto = np
        self.deer = loader.loadModel("rat.obj")
        self.deer.setScale((0.15, 0.15, 0.15))
        self.deer.setHpr((0, 90, 0))
        self.deer.setPos((0, 0, -2))
        self.deerShape = BulletBoxShape((3, 1, 3))
        self.deerNode = BulletRigidBodyNode('deerBox')
        self.deerNode.setAngularFactor((0, 0, 1))
        self.deerNode.setMass(10.0)
        self.deerNode.setFriction(1)
        self.deerNode.addShape(self.deerShape)
        self.deerNodePath = render.attachNewNode(self.deerNode)
        self.deerNodePath.setPos((30, 30, 130))
        self.world.attachRigidBody(self.deerNode)
        self.deer.reparentTo(self.deerNodePath)

        self.keyMap = {
            "w": False,
            "s": False,
            "a": False,
            "d": False,
            "space": False,
            "lshift": False,
            "p": False,
            "o": False
        }
        self.accept("w", self.setKey, ["w", True])
        self.accept("s", self.setKey, ["s", True])
        self.accept("a", self.setKey, ["a", True])
        self.accept("d", self.setKey, ["d", True])
        self.accept("space", self.setKey, ["space", True])
        self.accept("lshift", self.setKey, ["lshift", True])
        self.accept("e", self.lockMouse)
        self.accept("p", self.setKey, ["p", True])
        self.accept("o", self.setKey, ["o", True])

        self.accept("w-up", self.setKey, ["w", False])
        self.accept("s-up", self.setKey, ["s", False])
        self.accept("a-up", self.setKey, ["a", False])
        self.accept("d-up", self.setKey, ["d", False])
        self.accept("space-up", self.setKey, ["space", False])
        self.accept("lshift-up", self.setKey, ["lshift", False])
        self.accept("e-up", self.setKey, ["e", False])
        self.accept('escape', sys.exit)
        self.accept("p-up", self.setKey, ["p", False])
        self.accept("o-up", self.setKey, ["o", False])

        # Add the spinCameraTask procedure to the task manager.
        self.taskMgr.add(self.cameraControl, "CameraControl")

        self.camera.setPos(tuple(self.position))
Example #14
0
 def load_font(font_path):
     font_folder_path = Path(
         path.realpath(__file__)).parent.parent.parent.parent / "res/fonts"
     font_loader = Loader(GUIFontLoader.base)
     return font_loader.loadFont(
         Filename(font_folder_path / font_path).cStr())
Example #15
0
    29.0 / 30.0
)  #The test distance. If asteroid greater than asteroid_test_distancem then it will be moved closer
score = 0  # Initialize score
fullscreen = False
Frames = False
test_max_min = [0, 0, 0, 0]
max_player_speed = 300000
pointball_value = 0
title_screen = None
is_living = True
resolution = (800, 600)
fog_quality = 0.000002
cursor_hidden = False
# Windows settings
loadPrcFileData('', 'window-title Space Rocks!')
thunderstrike = Loader.loadFont(0, "./Fonts/thunderstrike.ttf")
thunderstrike3d = Loader.loadFont(0, "./Fonts/thunderstrike3d.ttf")


class Begin(ShowBase):
    def __init__(self):
        global pointball_value
        global title_screen
        global loading_screen
        # Basics
        ShowBase.__init__(self)
        #Setup the window
        base.disableMouse()
        render.setAntialias(AntialiasAttrib.MAuto)
        self.set_windowsettings()
        base.camLens.setFar(asteroid_spawn_distance * 100)
Example #16
0
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

# Panda3D modules.
from direct.showbase.Loader import Loader
from panda3d.core import SamplerState, Texture, TextureStage

# Global rendering options.
ANISOTROPIC_FILTERING = 4
MIPMAP = True
MIRROR = True

# Instanciate a Panda3D loader.
loader = Loader(None)


def load(path, anisotropic=None, mipmap=None, mirror=None):
    """Load a texture and apply some rendering properties.
    """
    if anisotropic is None: anisotropic = ANISOTROPIC_FILTERING
    if mipmap is None: mipmap = MIPMAP
    if mirror is None: mirror = MIRROR

    texture = loader.loadTexture(path)
    texture.setAnisotropicDegree(anisotropic)
    if mipmap:
        texture.setMagfilter(SamplerState.FT_linear_mipmap_linear)
        texture.setMinfilter(SamplerState.FT_linear_mipmap_linear)
    if mirror:
Example #17
0
    def _get_node_plate(cls,
                        loader: Loader,
                        build_plate_size: LVector2d,
                        name: str = "") -> NodePath:
        """Generate the textured build plate NodePath.

        This NodePath's only purpose is to display the app's logo.

        Parameters
        ----------
        loader : Loader
            Panda3D asset loader.
        build_plate_size : LVector2d
            Builder plate size.
        name : str
            Name for the generated NodePath.
        """
        # Geom data
        geom_data = cls._get_geom_data_plate(build_plate_size)

        # Primitive
        primitive = GeomTristrips(Geom.UHStatic)
        primitive.addVertices(0, 1, 3, 2)
        primitive.closePrimitive()

        # Geom, GeomNode
        geom = Geom(geom_data)
        geom.addPrimitive(primitive)
        geom_node = GeomNode("")
        geom_node.addGeom(geom)

        # NodePath
        node_path = NodePath(top_node_name=name)
        node_path.attachNewNode(geom_node)

        # Texture
        tex = loader.loadTexture(cls._PATH_TEXTURE)
        ts = TextureStage("ts")
        node_path.setTexture(ts, tex)
        tex.setBorderColor((0, 0, 0, 0))
        tex.setWrapU(Texture.WMBorderColor)
        tex.setWrapV(Texture.WMBorderColor)

        node_path.setTransparency(TransparencyAttrib.MAlpha)
        node_path.setAlphaScale(cls._TEXTURE_OPACITY)

        texture_scale = cls._TEXTURE_SCALE

        width, height = build_plate_size
        ratio = width / height
        if ratio >= 1:  # Landscape or square
            scale_v = 1 / texture_scale
            scale_u = scale_v * ratio
        else:  # Portrait
            scale_u = 1 / texture_scale
            scale_v = scale_u / ratio

        node_path.setTexScale(ts, scale_u, scale_v)
        node_path.setTexOffset(ts, -0.5 * (scale_u - 1), -0.5 * (scale_v - 1))

        return node_path