Ejemplo n.º 1
0
    def __enter__(self):
        self._settings = self.world.get_settings()
        self.frame = self.world.apply_settings(
            carla.WorldSettings(no_rendering_mode=False,
                                synchronous_mode=True,
                                fixed_delta_seconds=self.delta_seconds))

        def make_queue(register_event):
            """
            This queuing has nothing to do with (sequential) programming, it only stores the data in queues.
            Different types of data are stored in different queues.
            Each register event(in this case, world.on_tick and sensor.Listen) takes a Queue.put() method as callback,
            which then also takes data (Worldsnapshot or SensorData in this case) as argument
            so that each time these events are called the correspondent data would be save to queues.
            :param register_event: a function that takes a callback as argument
            :return:
            """
            q = queue.Queue()
            register_event(q.put)
            self._queues.append(q)

        make_queue(self.world.on_tick)
        for sensor in self.sensors:
            make_queue(sensor.listen)
        return self
Ejemplo n.º 2
0
 def setUp(self):
     super(TestSynchronousMode, self).setUp()
     self.world = self.client.get_world()
     self.settings = self.world.get_settings()
     settings = carla.WorldSettings(no_rendering_mode=False,
                                    synchronous_mode=True)
     self.world.apply_settings(settings)
Ejemplo n.º 3
0
 def test_reloading_map(self):
     settings = carla.WorldSettings(
         no_rendering_mode=False,
         synchronous_mode=True,
         fixed_delta_seconds=0.05)
     for _ in range(0, 4):
         self.world = self.client.reload_world()
         self.world.apply_settings(settings)
Ejemplo n.º 4
0
 def setUp(self):
     super(SyncSmokeTest, self).setUp()
     self.world = self.client.get_world()
     self.settings = self.world.get_settings()
     settings = carla.WorldSettings(no_rendering_mode=False,
                                    synchronous_mode=True,
                                    fixed_delta_seconds=0.05)
     self.world.apply_settings(settings)
Ejemplo n.º 5
0
    def apply_settings(self, fps=10.0, no_rendering=False):

        self.delta_seconds = 1.0 / fps
        self._settings = self.world.get_settings()
        self.frame = self.world.apply_settings(
            carla.WorldSettings(no_rendering_mode=no_rendering,
                                synchronous_mode=True,
                                fixed_delta_seconds=self.delta_seconds))
 def set_synchronous_mode(self, synchronous_mode):
     """
     Sets synchronous mode.
     """
     
     self.world.apply_settings(carla.WorldSettings(
         no_rendering_mode=False,
         synchronous_mode=True,
         fixed_delta_seconds=self.delta_seconds))
Ejemplo n.º 7
0
 def setUp(self):
     super(TestCollisionDeterminism, self).setUp()
     self.world = self.client.get_world()
     self.settings = self.world.get_settings()
     settings = carla.WorldSettings(no_rendering_mode=False,
                                    synchronous_mode=True,
                                    fixed_delta_seconds=0.05)
     self.world.apply_settings(settings)
     self.world.tick()
Ejemplo n.º 8
0
    def __enter__(self):
        self._settings = self.world.get_settings()
        self.frame = self.world.apply_settings(
            carla.WorldSettings(no_rendering_mode=False,
                                fixed_delta_seconds=self.delta_seconds,
                                synchronous_mode=True))

        for sensor in self.sensors.values():
            sensor.start()

        return self
Ejemplo n.º 9
0
    def test_spawn_points(self):
        
        self.world = self.client.get_world()
        blueprints = self.world.get_blueprint_library().filter("vehicle.*")
        
        # get all available maps
        maps = self.client.get_available_maps()
        for m in maps:
            
            # load the map
            self.client.load_world(m)
            self.world = self.client.get_world()
            
            # get all spawn points
            spawn_points = self.world.get_map().get_spawn_points()

            # Check why the world settings aren't applied after a reload
            self.settings = self.world.get_settings()
            settings = carla.WorldSettings(
                no_rendering_mode=False,
                synchronous_mode=True,
                fixed_delta_seconds=0.05)
            self.world.apply_settings(settings)

            # spawn all kind of vehicle
            for vehicle in blueprints:
                batch = [(vehicle, t) for t in spawn_points]
                batch = [carla.command.SpawnActor(*args) for args in batch]
                response = self.client.apply_batch_sync(batch, True)

                self.assertFalse(any(x.error for x in response))
                ids = [x.actor_id for x in response]
                self.assertEqual(len(ids), len(spawn_points))

                frame = self.world.tick()
                snapshot = self.world.get_snapshot()
                self.assertEqual(frame, snapshot.timestamp.frame)

                actors = self.world.get_actors()
                self.assertTrue(all(snapshot.has_actor(x.id) for x in actors))

                for actor_id, t0 in zip(ids, spawn_points):
                    actor_snapshot = snapshot.find(actor_id)
                    self.assertIsNotNone(actor_snapshot)
                    t1 = actor_snapshot.get_transform()
                    # Ignore Z cause vehicle is falling.
                    self.assertAlmostEqual(t0.location.x, t1.location.x, places=2)
                    self.assertAlmostEqual(t0.location.y, t1.location.y, places=2)
                    self.assertAlmostEqual(t0.rotation.pitch, t1.rotation.pitch, places=2)
                    self.assertAlmostEqual(t0.rotation.yaw, t1.rotation.yaw, places=2)
                    self.assertAlmostEqual(t0.rotation.roll, t1.rotation.roll, places=2)
                
                self.client.apply_batch_sync([carla.command.DestroyActor(x) for x in ids], True)
                frame = self.world.tick()
