def set_world_asynchronous(world: carla.World):
    if world is None:
        return
    settings = world.get_settings()
    if settings.synchronous_mode:
        settings.synchronous_mode = False
        world.apply_settings(settings)
Esempio n. 2
0
def spawn_vehicles(
    world: carla.World,  # pylint: disable=no-member
    num_vehicles: int,
) -> Sequence[carla.Vehicle]:  # pylint: disable=no-member
    """Spawns `vehicles` randomly in spawn points.

  Args:
    world: The world object associated with the simulation.
    num_vehicles: The number of vehicles to spawn.

  Returns:
    The list of vehicles actors.
  """
    # Blueprints library.
    bl = world.get_blueprint_library()
    # List of spawn points.
    spawn_points = world.get_map().get_spawn_points()
    # Output container
    actors = list()
    for _ in range(num_vehicles):
        # Fetch random blueprint.
        vehicle_bp = random.choice(bl.filter("vehicle.*"))
        # Attempt to spawn vehicle in random location.
        actor = world.try_spawn_actor(vehicle_bp, random.choice(spawn_points))
        if actor is not None:
            # Enable autopilot.
            actor.set_autopilot(True)
            # Append actor to the list.
            actors.append(actor)
    logging.debug("Spawned {} other vehicles".format(len(actors)))
    return actors
def spawn_sensors(world: carla.World,
                  actor: carla.Actor) -> Dict[str, carla.Sensor]:
    sensors = {}
    blueprints = {
        "rgb":
        world.get_blueprint_library().find('sensor.camera.rgb'),
        "segmentation":
        world.get_blueprint_library().find(
            'sensor.camera.semantic_segmentation'),
        "depth":
        world.get_blueprint_library().find('sensor.camera.depth')
    }

    fov = random.randint(60, 110)
    yaw = random.gauss(0, 45)
    sensor_transform = carla.Transform(carla.Location(0, 0, 3),
                                       carla.Rotation(0, yaw, 0))
    for sensor_name, blueprint in blueprints.items():
        blueprint.set_attribute("image_size_x", str(1920 / 2))
        blueprint.set_attribute("image_size_y", str(1080 / 2))
        blueprint.set_attribute("fov", str(fov))
        blueprint.set_attribute(
            "sensor_tick", str(SENSOR_TICK))  # Get new data every x second
        sensor: carla.Sensor = world.spawn_actor(blueprint,
                                                 sensor_transform,
                                                 attach_to=actor)
        sensors[sensor_name] = sensor
    return sensors
Esempio n. 4
0
def spawn_hero(
    world: carla.World,  # pylint: disable=no-member
    spawn_point: carla.Transform,  # pylint: disable=no-member
    vehicle_id: Optional[str] = None,
) -> carla.Vehicle:  # pylint: disable=no-member
    """Spawns `hero` in `spawn_point`.

  Args:
    world: The world object associated with the simulation.
    spawn_point: The point to spawn the hero actor.
    vehicle_id: An (optional) valid id for the vehicle object.

  Returns:
    The actor (vehicle) object.
  """
    # Blueprints library.
    bl = world.get_blueprint_library()
    if vehicle_id is not None:
        # Get the specific vehicle from the library.
        hero_bp = bl.find(vehicle_id)
    else:
        # Randomly choose a vehicle from the list.
        hero_bp = random.choice(bl.filter("vehicle.*"))
    # Rename the actor to `hero`.
    hero_bp.set_attribute("role_name", "hero")
    logging.debug("Spawns hero actor at {}".format(
        carla_xyz_to_ndarray(spawn_point.location)))
    hero = world.spawn_actor(hero_bp, spawn_point)
    return hero
Esempio n. 5
0
def query_all(world: carla.World) -> List[carla.Actor]:
    snapshot: carla.WorldSnapshot = world.get_snapshot()
    all_actors = []
    for actor_snapshot in snapshot:
        actor = world.get_actor(actor_snapshot.id)
        if actor is not None:
            all_actors.append(actor)
    return all_actors