Ejemplo n.º 10
0
 def test_reloading_map(self):
     print("TestSynchronousMode.test_reloading_map")
     settings = carla.WorldSettings(
         no_rendering_mode=False,
         synchronous_mode=True,
         fixed_delta_seconds=0.05)
     for _ in range(0, 4):
         self.world = self.client.reload_world()
         self.world.apply_settings(settings)
         # workaround: give time to UE4 to clean memory after loading (old assets)
         time.sleep(5)
Ejemplo n.º 11
0
    def __enter__(self):
        self._settings = self.world.get_settings()
        self.frame = self.world.apply_settings(
            carla.WorldSettings(no_rendering_mode=True, synchronous_mode=True))

        def make_queue(register_event):
            q = queue.Queue()
            register_event(q.put)
            self._queues.append(q)

        make_queue(self.world.on_tick)
        for sensor in self.sensors:
            make_queue(sensor.listen)
        return self
Ejemplo n.º 12
0
    def start(self):
        self._settings = self.world.get_settings()
        self.frame = self.world.apply_settings(
            carla.WorldSettings(no_rendering_mode=False,
                                synchronous_mode=True,
                                fixed_delta_seconds=self.delta_seconds))

        def make_queue(register_event):
            q = queue.Queue()
            register_event(q.put)
            self._queues.append(q)

        make_queue(self.world.on_tick)
        for sensor in self.sensors:
            make_queue(sensor.listen)
Ejemplo n.º 13
0
    def _initialize_world_settings(self):
        """Applies the simulator settings"""
        self.settings = self.world.get_settings()
        _ = self.world.apply_settings(
            carla.WorldSettings(no_rendering_mode=self.no_rendering_mode,
                                synchronous_mode=self.sync_mode,
                                fixed_delta_seconds=self.delta_sec))
        if self.sync_mode:
            print("Synchronous Mode enabled")
        else:
            print("Synchronous Mode disabled")

        if self.no_rendering_mode:
            print("No Rendering Mode enabled (==camera sensors are disabled)")
        else:
            print("No Rendering Mode disabled")
Ejemplo n.º 14
0
    def reloadWorld(self, envParams: EnvSetupParams):
        self.world = self.client.get_world()
        if self.world is None or self.world.get_map(
        ) is None or self.world.get_map().name != envParams.mapToUse:
            self.client.load_world(envParams.mapToUse)
        else:
            self.client.reload_world()

        self.envParams = envParams
        # Set settings for this episode and reload the world
        settings = carla.WorldSettings(
            no_rendering_mode=self.args.no_rendering,
            synchronous_mode=envParams.synchronousComm,
            fixed_delta_seconds=1.0 / envParams.fixedFPS)
        # settings.randomize_seeds()
        self.world.apply_settings(settings)
        self.map = self.world.get_map()
Ejemplo n.º 15
0
    def __enter__(self):
        self._settings = self.world.get_settings()
        self.frame = self.world.apply_settings(carla.WorldSettings(
            no_rendering_mode=False,
            synchronous_mode=True,
            fixed_delta_seconds=self.delta_seconds))

        def make_queue(register_event):
            q = queue.Queue()
            register_event(q.put)
            self._queues.append(q)

        make_queue(self.world.on_tick)
        for sensor in self.sensors:
            actor = self.world.get_actor(sensor) if type(sensor) is int else sensor
            make_queue(actor.listen)
        return self
    def __init__(self):
        try:
            carla_base.__init__(self)
            self.world = self.client.load_world('Town04')
            self.world.apply_settings(
                carla.WorldSettings(
                    no_rendering_mode=base_config.no_render_mode))
        except:
            raise RuntimeError('carla_base init fails...')
        else:
            if env_v1_config.fix_vehicle_pos:
                ## using predefine vehicles position
                self.vehicles_pos = np.load(
                    env_v1_config.vehicles_pos_file)['pos']
            else:
                ## random generate vehicles position
                self.vehicles_pos = generate_vehicles_pos(
                    n_vehicles=random.randint(27, 27))

            if env_v1_config.synchronous_mode:
                self.start_synchronous_mode()

            # ------ 设置动作空间大小 ----------- #
            self.action_space = spaces.Discrete(
                len(list(env_v1_config.actions.keys())))

            # ----
            self.max_step = 2000
            self.step_counter = 0

            # end_point
            self.end_point_x = 50.

            # max velocity
            self.longitude_velocity_norm = 6.  ## m/s, 归一化尺度
            self.lateral_velocity_norm = 1.5  ## m/s, 归一化尺度

            self.__longitude_norm = env_v1_config.farest_vehicle_consider  ## 纵向方向上的归一化尺度

            ##
            self.n_been_catched_record = 0

            self.test_mode = False

            self.left_obstacle = None
            self.right_obstacle = None
Ejemplo n.º 17
0
    def __enter__(self):
        # some data about the simulation such as synchrony between client and server or rendering mode
        self._settings = self.world.get_settings()
        # ---- This is important carla.WorldSettings
        self.frame = self.world.apply_settings(
            carla.WorldSettings(no_rendering_mode=False,
                                synchronous_mode=True,
                                fixed_delta_seconds=self.delta_seconds))

        def make_queue(register_event):
            q = queue.Queue()
            register_event(q.put)
            self._queues.append(q)

        make_queue(self.world.on_tick)
        for sensor in self.sensors:
            make_queue(sensor.listen)
        return self
Ejemplo n.º 18
0
    def __enter__(self):
        self._settings = self.world.get_settings()
        self.frame = self.world.apply_settings(
            carla.WorldSettings(no_rendering_mode=False,
                                synchronous_mode=True,
                                fixed_delta_seconds=self.delta_seconds))

        def make_queue(register_event):
            q = queue.Queue()
            register_event(q.put)
            self._queues.append(q)

        make_queue(self.world.on_tick)
        make_queue(self.camera_rgb.listen)
        make_queue(self.camera_lidar.listen)
        # make_queue(self.sensor_collision.listen)

        return self
Ejemplo n.º 19
0
    def test_spawn_points(self):
        print("TestSnapshot.test_spawn_points")
        self.world = self.client.reload_world()
        # workaround: give time to UE4 to clean memory after loading (old assets)
        time.sleep(5)

        # Check why the world settings aren't applied after a reload
        self.settings = self.world.get_settings()
        settings = carla.WorldSettings(no_rendering_mode=False,
                                       synchronous_mode=True,
                                       fixed_delta_seconds=0.05)
        self.world.apply_settings(settings)

        spawn_points = self.world.get_map().get_spawn_points()[:20]
        vehicles = self.world.get_blueprint_library().filter('vehicle.*')
        batch = [(random.choice(vehicles), t) for t in spawn_points]
        batch = [carla.command.SpawnActor(*args) for args in batch]
        response = self.client.apply_batch_sync(batch, False)

        self.assertFalse(any(x.error for x in response))
        ids = [x.actor_id for x in response]
        self.assertEqual(len(ids), len(spawn_points))

        frame = self.world.tick()
        snapshot = self.world.get_snapshot()
        self.assertEqual(frame, snapshot.timestamp.frame)

        actors = self.world.get_actors()
        self.assertTrue(all(snapshot.has_actor(x.id) for x in actors))

        for actor_id, t0 in zip(ids, spawn_points):
            actor_snapshot = snapshot.find(actor_id)
            self.assertIsNotNone(actor_snapshot)
            t1 = actor_snapshot.get_transform()
            # Ignore Z cause vehicle is falling.
            self.assertAlmostEqual(t0.location.x, t1.location.x, places=2)
            self.assertAlmostEqual(t0.location.y, t1.location.y, places=2)
            self.assertAlmostEqual(t0.rotation.pitch,
                                   t1.rotation.pitch,
                                   places=2)
            self.assertAlmostEqual(t0.rotation.yaw, t1.rotation.yaw, places=2)
            self.assertAlmostEqual(t0.rotation.roll,
                                   t1.rotation.roll,
                                   places=2)
Ejemplo n.º 20
0
    def __init__(self):
        self.client = carla.Client("localhost", 2000)
        self.client.set_timeout(2.0)
        self.world = self.client.get_world()
        self.world = self.client.reload_world()
        self.map = self.world.get_map()
        self.blueprint_library = self.world.get_blueprint_library()
        self.model_3 = self.blueprint_library.filter("model3")[0]
        self.vehicle = None

        # world in sync mode
        self.world.apply_settings(
            carla.WorldSettings(
                no_rendering_mode=NO_RENDERING,  # False for debug
                synchronous_mode=True,
                fixed_delta_seconds=DT_))

        pygame.init()
        self.display = pygame.display.set_mode(
            (800, 600), pygame.HWSURFACE | pygame.DOUBLEBUF)
        self.font = get_font()
        self.clock = pygame.time.Clock()
    def __enter__(self):
        self._settings = self.world.get_settings()
        self.frame = self.world.apply_settings(
            carla.WorldSettings(no_rendering_mode=False,
                                synchronous_mode=True,
                                fixed_delta_seconds=self.delta_seconds))

        def make_queue_snapshot(register_event):
            q = queue.Queue()
            register_event(q.put)
            self._queues.append((q, 'carla.WorldSnapshot'))

        def make_queue_sensor(sensor, register_event):
            q = queue.Queue()
            register_event(q.put)
            # self._queues.append((q, sensor.type_id))
            self._queues.append((q, sensor[1]))

        make_queue_snapshot(self.world.on_tick)
        for sensor in self.sensors:
            # make_queue_sensor(sensor, sensor.listen)
            make_queue_sensor(sensor, sensor[0].listen)
        return self