Esempio n. 6
0
    def __init__(self, carla_world: carla.World, ego_vehicle: carla.Vehicle):
        # Params for images
        self.img_width = 1280 # in [px]
        self.img_height = 720 # in [px]
        self.fov_horizontal = 120 # in [deg]
        self.display_width = 640 # in [px]
        self.display_height = 360 # in [px]

        # Params for static camera calibration
        self.translation_x = 0.4 # in [m] from center of car
        self.translation_z = 1.5 # in [m] from bottom of car
        self.translation_y = 0.0 # in [m] from center of car
        self.pitch = 0.0 # in [deg]
        self.roll = 0.0 # in [deg]
        self.yaw = 0.0 # in [deg]

        # Images that are stored on disk per frame
        self.rgb_img: np.array = np.zeros((self.img_height, self.img_width, 3), dtype=np.uint8)
        self.depth_img: np.array = np.zeros((self.img_height, self.img_width, 3), dtype=np.uint8)
        self.semseg_img: np.array = np.zeros((self.img_height, self.img_width, 3), dtype=np.uint8)

        # Images that are displayed in pygame for visualization (note spectator img is just needed for visu)
        self.display_spectator_img: np.array = np.zeros((self.display_height, self.display_width, 3), dtype=np.uint8)
        self.display_rgb_img: np.array = np.zeros((self.display_height, self.display_width, 3), dtype=np.uint8)
        self.display_depth_img: np.array = np.zeros((self.display_height, self.display_width, 3), dtype=np.uint8)
        self.display_semseg_img: np.array = np.zeros((self.display_height, self.display_width, 3), dtype=np.uint8)

        # Create sensors
        blueprint_library: carla.BlueprintLibrary = carla_world.get_blueprint_library()
        cam_transform = carla.Transform(
            carla.Location(x=self.translation_x, z=self.translation_z, y=self.translation_y),
            carla.Rotation(pitch=self.pitch, yaw=self.yaw, roll=self.roll)
        )

        # Attach dummy rgb sensor to follow the ego vehicle (only for visulization)
        spectator_bp = blueprint_library.find('sensor.camera.rgb')
        self._add_attr_to_blueprint(spectator_bp)
        spectator_transform = carla.Transform(carla.Location(x=-6, z=3))
        self.spectator: carla.Actor = carla_world.spawn_actor(spectator_bp, spectator_transform, attach_to=ego_vehicle)
        self.spectator.listen(self._read_spectator_img)

        # Attach rgb cam sensors to ego vehicle
        cam_rgb_bp = blueprint_library.find('sensor.camera.rgb')
        self._add_attr_to_blueprint(cam_rgb_bp)
        self.cam_rgb: carla.Actor = carla_world.spawn_actor(cam_rgb_bp, cam_transform, attach_to=ego_vehicle)
        self.cam_rgb.listen(self._read_rgb_img)

        # Attach depth sensor to ego vehicle
        cam_depth_bp = blueprint_library.find("sensor.camera.depth")
        self._add_attr_to_blueprint(cam_depth_bp)
        self.cam_depth: carla.Actor = carla_world.spawn_actor(cam_depth_bp, cam_transform, attach_to=ego_vehicle)
        self.cam_depth.listen(self._read_depth_img)

        # Attach semseg sensor to ego vehicle
        cam_semseg_bp = blueprint_library.find("sensor.camera.semantic_segmentation")
        self._add_attr_to_blueprint(cam_semseg_bp)
        self.cam_semseg: carla.Actor = carla_world.spawn_actor(cam_semseg_bp, cam_transform, attach_to=ego_vehicle)
        self.cam_semseg.listen(self._read_semseg_img)
    def __init__(self, world: carla.World, carla_vehicle: carla.Vehicle):
        self.has_collided = False

        def on_collision(e):
            self.has_collided = True

        blueprint_library = world.get_blueprint_library()
        blueprint = blueprint_library.find('sensor.other.collision')
        self._collision_sensor = world.spawn_actor(
            blueprint, carla_vehicle.get_transform(), attach_to=carla_vehicle)
        self._collision_sensor.listen(on_collision)
Esempio n. 8
0
def get_spawn_point(
    world: carla.World,  # pylint: disable=no-member
    spawn_point: Optional[Union[int, carla.Transform]]  # pylint: disable=no-member
) -> carla.Location:  # pylint: disable=no-member
    """Parses and returns a CARLA spawn points."""
    if isinstance(spawn_point, carla.Transform):  # pylint: disable=no-member
        _spawn_point = spawn_point
    elif isinstance(spawn_point, int):
        _spawn_point = world.get_map().get_spawn_points()[spawn_point]
    else:
        _spawn_point = random.choice(world.get_map().get_spawn_points())
    return _spawn_point
Esempio n. 9
0
def get_pedestrians_surface(
    world: carla.World,  # pylint: disable=no-member
    pixels_per_meter: int = 5,
    scale: float = 1.0,
    margin: int = 150,
) -> pygame.Surface:
    """Generates a `PyGame` surface of pedestrians.

  Args:
    world: The `CARLA` world.
    pixels_per_meter: The number of pixels rendered per meter.
    scale: The scaling factor of the rendered map.
    margin: The number of pixels used for margin.

  Returns
    The pedestrians rendered as a `PyGame` surface.
  """
    # Fetch CARLA map.
    carla_map = world.get_map()

    # Fetch all the pedestrians.
    pedestrians = [
        actor for actor in world.get_actors()
        if "walker.pedestrian" in actor.type_id
    ]

    # Setups the `PyGame` surface and offsets.
    world_offset, surface = draw_settings(
        carla_map=carla_map,
        pixels_per_meter=pixels_per_meter,
        scale=scale,
        margin=margin,
    )

    # Set background black
    surface.fill(COLORS["BLACK"])

    # Iterate over pedestrians.
    for pedestrian in pedestrians:
        # Draw pedestrian as a rectangular.
        corners = actor_to_corners(pedestrian)
        # Convert to pixel coordinates.
        corners = [
            world_to_pixel(p, scale, world_offset, pixels_per_meter)
            for p in corners
        ]
        pygame.draw.polygon(surface, COLORS["WHITE"], corners)

    return surface
    def __init__(self, carla_world: carla.World, lane_gt_config, debug=False):
        self.carla_world = carla_world
        self.map = carla_world.get_map()

        # carla.Transform of current query point
        self._carla_tform = None

        # Search radius
        self._radius = lane_gt_config['radius']

        # bool: True to draw lane boundaries points during querying
        self.debug = debug

        self.gt = {}
        # Current waypoint
        self.waypoint = None
        # Flag indicating ego vehicle is in junction
        self.gt['in_junction'] = False
        # Current road id
        self.gt['road_id'] = None
        # Current lane id (to know the order of double marking types)
        self.gt['lane_id'] = None
        # Flag indicating ego vehicle is going into junction
        self.gt['into_junction'] = False
        # Carla.LaneMarking object of each marking
        self.gt['left_marking'] = None
        self.gt['next_left_marking'] = None
        self.gt['right_marking'] = None
        self.gt['next_right_marking'] = None
        # c0 and c1 of lane markings
        self.gt['left_marking_coeffs'] = [0, 0]
        self.gt['next_left_marking_coeffs'] = [0, 0]
        self.gt['right_marking_coeffs'] = [0, 0]
        self.gt['next_right_marking_coeffs'] = [0, 0]
Esempio n. 11
0
def get_present_vehicles(role_name_prefix: str,
                         world: carla.World) -> List[carla.Actor]:
    all_actors: carla.ActorList = world.get_actors().filter('vehicle.*')
    return [
        a for a in all_actors
        if has_prefixed_attribute(a, 'role_name', role_name_prefix)
    ]
Esempio n. 12
0
def get_blueprints(world: carla.World,
                   vehicles_filter: str = None,
                   pedestrians_filter: str = None,
                   safe=True):
    """Returns a list of blueprints for vehicles and pedestrians"""
    if vehicles_filter is None:
        vehicles_filter = 'vehicle.*'

    if pedestrians_filter is None:
        pedestrians_filter = 'walker.pedestrian.*'

    blueprint_lib = world.get_blueprint_library()

    vehicles_blueprints = blueprint_lib.filter(vehicles_filter)
    walkers_blueprints = blueprint_lib.filter(pedestrians_filter)

    if safe:
        vehicles_blueprints = filter(
            lambda b: (int(b.get_attribute('number_of_wheels')) == 4) and
            not (b.id.endswith('isetta') or b.id.endswith('carlacola') or b.id.
                 endswith('cybertruck') or b.id.endswith('t2')),
            vehicles_blueprints)
        vehicles_blueprints = list(vehicles_blueprints)

    return vehicles_blueprints, walkers_blueprints
Esempio n. 13
0
def random_blueprint(world: carla.World,
                     actor_filter='vehicle.*',
                     role_name='agent') -> carla.ActorBlueprint:
    """Retrieves a random blueprint.
        :param world: a carla.World instance.
        :param actor_filter: a string used to filter (select) blueprints. Default: 'vehicle.*'
        :param role_name: blueprint's role_name, Default: 'agent'.
        :return: a carla.ActorBlueprint instance.
    """
    blueprints = world.get_blueprint_library().filter(actor_filter)
    blueprint: carla.ActorBlueprint = random.choice(blueprints)
    blueprint.set_attribute('role_name', role_name)

    if blueprint.has_attribute('color'):
        color = random.choice(
            blueprint.get_attribute('color').recommended_values)
        blueprint.set_attribute('color', color)

    if blueprint.has_attribute('driver_id'):
        driver_id = random.choice(
            blueprint.get_attribute('driver_id').recommended_values)
        blueprint.set_attribute('driver_id', driver_id)

    if blueprint.has_attribute('is_invincible'):
        blueprint.set_attribute('is_invincible', 'true')

    # set the max speed
    if blueprint.has_attribute('speed'):
        float(blueprint.get_attribute('speed').recommended_values[1])
        float(blueprint.get_attribute('speed').recommended_values[2])
    else:
        print("No recommended values for 'speed' attribute")

    return blueprint