Ejemplo n.º 22
0
def main():
    try:
        client = carla.Client('localhost', 2000)
        client.set_timeout(2.0)

        load_world_if_needed(client, "/Game/Carla/Maps/Town01")

        world = client.get_world()
        world.apply_settings(carla.WorldSettings(True, False, 1.0 / 30))
        map = world.get_map()

        start_tf = carla.Transform(carla.Location(x=230, y=55, z=0.1),
                                   carla.Rotation(0, 180, 0))
        start_wp = map.get_waypoint(start_tf.location)
        end_loc = carla.Location(x=240, y=55, z=0)

        waypoints = find_waypoins(
            start_wp,
            [10, 172, 25, 32, 2, 88, 21, 188, 22, 158, 4, 141, 17, 114, 10], 1,
            end_loc)
        print('waypoint count ', len(waypoints))
        route_line = LineString([(wp.transform.location.x,
                                  wp.transform.location.y)
                                 for wp in waypoints])

        blueprint_library = world.get_blueprint_library()
        bp = blueprint_library.find('vehicle.jeep.wrangler_rubicon')

        vehicle = world.spawn_actor(bp, start_tf)
        print('created %s' % vehicle.type_id)

        print('===============')
        print('physics_control')
        print(vehicle.get_physics_control())

        #vehicle.set_velocity(carla.Vector3D(-10, 0, 0)) # 초기 속도를 지정할 수 있다.
        while True:
            curr_tf = vehicle.get_transform()
            curr_location = vehicle.get_location()
            curr_velocity = vehicle.get_velocity()
            waypoint = map.get_waypoint(curr_location)
            vehicle.apply_control(
                my_control(curr_tf, curr_velocity, route_line))
            frame = world.tick()
            print(f"frame={frame}, road_id={waypoint.road_id}")

            spectator_tf = carla.Transform(
                carla.Location(curr_location.x, curr_location.y,
                               curr_location.z + 2.5), curr_tf.rotation)
            world.get_spectator().set_transform(spectator_tf)

            if curr_location.distance(end_loc) < 3: break

        print("success")

    finally:
        print('destroying vehicle')
        vehicle.destroy()

        # synchronous_mode를 해제한다.
        world.apply_settings(carla.WorldSettings(False))
        print('done.')
Ejemplo n.º 23
0
        'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
    pass

import carla
import random
import time

if __name__=='__main__':
    try:
        client = carla.Client('localhost', 2000)
        client.set_timeout(3.0)
        world = client.get_world()
        previous_settings = world.get_settings()
        world.apply_settings(carla.WorldSettings(
            synchronous_mode=True,
            fixed_delta_seconds=1.0 / 10.0))
        spawn_points = world.get_map().get_spawn_points()
     
        blueprint_library = world.get_blueprint_library()
        vehicle_bp = random.choice(blueprint_library.filter('vehicle.toyota.*'))
        actors = []
        print("number of spawn points: {}".format(len(spawn_points)))
        for i in range(len(spawn_points)): 
            actor = world.try_spawn_actor(vehicle_bp, spawn_points[i % len(spawn_points)])
            if actor==None:
                continue
            actor.set_autopilot()
            actors.append(actor)
        last_number = 0
        while True:
Ejemplo n.º 24
0
    def main(self):
        try:
            # initialize one painter
            try:
                self.painter = CarlaPainter('localhost', 8089)
            except Exception as e:
                print("NO PAINTER")
                print(e)
                self.painter = None

            self.client = carla.Client('localhost', 2000)
            self.client.set_timeout(10.0)
            self.world = self.client.get_world()

            # set synchronous mode
            previous_settings = self.world.get_settings()
            self.world.apply_settings(
                carla.WorldSettings(synchronous_mode=True,
                                    fixed_delta_seconds=1.0 / 30.0))

            # spawn an ego vehicle
            spawn_points = self.world.get_map().get_spawn_points()
            blueprints_vehicles = self.world.get_blueprint_library().filter(
                "vehicle.*")

            ego_transform = spawn_points[0]

            blueprints_vehicles = [
                x for x in blueprints_vehicles
                if int(x.get_attribute('number_of_wheels')) == 4
            ]

            # set ego vehicle's role name to let CarlaViz know this vehicle is the ego vehicle
            blueprints_vehicles[0].set_attribute('role_name',
                                                 'ego')  # or set to 'hero'
            batch = [
                carla.command.SpawnActor(blueprints_vehicles[0],
                                         ego_transform).then(
                                             carla.command.SetAutopilot(
                                                 carla.command.FutureActor,
                                                 False))
            ]
            results = self.client.apply_batch_sync(batch, False)
            if not results[0].error:
                self.ego_vehicle = self.world.get_actor(results[0].actor_id)
            else:
                print('spawn ego error, exit')
                self.ego_vehicle = None
                return

            # attach a camera and a lidar to the ego vehicle
            #blueprint_camera = self.world.get_blueprint_library().find('sensor.camera.rgb')
            #blueprint_camera.set_attribute('image_size_x', '640')
            #blueprint_camera.set_attribute('image_size_y', '480')
            #blueprint_camera.set_attribute('fov', '110')
            #blueprint_camera.set_attribute('sensor_tick', '0.1')
            #transform_camera = carla.Transform(carla.Location(x=.3, z=1.8))
            #self.camera = self.world.spawn_actor(blueprint_camera, transform_camera, attach_to=self.ego_vehicle)
            #self.camera.listen(lambda data: self.camera_listener(data))

            blueprint_lidar = self.world.get_blueprint_library().find(
                'sensor.lidar.ray_cast')
            # these specs follow the velodyne vlp32 spec
            blueprint_lidar.set_attribute('range', '200')
            #blueprint_lidar.set_attribute('range', '30')
            blueprint_lidar.set_attribute('rotation_frequency', '10')
            blueprint_lidar.set_attribute('channels', '32')
            blueprint_lidar.set_attribute('lower_fov', '-25')
            blueprint_lidar.set_attribute('upper_fov', '15')
            blueprint_lidar.set_attribute('points_per_second', '578560')
            self.blueprint_lidar = blueprint_lidar
            transform_lidar = carla.Transform(carla.Location(x=0.0, z=1.8))
            self.lidar = self.world.spawn_actor(blueprint_lidar,
                                                transform_lidar,
                                                attach_to=self.ego_vehicle)
            self.lidar.listen(lambda data: self.lidar_listener(data))

            # tick to generate these actors in the game world
            self.world.tick()

            # save vehicles' trajectories to draw in the frontend
            trajectories = [[]]
            self.obstacle = None

            #self.obstacle = self.spawn_obstacle()

            while (True):
                self.world.tick()
                strs = []
                locs = []

                loc = self.ego_vehicle.get_location()
                strs.append("{:.2f}, ".format(loc.x) + "{:.2f}".format(loc.y) \
                        + ", {:.2f}".format(loc.z))
                locs.append([loc.x, loc.y, loc.z + 10.0])

                strs.append( "{:.2f}, ".format(loc.x-self.certificate_distance) + "{:.2f}".format(loc.y) \
                        + ", {:.2f}".format(loc.z))

                locs.append(
                    [loc.x - self.certificate_distance, loc.y, loc.z + 10.0])

                strs.append("Certificate GOOD" if self.
                            certificate_result else "Certificate BAD")
                locs.append([loc.x - 5, loc.y - 5, loc.z + 20.0])
                self.painter.draw_texts(strs, locs, size=20)
                ##@trajectories[0].append([ego_location.x, ego_location.y, ego_location.z])

                ## draw trajectories
                #painter.draw_polylines(trajectories)

                ## draw ego vehicle's velocity just above the ego vehicle
                #ego_velocity = ego_vehicle.get_velocity()
                #velocity_str = "{:.2f}, ".format(ego_velocity.x) + "{:.2f}".format(ego_velocity.y) \
                #        + ", {:.2f}".format(ego_velocity.z)

        finally:
            if previous_settings is not None:
                self.world.apply_settings(previous_settings)
            if self.lidar is not None:
                self.lidar.stop()
                self.lidar.destroy()
            if self.camera is not None:
                self.camera.stop()
                self.camera.destroy()
            if self.ego_vehicle is not None:
                self.ego_vehicle.destroy()
            if self.obstacle is not None:
                self.obstacle.destroy()