Esempio n. 14
0
def prepare_ego_vehicle(world: carla.World) -> carla.Actor:
    car_blueprint = world.get_blueprint_library().find("vehicle.audi.a2")

    # This will allow external scripts like manual_control.py or no_rendering_mode.py
    # from the official CARLA examples to take control over the ego agent
    car_blueprint.set_attribute("role_name", "hero")

    # spawn points doesnt matter - scenario sets up position in reset
    ego_vehicle = world.spawn_actor(
        car_blueprint,
        carla.Transform(carla.Location(0, 0, 500), carla.Rotation()))

    assert ego_vehicle is not None, "Ego vehicle could not be spawned"

    # Setup any car sensors you like, collect observations and then use them as input to your model
    return ego_vehicle
Esempio n. 15
0
    def __init__(self, world: carla.World, route_resolution=1.0):
        """
        Args:
            world (carla.World): the carla world instance
            route_resolution (float): the resolution in meters for planned route
        """
        self._world = world
        self._map = world.get_map()
        self._waypoints = self._map.generate_waypoints(2.0)
        self._actors = []  # including vehicles and walkers
        self._actor_dict = {}
        self._actor_locations = {}
        self._route_resolution = route_resolution

        dao = GlobalRoutePlannerDAO(world.get_map(),
                                    sampling_resolution=route_resolution)
        self._global_route_planner = GlobalRoutePlanner(dao)
        self._global_route_planner.setup()
Esempio n. 16
0
def spawn_pedestrians(
    world: carla.World,  # pylint: disable=no-member
    num_pedestrians: int,
    speeds: Sequence[float] = (1.0, 1.5, 2.0),
) -> Sequence[carla.Vehicle]:  # pylint: disable=no-member
    """Spawns `pedestrians` in random locations.

  Args:
    world: The world object associated with the simulation.
    num_pedestrians: The number of pedestrians to spawn.
    speeds: The valid set of speeds for the pedestrians.

  Returns:
    The list of pedestrians actors.
  """
    # Blueprints library.
    bl = world.get_blueprint_library()
    # Output container
    actors = list()
    for n in range(num_pedestrians):
        # Fetch random blueprint.
        pedestrian_bp = random.choice(bl.filter("walker.pedestrian.*"))
        # Make pedestrian invicible.
        pedestrian_bp.set_attribute("is_invincible", "true")
        while len(actors) != n:
            # Get random location.
            spawn_point = carla.Transform()  # pylint: disable=no-member
            spawn_point.location = world.get_random_location_from_navigation()
            if spawn_point.location is None:
                continue
            # Attempt to spawn vehicle in random location.
            actor = world.try_spawn_actor(pedestrian_bp, spawn_point)
            player_control = carla.WalkerControl()
            player_control.speed = 3
            pedestrian_heading = 90
            player_rotation = carla.Rotation(0, pedestrian_heading, 0)
            player_control.direction = player_rotation.get_forward_vector()
            if actor is not None:
                actor.apply_control(player_control)
                actors.append(actor)
    logging.debug("Spawned {} pedestrians".format(len(actors)))
    return actors
    def __init__(
            self,
            world: carla.World,
            args,
            transform: carla.Transform,
            agent_type: str,
            render_image: bool,
            evaluation: bool):
        self.world = world
        self.map = world.get_map()
        self.vehicle = None
        self.agent = None

        self.camera_sensor_dict = None
        self.segment_sensor_dict = None
        self.collision_sensor = None

        self.args = args
        self.agent_type = agent_type
        self.render_image = render_image
        self.evaluation = evaluation

        self.image_width = args.width
        self.image_height = args.height
        self.camera_keywords: List[str] = args.camera_keywords

        set_world_rendering_option(self.world, self.render_image)

        self.data_frame_dict = dict()
        self.data_frame_number_ = None
        self.progress_index = 0
        self.data_frame_buffer = set()
        self.stop_dict = dict()
        self.cmd_dict = dict()

        ExperimentDirectory.__init__(self, get_timestamp())
        self.target_waypoint_ = None
        self.waypoint_dict = dict()
        self.waypoint_buffer = set()

        set_world_asynchronous(self.world)

        self.set_vehicle(transform)
        if self.autopilot:
            self.set_agent()
        self.export_meta()

        set_world_synchronous(self.world)
        if self.render_image:
            self.set_camera_sensor()
            self.set_segment_sensor()
        self.set_collision_sensor()
    def __init__(self,
                 carla_world: carla.World,
                 traffic_manager: carla.TrafficManager,
                 config: dict,
                 spawn_point: carla.Transform = None):
        """
        Constructor method.

        If spawn_point not given, choose random spawn point recommended by the map.
        """
        self.carla_world = carla_world
        self.tm = traffic_manager
        self.spectator = carla_world.get_spectator()
        try:
            self.map = self.carla_world.get_map()
        except RuntimeError as error:
            print('RuntimeError: {}'.format(error))
            print('  The server could not send the OpenDRIVE (.xodr) file:')
            print(
                '  Make sure it exists, has the same name of your town, and is correct.'
            )
            sys.exit(1)
        self._weather_presets = find_weather_presets()
        self._weather_index = config['world']['weather']
        self.carla_world.set_weather(
            self._weather_presets[self._weather_index][0])
        self.ego_veh = None

        # Containers for managing carla sensors
        self.carla_sensors = {}
        # This dict will store references to all sensor's data container.
        # It is to facilitate the recording, so the recorder only needs to query this one-stop container.
        # When a CarlaSensor is added via add_carla_sensor(), its data container is registered automatically.
        # When sensor data are updated, the content in this dict is updated automatically since they are just pointers.
        self.all_sensor_data = {}

        # Ground truth extractor
        self.ground_truth = None

        # Start simuation
        self.restart(config, spawn_point)
        # Tick the world to bring the ego vehicle actor into effect
        self.carla_world.tick()

        # Placeholder for the behavior agent
        # See set_behavior_agent() method.
        self._behavior_agent = None
        # Placeholder for goals of behavior agent
        self._agent_goals = None
Esempio n. 19
0
def global_plan(
    world: carla.World,  # pylint: disable=no-member
    origin: carla.Location,  # pylint: disable=no-member
    destination: carla.Location,  # pylint: disable=no-member
) -> Tuple[Sequence[carla.Waypoint], Sequence[Any], float]:  # pylint: disable=no-member
    """Generates the optimal plan between two location, respecting the topology.

  Args:
    world: The `CARLA` world.
    origin: The starting location.
    destination: The final destination.

  Returns:
    waypoints: A sequence of waypoints.
    roadoptions: A sequence of commands to navigate at each waypoint.
    distances: The distance per pair of waypoints of the plan.
  """
    try:
        from agents.navigation.global_route_planner import GlobalRoutePlanner  # pylint: disable=import-error
        from agents.navigation.global_route_planner_dao import GlobalRoutePlannerDAO  # pylint: disable=import-error
    except ImportError:
        raise ImportError(
            "Missing CARLA installation, "
            "make sure the environment variable CARLA_ROOT is provided "
            "and that the PythonAPI is `easy_install`ed")

    # Setup global planner.
    grp_dao = GlobalRoutePlannerDAO(wmap=world.get_map(),
                                    sampling_resolution=1)
    grp = GlobalRoutePlanner(grp_dao)
    grp.setup()
    # Generate plan.
    waypoints, roadoptions = zip(*grp.trace_route(origin, destination))
    # Accummulate pairwise distance.
    distances = [0.0]
    for i in range(1, len(waypoints)):
        loc_tm1 = waypoints[i - 1].transform.location
        loc_tm1 = np.asarray([loc_tm1.x, loc_tm1.y, loc_tm1.z])
        loc_t = waypoints[i].transform.location
        loc_t = np.asarray([loc_t.x, loc_t.y, loc_t.z])
        distances.append(np.linalg.norm(loc_tm1 - loc_t))

    return waypoints, roadoptions, distances
Esempio n. 20
0
def compute_all_paths_from_location(
        location: carla.Location,
        carla_world: carla.World,
        dist_between_waypoints: float,
        path_length: int = 10,
        lane_type: carla.LaneType = carla.LaneType.Driving,
        verbose: bool = False):
    paths = []
    path_start = carla_world.get_map().get_waypoint(location,
                                                    lane_type=lane_type)

    if verbose:
        print("Path start - ")
        print_waypoint_info(path_start)

    add_to_path(path_start, paths, [], 0, dist_between_waypoints, path_length,
                verbose)

    return paths