Ejemplo n.º 25
0
def setup(
    town: str,
    weather: str,
    fps: int = 20,
    server_timestop: float = 20.0,
    client_timeout: float = 20.0,
    num_max_restarts: int = 5,
) -> Tuple[carla.Client, carla.World, int, subprocess.Popen]:  # pylint: disable=no-member
    """Returns the `CARLA` `server`, `client` and `world`.

  Args:
    town: The `CARLA` town identifier.
    fps: The frequency (in Hz) of the simulation.
    server_timestop: The time interval between spawing the server
      and resuming program.
    client_timeout: The time interval before stopping
      the search for the carla server.
    num_max_restarts: Number of attempts to connect to the server.

  Returns:
    client: The `CARLA` client.
    world: The `CARLA` world.
    frame: The synchronous simulation time step ID.
    server: The `CARLA` server.
  """
    assert town in ("Town01", "Town02", "Town03", "Town04", "Town05")
    # All preset weather parameters in carla.WeatherParameters
    assert weather in ("ClearNoon", "CloudyNoon", "WetNoon", "WetCloudyNoon",
                       "SoftRainNoon", "MidRainyNoon", "HardRainNoon",
                       "ClearSunset", "CloudySunset", "WetSunset",
                       "WetCloudySunset", "SoftRainSunset", "MidRainSunset",
                       "HardRainSunset")
    weather_params = getattr(carla.WeatherParameters, weather)
    # The attempts counter.
    attempts = 0

    while attempts < num_max_restarts:
        logging.debug(
            "{} out of {} attempts to setup the CARLA simulator".format(
                attempts + 1, num_max_restarts))

        # Random assignment of port.
        port = np.random.randint(2000, 3000)

        # Start CARLA server.
        env = os.environ.copy()
        env["SDL_VIDEODRIVER"] = "offscreen"
        env["SDL_HINT_CUDA_DEVICE"] = "1"
        logging.debug("Inits a CARLA server at port={}".format(port))
        server = subprocess.Popen(
            [
                os.path.join(os.environ.get("CARLA_ROOT"), "CarlaUE4.sh"),
                "-carla-rpc-port={}".format(port),
                "-quality-level=Epic",
            ],
            stdout=None,
            stderr=subprocess.STDOUT,
            preexec_fn=os.setsid,
            env=env,
        )
        atexit.register(os.killpg, server.pid, signal.SIGKILL)
        time.sleep(server_timestop)

        # Connect client.
        logging.debug("Connects a CARLA client at port={}".format(port))
        try:
            client = carla.Client("localhost", port)  # pylint: disable=no-member
            client.set_timeout(client_timeout)
            client.load_world(map_name=town)
            world = client.get_world()
            world.set_weather(weather_params)  # pylint: disable=no-member
            frame = world.apply_settings(
                carla.WorldSettings(  # pylint: disable=no-member
                    no_rendering_mode=False,
                    synchronous_mode=True,
                    fixed_delta_seconds=1.0 / fps,
                ))
            logging.debug("Server version: {}".format(
                client.get_server_version()))
            logging.debug("Client version: {}".format(
                client.get_client_version()))
            return client, world, frame, server
        except RuntimeError as msg:
            logging.debug(msg)
            attempts += 1
            logging.debug("Stopping CARLA server at port={}".format(port))
            os.killpg(server.pid, signal.SIGKILL)
            atexit.unregister(lambda: os.killpg(server.pid, signal.SIGKILL))

    logging.debug("Failed to connect to CARLA after {} attempts".format(
        num_max_restarts))
    sys.exit()