Esempio n. 21
0
def spawn_actor(world: carla.World,
                blueprint: carla.ActorBlueprint,
                spawn_point: carla.Transform,
                attach_to: carla.Actor = None,
                attachment_type=carla.AttachmentType.Rigid) -> carla.Actor:
    """Tries to spawn an actor in a CARLA simulator.
        :param world: a carla.World instance.
        :param blueprint: specifies which actor has to be spawned.
        :param spawn_point: where to spawn the actor. A transform specifies the location and rotation.
        :param attach_to: whether the spawned actor has to be attached (linked) to another one.
        :param attachment_type: the kind of the attachment. Can be 'Rigid' or 'SpringArm'.
        :return: a carla.Actor instance.
    """
    actor = world.try_spawn_actor(blueprint, spawn_point, attach_to,
                                  attachment_type)

    if actor is None:
        raise ValueError(
            f'Cannot spawn actor. Try changing the spawn_point ({spawn_point.location}) to something else.'
        )

    return actor
 def __init__(self,
              client: carla.Client,
              world: carla.World,
              safe_mode=True):
     self.client = client
     self.world = world
     self.spawn_points = self.world.get_map().get_spawn_points()
     self.blueprints = self.world.get_blueprint_library().filter(
         "vehicle.*")
     self.blueprintsWalkers = world.get_blueprint_library().filter(
         "walker.pedestrian.*")
     self.vehicles_list: List[int] = []
     self.walkers_list = []
     self.all_id = []
     self.all_actors = []
     self.safe_mode = safe_mode
     self._bad_colors = [
         "255,255,255", "183,187,162", "237,237,237", "134,134,134",
         "243,243,243", "127,130,135", "109,109,109", "181,181,181",
         "140,140,140", "181,178,124", "171,255,0", "251,241,176",
         "158,149,129", "233,216,168", "233,216,168", "108,109,126",
         "193,193,193", "227,227,227", "151,150,125", "206,206,206",
         "255,222,218", "211,211,211", "191,191,191"
     ] if safe_mode else []
Esempio n. 23
0
def get_lane_boundaries_surface(
    world: carla.World,  # pylint: disable=no-member
    pixels_per_meter: int = 5,
    scale: float = 1.0,
    margin: int = 150,
) -> pygame.Surface:
    """Generates a `PyGame` surface of a CARLA town lane boundaries.

  Heavily inspired by the official CARLA `no_rendering_mode.py` example.

  Args:
    world: The `CARLA` world.
    pixels_per_meter: The number of pixels rendered per meter.
    scale: The scaling factor of the rendered map.
    margin: The number of pixels used for margin.

  Returns
    The lane boundaries of a CARLA town as a `PyGame` surface.
  """
    # Fetch CARLA map.
    carla_map = world.get_map()

    # Setups the `PyGame` surface and offsets.
    world_offset, surface = draw_settings(
        carla_map=carla_map,
        pixels_per_meter=pixels_per_meter,
        scale=scale,
        margin=margin,
    )

    def get_lane_markings(lane_marking_type, waypoints, sign):
        margin = 0.25
        marking_1 = [
            world_to_pixel(
                lateral_shift(w.transform, sign * w.lane_width * 0.5),
                scale,
                world_offset,
                pixels_per_meter,
            ) for w in waypoints
        ]
        if lane_marking_type == carla.LaneMarkingType.Broken or (  # pylint: disable=no-member
                lane_marking_type == carla.LaneMarkingType.Solid):  # pylint: disable=no-member
            return [(lane_marking_type, marking_1)]
        else:
            marking_2 = [
                world_to_pixel(
                    lateral_shift(w.transform,
                                  sign * (w.lane_width * 0.5 + margin * 2)),
                    scale,
                    world_offset,
                    pixels_per_meter,
                ) for w in waypoints
            ]
            if lane_marking_type == carla.LaneMarkingType.SolidBroken:  # pylint: disable=no-member
                return [
                    (carla.LaneMarkingType.Broken, marking_1),  # pylint: disable=no-member
                    (carla.LaneMarkingType.Solid, marking_2),  # pylint: disable=no-member
                ]
            elif lane_marking_type == carla.LaneMarkingType.BrokenSolid:  # pylint: disable=no-member
                return [
                    (carla.LaneMarkingType.Solid, marking_1),  # pylint: disable=no-member
                    (carla.LaneMarkingType.Broken, marking_2),  # pylint: disable=no-member
                ]
            elif lane_marking_type == carla.LaneMarkingType.BrokenBroken:  # pylint: disable=no-member
                return [
                    (carla.LaneMarkingType.Broken, marking_1),  # pylint: disable=no-member
                    (carla.LaneMarkingType.Broken, marking_2),  # pylint: disable=no-member
                ]

            elif lane_marking_type == carla.LaneMarkingType.SolidSolid:  # pylint: disable=no-member
                return [
                    (carla.LaneMarkingType.Solid, marking_1),  # pylint: disable=no-member
                    (carla.LaneMarkingType.Solid, marking_2),  # pylint: disable=no-member
                ]

        return [
            (carla.LaneMarkingType.NONE, []),  # pylint: disable=no-member
        ]

    def draw_solid_line(surface, color, closed, points, width):
        if len(points) >= 2:
            pygame.draw.lines(surface, color, closed, points, width)

    def draw_broken_line(surface, color, closed, points, width):
        broken_lines = [
            x for n, x in enumerate(zip(*(iter(points), ) * 20)) if n % 3 == 0
        ]
        for line in broken_lines:
            pygame.draw.lines(surface, color, closed, line, width)

    def draw_lane_marking_single_side(surface, waypoints, sign):
        lane_marking = None

        marking_type = carla.LaneMarkingType.NONE  # pylint: disable=no-member
        previous_marking_type = carla.LaneMarkingType.NONE  # pylint: disable=no-member

        markings_list = []
        temp_waypoints = []
        current_lane_marking = carla.LaneMarkingType.NONE  # pylint: disable=no-member
        for sample in waypoints:
            lane_marking = sample.left_lane_marking if sign < 0 else sample.right_lane_marking

            if lane_marking is None:
                continue

            marking_type = lane_marking.type

            if current_lane_marking != marking_type:
                markings = get_lane_markings(
                    previous_marking_type,
                    temp_waypoints,
                    sign,
                )
                current_lane_marking = marking_type

                for marking in markings:
                    markings_list.append(marking)

                temp_waypoints = temp_waypoints[-1:]

            else:
                temp_waypoints.append((sample))
                previous_marking_type = marking_type

        # Add last marking.
        last_markings = get_lane_markings(
            previous_marking_type,
            temp_waypoints,
            sign,
        )
        for marking in last_markings:
            markings_list.append(marking)

        for markings in markings_list:
            if markings[0] == carla.LaneMarkingType.Solid:  # pylint: disable=no-member
                draw_solid_line(
                    surface,
                    COLORS["WHITE"],
                    False,
                    markings[1],
                    2,
                )
            elif markings[0] == carla.LaneMarkingType.Broken:  # pylint: disable=no-member
                draw_broken_line(
                    surface,
                    COLORS["WHITE"],
                    False,
                    markings[1],
                    2,
                )

    # Set background black
    surface.fill(COLORS["BLACK"])
    precision = 0.05

    # Parse OpenDrive topology.
    topology = [x[0] for x in carla_map.get_topology()]
    topology = sorted(topology, key=lambda w: w.transform.location.z)
    set_waypoints = []
    for waypoint in topology:
        waypoints = [waypoint]

        nxt = waypoint.next(precision)
        if len(nxt) > 0:
            nxt = nxt[0]
            while nxt.road_id == waypoint.road_id:
                waypoints.append(nxt)
                nxt = nxt.next(precision)
                if len(nxt) > 0:
                    nxt = nxt[0]
                else:
                    break
        set_waypoints.append(waypoints)

    # Draw roads.
    for waypoints in set_waypoints:
        waypoint = waypoints[0]
        road_left_side = [
            lateral_shift(w.transform, -w.lane_width * 0.5) for w in waypoints
        ]
        road_right_side = [
            lateral_shift(w.transform, w.lane_width * 0.5) for w in waypoints
        ]

        polygon = road_left_side + [x for x in reversed(road_right_side)]
        polygon = [
            world_to_pixel(
                x,
                scale=scale,
                offset=world_offset,
                pixels_per_meter=pixels_per_meter,
            ) for x in polygon
        ]

        # Draw Lane Markings
        if not waypoint.is_junction:
            # Left Side
            draw_lane_marking_single_side(surface, waypoints, -1)
            # Right Side
            draw_lane_marking_single_side(surface, waypoints, 1)

    return surface