Ejemplo n.º 26
0
    def __init__(self, address='localhost', port=2000, timeout=2.0, image_shape=(150, 200, 3), window_size=(800, 600),
                 vehicle_filter='vehicle.*', sensors: dict = None, route_resolution=2.0, fps=30.0, render=True,
                 debug=False):
        """
        :param address: CARLA simulator's id address. Required only if the simulator runs on a different machine.
        :param port: CARLA simulator's port.
        :param timeout: connection timeout.
        :param image_shape: shape of the images observations.
        :param window_size: pygame's window size. Meaningful only if `visualize=True`.
        :param vehicle_filter: use to spawn a particular vehicle (e.g. 'vehicle.tesla.model3') or class of vehicles
            (e.g. 'vehicle.audi.*')
        :param sensors: specifies which sensors should be equipped to the vehicle, better specified by subclassing
            `default_sensors()`.
        :param route_resolution: route planner resolution grain.
        :param fps: maximum framerate, it depends on your compiting power.
        :param render: if True a pygame window is shown.
        :param debug: enable to display some useful information about the vehicle.
        """
        super().__init__()
        env_utils.init_pygame()

        self.timeout = timeout
        self.client = env_utils.get_client(address, port, self.timeout)
        self.world: carla.World = self.client.get_world()
        self.map: carla.Map = self.world.get_map()
        self.synchronous_context = None

        # set fix fps:
        self.world.apply_settings(carla.WorldSettings(
            no_rendering_mode=False,
            synchronous_mode=False,
            fixed_delta_seconds=1.0 / fps))

        # vehicle
        self.vehicle_filter = vehicle_filter
        self.vehicle: carla.Vehicle = None

        # actions
        self.control: carla.VehicleControl = None
        self.prev_actions = None

        # weather
        # TODO: add weather support

        # visualization and debugging stuff
        self.image_shape = image_shape
        self.image_size = (image_shape[1], image_shape[0])
        self.DEFAULT_IMAGE = np.zeros(shape=self.image_shape, dtype=np.float32)
        self.fps = fps
        self.tick_time = 1.0 / self.fps
        self.should_render = render
        self.should_debug = debug
        self.clock = pygame.time.Clock()

        if self.should_render:
            self.window_size = window_size
            self.font = env_utils.get_font(size=13)
            self.display = env_utils.get_display(window_size)

        # variables for reward computation
        self.collision_penalty = 0.0

        # vehicle sensors suite
        self.sensors_spec = sensors if isinstance(sensors, dict) else self.default_sensors()
        self.sensors = dict()
 def close_synchronous_mode(self):
     """close synchoronous mode"""
     self.world.apply_settings(
         carla.WorldSettings(no_rendering_mode=base_config.no_render_mode,
                             synchronous_mode=False))
 def start_synchronous_mode(self):
     """carla synchoronous mode"""
     self.world.apply_settings(
         carla.WorldSettings(no_rendering_mode=base_config.no_render_mode,
                             synchronous_mode=True))
    def main(self, case):
        try:
            # connect to Carla engine
            self.client = carla.Client('localhost', 2000)
            self.client.set_timeout(10.0)
            self.world = self.client.get_world()
            previous_settings = self.world.get_settings()
            self.world.apply_settings(carla.WorldSettings(
                synchronous_mode=True,
                fixed_delta_seconds=1.0 / 20.0))
            self.tm = self.client.get_trafficmanager()
            self.tm.set_synchronous_mode(True)
            self.tm_port = self.tm.get_port()
            
            # create interlock starting scenario
            results = case(self.tm_port, self.client.apply_batch_sync, self.world)
            self.vehicles.extend(results[1:])
            if not results[0].error:
                self.ego_vehicle = self.world.get_actor(results[0].actor_id)
                self.ego_id = results[0].actor_id
            else:
                print('spawn ego error, exit')
                self.ego_vehicle = None
                return

            # attach a camera and a lidar to the ego vehicle
            self.blueprint_camera = self.world.get_blueprint_library().find('sensor.camera.rgb')
            self.blueprint_camera.set_attribute('image_size_x', '1200')
            self.blueprint_camera.set_attribute('image_size_y', '400')
            self.blueprint_camera.set_attribute('fov', '120')
            #self.blueprint_camera.set_attribute('sensor_tick', '0.1')
            transform_camera = carla.Transform(carla.Location(x=.0, z=1.8))
            self.camera = self.world.spawn_actor(self.blueprint_camera, transform_camera, attach_to=self.ego_vehicle)
            self.camera.listen(lambda data: self.camera_listener(data))

            self.blueprint_lidar = self.world.get_blueprint_library().find('sensor.lidar.ray_cast_semantic')
            self.blueprint_lidar.set_attribute('range', '200000')
            self.blueprint_lidar.set_attribute('rotation_frequency', '20')
            #self.blueprint_lidar.set_attribute('channels', '64') # 0.6/0.4 resolution
            self.blueprint_lidar.set_attribute('channels', '192') # 0.2/0.2 resolution
            #self.blueprint_lidar.set_attribute('channels', '402')# 0.1/0.1 resolution
            self.blueprint_lidar.set_attribute('lower_fov', '-25')
            self.blueprint_lidar.set_attribute('upper_fov', '15')
            #self.blueprint_lidar.set_attribute('points_per_second', '1200000')# 0.6/0.4 resolution
            self.blueprint_lidar.set_attribute('points_per_second', '7200000')# 0.2/0.2 resolution
            #self.blueprint_lidar.set_attribute('points_per_second', '28860000')# 0.1/0.1 resolution
            transform_lidar = carla.Transform(carla.Location(x=0.0, z=1.8))
            self.lidar = self.world.spawn_actor(self.blueprint_lidar, transform_lidar, attach_to=self.ego_vehicle)
            self.lidar.listen(lambda data: self.lidar_listener(data))

            # attach semantic segmentation camera to ego
            blueprint_camera_segmentation = self.world.get_blueprint_library().find('sensor.camera.semantic_segmentation')
            blueprint_camera_segmentation.set_attribute('image_size_x', str(self.blueprint_camera.get_attribute("image_size_x").as_int()))
            blueprint_camera_segmentation.set_attribute('image_size_y', str(self.blueprint_camera.get_attribute("image_size_y").as_int()))
            blueprint_camera_segmentation.set_attribute('fov', str(self.blueprint_camera.get_attribute("fov").as_float()))
            self.camera_segmentation = self.world.spawn_actor(blueprint_camera_segmentation, transform_camera, attach_to=self.ego_vehicle)
            self.camera_segmentation.listen(lambda data: self.camera_segmentation_listener(data))

            # tick to generate these actors in the game world
            self.world.tick()

            self.certificate_result = True
            while (True):
                self.frame += 1
                self.world.tick()
                self.sensor_processor()
                if not self.certificate_result:
                    self.world.get_actor(self.ego_id).apply_control(carla.VehicleControl(brake=1.0))
        finally:
            if previous_settings is not None:
                self.world.apply_settings(previous_settings)
            if self.lidar is not None:
                self.lidar.stop()
                self.lidar.destroy()
            if self.camera is not None:
                self.camera.stop()
                self.camera.destroy()
            if self.camera_segmentation is not None:
                self.camera_segmentation.stop()
                self.camera_segmentation.destroy()
            if self.ego_vehicle is not None:
                self.ego_vehicle.destroy()
            self.client.apply_batch([carla.command.DestroyActor(x.actor_id) for x in self.vehicles])