Esempio n. 24
0
def get_road_surface(
    world: carla.World,  # pylint: disable=no-member
    pixels_per_meter: int = 5,
    scale: float = 1.0,
    margin: int = 150,
) -> pygame.Surface:
    """Generates a `PyGame` surface of a CARLA town.

  Heavily inspired by the official CARLA `no_rendering_mode.py` example.

  Args:
    world: The `CARLA` world.
    pixels_per_meter: The number of pixels rendered per meter.
    scale: The scaling factor of the rendered map.
    margin: The number of pixels used for margin.

  Returns
    The topology of a CARLA town as a `PyGame` surface.
  """
    # Fetch CARLA map.
    carla_map = world.get_map()

    # Setups the `PyGame` surface and offsets.
    world_offset, surface = draw_settings(
        carla_map=carla_map,
        pixels_per_meter=pixels_per_meter,
        scale=scale,
        margin=margin,
    )

    # Set background black
    surface.fill(COLORS["BLACK"])
    precision = 0.05

    # Parse OpenDrive topology.
    topology = [x[0] for x in carla_map.get_topology()]
    topology = sorted(topology, key=lambda w: w.transform.location.z)
    set_waypoints = []
    for waypoint in topology:
        waypoints = [waypoint]

        nxt = waypoint.next(precision)
        if len(nxt) > 0:
            nxt = nxt[0]
            while nxt.road_id == waypoint.road_id:
                waypoints.append(nxt)
                nxt = nxt.next(precision)
                if len(nxt) > 0:
                    nxt = nxt[0]
                else:
                    break
        set_waypoints.append(waypoints)

    # Draw roads.
    for waypoints in set_waypoints:
        waypoint = waypoints[0]
        road_left_side = [
            lateral_shift(w.transform, -w.lane_width * 0.5) for w in waypoints
        ]
        road_right_side = [
            lateral_shift(w.transform, w.lane_width * 0.5) for w in waypoints
        ]

        polygon = road_left_side + [x for x in reversed(road_right_side)]
        polygon = [
            world_to_pixel(
                x,
                scale=scale,
                offset=world_offset,
                pixels_per_meter=pixels_per_meter,
            ) for x in polygon
        ]

        if len(polygon) > 2:
            pygame.draw.polygon(surface, COLORS["WHITE"], polygon, 5)
            pygame.draw.polygon(surface, COLORS["WHITE"], polygon)

    return surface
Esempio n. 25
0
def get_traffic_lights_surface(
    world: carla.World,  # pylint: disable=no-member
    pixels_per_meter: int = 5,
    scale: float = 1.0,
    margin: int = 150,
) -> Tuple[pygame.Surface, pygame.Surface, pygame.Surface]:
    """Generates three `PyGame` surfaces of traffic lights (Green, Yellow, Red).

  Args:
    world: The `CARLA` world.
    pixels_per_meter: The number of pixels rendered per meter.
    scale: The scaling factor of the rendered map.
    margin: The number of pixels used for margin.

  Returns
    The traffic lights rendered as `PyGame` surface (Green, Yellow, Red).
  """
    # Fetch CARLA map.
    carla_map = world.get_map()

    # Fetch all the pedestrians.
    traffic_lights = [
        actor for actor in world.get_actors()
        if "traffic.traffic_light" in actor.type_id
    ]

    # Setups the `PyGame` surface and offsets.
    world_offset, green_surface = draw_settings(
        carla_map=carla_map,
        pixels_per_meter=pixels_per_meter,
        scale=scale,
        margin=margin,
    )
    width = green_surface.get_width()
    height = green_surface.get_height()
    yellow_surface = pygame.Surface((width, height))  # pylint: disable=too-many-function-args
    red_surface = pygame.Surface((width, height))  # pylint: disable=too-many-function-args

    # Set background black
    green_surface.fill(COLORS["BLACK"])
    yellow_surface.fill(COLORS["BLACK"])
    red_surface.fill(COLORS["BLACK"])

    # Iterate over pedestrians.
    for traffic_light in traffic_lights:
        # Identify state of the traffic light.
        if traffic_light.state.name == "Green":
            surface = green_surface
        elif traffic_light.state.name == "Yellow":
            surface = yellow_surface
        elif traffic_light.state.name == "Red":
            surface = red_surface
        else:
            continue
        # Convert to pixel coordinates.
        center = world_to_pixel(
            traffic_light.get_transform().location,
            scale,
            world_offset,
            pixels_per_meter,
        )
        pygame.draw.circle(surface, COLORS["WHITE"], center, 10)

    return green_surface, yellow_surface, red_surface
Esempio n. 26
0
def get_blueprint(world: carla.World, actor_id: str) -> carla.ActorBlueprint:
    return world.get_blueprint_library().find(actor_id)
def get_synchronous_mode(world: carla.World):
    return world.get_settings().synchronous_mode
def set_traffic_lights_green(world: carla.World):
    set_world_asynchronous(world)
    for tl in world.get_actors().filter('traffic.*'):
        if isinstance(tl, carla.TrafficLight):
            tl.set_state(carla.TrafficLightState.Green)
            tl.freeze(True)
def set_world_rendering_option(world: carla.World, render: bool):
    if world is None:
        return
    settings = world.get_settings()
    settings.no_rendering_mode = not render
    world.apply_settings(settings)