def main():
    worlds = ["Town02"]
    # worlds = ["Town01", "Town02", "Town03", "Town04", "Town05"]
    client = carla.Client("127.0.0.1", 2000)
    client.set_timeout(10.0)
    traffic_manager: carla.TrafficManager = client.get_trafficmanager()
    traffic_manager.set_global_distance_to_leading_vehicle(2.0)
    traffic_manager.global_percentage_speed_difference(25.0)
    # traffic_manager.set_hybrid_physics_mode(True)
    # traffic_manager.set_synchronous_mode(True)

    for world_name in worlds:
        print(f"Loading {world_name}")
        client.load_world(world_name)
        world: carla.World = client.get_world()

        start_frame = world.apply_settings(
            carla.WorldSettings(no_rendering_mode=False,
                                synchronous_mode=True,
                                fixed_delta_seconds=1 / FPS))
        weather = Weather(carla.WeatherParameters.ClearNoon)
        world.set_weather(weather.weather)

        vehicle_spawner = VehicleSpawner(client, world, False)
        vehicle_spawner.spawn_nearby(0, 40, 40, 40, 80, 1000000)

        print("Running the world for 5 seconds before capturing...")
        frame = start_frame
        while frame < start_frame + FPS * 5:
            frame = world.tick()
        print("Starting capture!")

        all_sensors: List[carla.Sensor] = []
        vehicle_sensor_queues: Dict[int, Dict[str, Tuple[Queue,
                                                         carla.Sensor]]] = {}
        for vehicle_id in vehicle_spawner.vehicles_list:
            vehicle = world.get_actor(vehicle_id)
            sensors = spawn_sensors(world, vehicle)

            for sensor_name, sensor in sensors.items():
                all_sensors.append(sensor)
                queue = Queue()
                sensor.listen(queue.put)
                if vehicle_id not in vehicle_sensor_queues:
                    vehicle_sensor_queues[vehicle_id] = {}
                vehicle_sensor_queues[vehicle_id][sensor_name] = (queue,
                                                                  sensor)

        while frame < start_frame + FPS * 5:
            frame = world.tick()

        for i in range(0, NUMBER_OF_IMAGES_PER_VEHICLE_PER_WORLD):
            weather.tick(1)
            world.set_weather(weather.weather)
            frame = world.tick()
            print(f"Tick ({frame})")

            for vehicle_id, vehicle_sensors in vehicle_sensor_queues.items():
                new_yaw = random.gauss(0, 45)
                frame_nums = []
                for sensor_name, (queue, sensor) in vehicle_sensors.items():
                    try:
                        image = retrieve_data(frame, queue, TIMEOUT)
                        print(f"Got image from {sensor_name} {image.frame}")
                        frame_nums.append(image.frame)
                        image.save_to_disk(
                            f"output_perception/{world_name}/{sensor_name}/{vehicle_id}_{image.frame}.png",
                            get_color_converter(sensor_name))
                        sensor.set_transform(
                            carla.Transform(carla.Location(0, 0, 3),
                                            carla.Rotation(0, new_yaw, 0)))
                    except Empty:
                        print("Empty queue")
                assert all(frame == frame_nums[0] for frame in frame_nums)

            # Run amount of ticks equal to the sensors' sensor_tick value
            settings = world.get_settings()
            settings.no_rendering_mode = True
            world.apply_settings(settings)
            for t in range(0, int(SENSOR_TICK * FPS) - 8):
                weather.tick(1 / FPS * 5)
                world.set_weather(weather.weather)
                frame = world.tick()
                print(f"Tick ({frame})")
            settings.no_rendering_mode = False
            world.apply_settings(settings)

            # Do rest of ticks with rendering (to hopefully get rain effect)
            for i in range(0, 8):
                weather.tick(1 / FPS * 5)
                world.set_weather(weather.weather)
                frame = world.tick()
                print(f"Tick ({frame})")

        # Clean up
        # traffic_manager.set_synchronous_mode(False)
        for sensor in all_sensors:
            sensor.destroy()
        vehicle_spawner.destroy_vehicles()