2018-12-14 03:55:34 +08:00
|
|
|
#!/usr/bin/env python
|
|
|
|
|
|
|
|
# Copyright (c) 2018 Intel Labs.
|
|
|
|
# authors: German Ros (german.ros@intel.com)
|
|
|
|
#
|
|
|
|
# This work is licensed under the terms of the MIT license.
|
|
|
|
# For a copy, see <https://opensource.org/licenses/MIT>.
|
|
|
|
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Example of automatic vehicle control from client side."""
|
2018-12-14 03:55:34 +08:00
|
|
|
|
|
|
|
from __future__ import print_function
|
|
|
|
|
|
|
|
import argparse
|
2018-12-20 03:17:15 +08:00
|
|
|
import collections
|
|
|
|
import datetime
|
|
|
|
import glob
|
2018-12-14 03:55:34 +08:00
|
|
|
import logging
|
2018-12-20 03:17:15 +08:00
|
|
|
import math
|
|
|
|
import os
|
2021-06-21 21:32:49 +08:00
|
|
|
import numpy.random as random
|
2018-12-14 03:55:34 +08:00
|
|
|
import re
|
2018-12-20 03:17:15 +08:00
|
|
|
import sys
|
2018-12-14 03:55:34 +08:00
|
|
|
import weakref
|
|
|
|
|
|
|
|
try:
|
|
|
|
import pygame
|
2018-12-20 03:17:15 +08:00
|
|
|
from pygame.locals import KMOD_CTRL
|
|
|
|
from pygame.locals import K_ESCAPE
|
|
|
|
from pygame.locals import K_q
|
2018-12-14 03:55:34 +08:00
|
|
|
except ImportError:
|
2018-12-20 03:17:15 +08:00
|
|
|
raise RuntimeError('cannot import pygame, make sure pygame package is installed')
|
2018-12-14 03:55:34 +08:00
|
|
|
|
|
|
|
try:
|
|
|
|
import numpy as np
|
|
|
|
except ImportError:
|
|
|
|
raise RuntimeError(
|
|
|
|
'cannot import numpy, make sure numpy package is installed')
|
|
|
|
|
2018-12-20 03:17:15 +08:00
|
|
|
# ==============================================================================
|
2020-03-17 18:31:05 +08:00
|
|
|
# -- Find CARLA module ---------------------------------------------------------
|
2018-12-20 03:17:15 +08:00
|
|
|
# ==============================================================================
|
|
|
|
try:
|
2019-03-29 02:15:13 +08:00
|
|
|
sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
|
2018-12-20 03:17:15 +08:00
|
|
|
sys.version_info.major,
|
|
|
|
sys.version_info.minor,
|
|
|
|
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
|
|
|
|
except IndexError:
|
|
|
|
pass
|
|
|
|
|
2019-02-13 09:44:07 +08:00
|
|
|
# ==============================================================================
|
2020-03-17 18:31:05 +08:00
|
|
|
# -- Add PythonAPI for release mode --------------------------------------------
|
2019-02-13 09:44:07 +08:00
|
|
|
# ==============================================================================
|
|
|
|
try:
|
2019-07-08 22:39:05 +08:00
|
|
|
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/carla')
|
2019-02-13 09:44:07 +08:00
|
|
|
except IndexError:
|
|
|
|
pass
|
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
import carla
|
|
|
|
from carla import ColorConverter as cc
|
2020-03-17 18:31:05 +08:00
|
|
|
|
|
|
|
from agents.navigation.behavior_agent import BehaviorAgent # pylint: disable=import-error
|
|
|
|
from agents.navigation.basic_agent import BasicAgent # pylint: disable=import-error
|
2022-04-20 20:44:27 +08:00
|
|
|
from agents.navigation.constant_velocity_agent import ConstantVelocityAgent # pylint: disable=import-error
|
2018-12-21 06:15:06 +08:00
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
|
|
|
|
# ==============================================================================
|
2018-12-20 03:17:15 +08:00
|
|
|
# -- Global functions ----------------------------------------------------------
|
2018-12-14 03:55:34 +08:00
|
|
|
# ==============================================================================
|
|
|
|
|
2020-03-17 18:31:05 +08:00
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
def find_weather_presets():
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Method to find weather presets"""
|
2018-12-14 03:55:34 +08:00
|
|
|
rgx = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)')
|
2020-03-17 18:31:05 +08:00
|
|
|
def name(x): return ' '.join(m.group(0) for m in rgx.finditer(x))
|
2018-12-20 03:17:15 +08:00
|
|
|
presets = [x for x in dir(carla.WeatherParameters) if re.match('[A-Z].+', x)]
|
2018-12-14 03:55:34 +08:00
|
|
|
return [(getattr(carla.WeatherParameters, x), name(x)) for x in presets]
|
|
|
|
|
|
|
|
|
2018-12-20 03:17:15 +08:00
|
|
|
def get_actor_display_name(actor, truncate=250):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Method to get actor display name"""
|
2018-12-20 03:17:15 +08:00
|
|
|
name = ' '.join(actor.type_id.replace('_', '.').title().split('.')[1:])
|
2019-03-19 19:20:59 +08:00
|
|
|
return (name[:truncate - 1] + u'\u2026') if len(name) > truncate else name
|
2018-12-20 03:17:15 +08:00
|
|
|
|
2022-04-20 20:44:27 +08:00
|
|
|
def get_actor_blueprints(world, filter, generation):
|
|
|
|
bps = world.get_blueprint_library().filter(filter)
|
|
|
|
|
|
|
|
if generation.lower() == "all":
|
|
|
|
return bps
|
|
|
|
|
|
|
|
# If the filter returns only one bp, we assume that this one needed
|
|
|
|
# and therefore, we ignore the generation
|
|
|
|
if len(bps) == 1:
|
|
|
|
return bps
|
|
|
|
|
|
|
|
try:
|
|
|
|
int_generation = int(generation)
|
|
|
|
# Check if generation is in available generations
|
2023-06-17 02:41:06 +08:00
|
|
|
if int_generation in [1, 2, 3]:
|
2022-04-20 20:44:27 +08:00
|
|
|
bps = [x for x in bps if int(x.get_attribute('generation')) == int_generation]
|
|
|
|
return bps
|
|
|
|
else:
|
|
|
|
print(" Warning! Actor Generation is not valid. No actor will be spawned.")
|
|
|
|
return []
|
|
|
|
except:
|
|
|
|
print(" Warning! Actor Generation is not valid. No actor will be spawned.")
|
|
|
|
return []
|
2018-12-20 03:17:15 +08:00
|
|
|
|
|
|
|
# ==============================================================================
|
|
|
|
# -- World ---------------------------------------------------------------
|
|
|
|
# ==============================================================================
|
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
class World(object):
|
2020-03-17 18:31:05 +08:00
|
|
|
""" Class representing the surrounding environment """
|
|
|
|
|
|
|
|
def __init__(self, carla_world, hud, args):
|
|
|
|
"""Constructor method"""
|
2021-06-21 21:32:49 +08:00
|
|
|
self._args = args
|
2018-12-14 03:55:34 +08:00
|
|
|
self.world = carla_world
|
2020-03-17 18:31:05 +08:00
|
|
|
try:
|
|
|
|
self.map = self.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)
|
2018-12-14 03:55:34 +08:00
|
|
|
self.hud = hud
|
2019-03-14 14:31:40 +08:00
|
|
|
self.player = None
|
2018-12-20 03:17:15 +08:00
|
|
|
self.collision_sensor = None
|
|
|
|
self.lane_invasion_sensor = None
|
2019-03-14 14:31:40 +08:00
|
|
|
self.gnss_sensor = None
|
2018-12-20 03:17:15 +08:00
|
|
|
self.camera_manager = None
|
2018-12-14 03:55:34 +08:00
|
|
|
self._weather_presets = find_weather_presets()
|
|
|
|
self._weather_index = 0
|
2020-03-17 18:31:05 +08:00
|
|
|
self._actor_filter = args.filter
|
2022-04-20 20:44:27 +08:00
|
|
|
self._actor_generation = args.generation
|
2020-03-17 18:31:05 +08:00
|
|
|
self.restart(args)
|
2018-12-20 03:17:15 +08:00
|
|
|
self.world.on_tick(hud.on_world_tick)
|
2019-03-14 14:31:40 +08:00
|
|
|
self.recording_enabled = False
|
|
|
|
self.recording_start = 0
|
2018-12-14 03:55:34 +08:00
|
|
|
|
2020-03-17 18:31:05 +08:00
|
|
|
def restart(self, args):
|
|
|
|
"""Restart the world"""
|
2018-12-20 03:17:15 +08:00
|
|
|
# Keep same camera config if the camera manager exists.
|
2019-03-14 14:31:40 +08:00
|
|
|
cam_index = self.camera_manager.index if self.camera_manager is not None else 0
|
2020-03-17 18:31:05 +08:00
|
|
|
cam_pos_id = self.camera_manager.transform_index if self.camera_manager is not None else 0
|
|
|
|
|
2019-03-14 14:31:40 +08:00
|
|
|
# Get a random blueprint.
|
2023-04-21 18:58:13 +08:00
|
|
|
blueprint_list = get_actor_blueprints(self.world, self._actor_filter, self._actor_generation)
|
|
|
|
if not blueprint_list:
|
|
|
|
raise ValueError("Couldn't find any blueprints with the specified filters")
|
|
|
|
blueprint = random.choice(blueprint_list)
|
2018-12-20 03:17:15 +08:00
|
|
|
blueprint.set_attribute('role_name', 'hero')
|
|
|
|
if blueprint.has_attribute('color'):
|
|
|
|
color = random.choice(blueprint.get_attribute('color').recommended_values)
|
|
|
|
blueprint.set_attribute('color', color)
|
2021-06-21 21:32:49 +08:00
|
|
|
|
2019-03-14 14:31:40 +08:00
|
|
|
# Spawn the player.
|
|
|
|
if self.player is not None:
|
|
|
|
spawn_point = self.player.get_transform()
|
2018-12-20 03:17:15 +08:00
|
|
|
spawn_point.location.z += 2.0
|
|
|
|
spawn_point.rotation.roll = 0.0
|
|
|
|
spawn_point.rotation.pitch = 0.0
|
|
|
|
self.destroy()
|
2019-03-14 14:31:40 +08:00
|
|
|
self.player = self.world.try_spawn_actor(blueprint, spawn_point)
|
2021-06-19 00:06:25 +08:00
|
|
|
self.modify_vehicle_physics(self.player)
|
2019-03-14 14:31:40 +08:00
|
|
|
while self.player is None:
|
2020-03-17 18:31:05 +08:00
|
|
|
if not self.map.get_spawn_points():
|
|
|
|
print('There are no spawn points available in your map/town.')
|
|
|
|
print('Please add some Vehicle Spawn Point to your UE4 scene.')
|
|
|
|
sys.exit(1)
|
2019-02-19 02:48:50 +08:00
|
|
|
spawn_points = self.map.get_spawn_points()
|
2019-03-14 14:31:40 +08:00
|
|
|
spawn_point = random.choice(spawn_points) if spawn_points else carla.Transform()
|
|
|
|
self.player = self.world.try_spawn_actor(blueprint, spawn_point)
|
2021-06-19 00:06:25 +08:00
|
|
|
self.modify_vehicle_physics(self.player)
|
2021-06-21 21:32:49 +08:00
|
|
|
|
|
|
|
if self._args.sync:
|
|
|
|
self.world.tick()
|
|
|
|
else:
|
|
|
|
self.world.wait_for_tick()
|
|
|
|
|
2018-12-20 03:17:15 +08:00
|
|
|
# Set up the sensors.
|
2019-03-14 14:31:40 +08:00
|
|
|
self.collision_sensor = CollisionSensor(self.player, self.hud)
|
|
|
|
self.lane_invasion_sensor = LaneInvasionSensor(self.player, self.hud)
|
|
|
|
self.gnss_sensor = GnssSensor(self.player)
|
2021-06-21 21:32:49 +08:00
|
|
|
self.camera_manager = CameraManager(self.player, self.hud)
|
2020-03-17 18:31:05 +08:00
|
|
|
self.camera_manager.transform_index = cam_pos_id
|
2018-12-14 03:55:34 +08:00
|
|
|
self.camera_manager.set_sensor(cam_index, notify=False)
|
2019-03-14 14:31:40 +08:00
|
|
|
actor_type = get_actor_display_name(self.player)
|
2018-12-14 03:55:34 +08:00
|
|
|
self.hud.notification(actor_type)
|
|
|
|
|
|
|
|
def next_weather(self, reverse=False):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Get next weather setting"""
|
2018-12-14 03:55:34 +08:00
|
|
|
self._weather_index += -1 if reverse else 1
|
|
|
|
self._weather_index %= len(self._weather_presets)
|
|
|
|
preset = self._weather_presets[self._weather_index]
|
|
|
|
self.hud.notification('Weather: %s' % preset[1])
|
2019-03-14 14:31:40 +08:00
|
|
|
self.player.get_world().set_weather(preset[0])
|
2018-12-14 03:55:34 +08:00
|
|
|
|
2021-06-19 00:06:25 +08:00
|
|
|
def modify_vehicle_physics(self, actor):
|
|
|
|
#If actor is not a vehicle, we cannot use the physics control
|
|
|
|
try:
|
|
|
|
physics_control = actor.get_physics_control()
|
|
|
|
physics_control.use_sweep_wheel_collision = True
|
|
|
|
actor.apply_physics_control(physics_control)
|
|
|
|
except Exception:
|
|
|
|
pass
|
2021-06-21 17:07:05 +08:00
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
def tick(self, clock):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Method for every tick"""
|
2018-12-14 03:55:34 +08:00
|
|
|
self.hud.tick(self, clock)
|
|
|
|
|
|
|
|
def render(self, display):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Render world"""
|
2018-12-14 03:55:34 +08:00
|
|
|
self.camera_manager.render(display)
|
|
|
|
self.hud.render(display)
|
|
|
|
|
2019-03-14 14:31:40 +08:00
|
|
|
def destroy_sensors(self):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Destroy sensors"""
|
2019-03-14 14:31:40 +08:00
|
|
|
self.camera_manager.sensor.destroy()
|
|
|
|
self.camera_manager.sensor = None
|
|
|
|
self.camera_manager.index = None
|
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
def destroy(self):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Destroys all actors"""
|
2018-12-20 03:17:15 +08:00
|
|
|
actors = [
|
|
|
|
self.camera_manager.sensor,
|
|
|
|
self.collision_sensor.sensor,
|
|
|
|
self.lane_invasion_sensor.sensor,
|
2019-03-14 14:31:40 +08:00
|
|
|
self.gnss_sensor.sensor,
|
|
|
|
self.player]
|
2018-12-20 03:17:15 +08:00
|
|
|
for actor in actors:
|
2018-12-14 03:55:34 +08:00
|
|
|
if actor is not None:
|
|
|
|
actor.destroy()
|
|
|
|
|
2019-12-18 02:40:27 +08:00
|
|
|
|
2018-12-20 03:17:15 +08:00
|
|
|
# ==============================================================================
|
|
|
|
# -- KeyboardControl -----------------------------------------------------------
|
|
|
|
# ==============================================================================
|
|
|
|
|
2019-03-14 14:31:40 +08:00
|
|
|
|
2018-12-20 03:17:15 +08:00
|
|
|
class KeyboardControl(object):
|
2019-12-18 02:40:27 +08:00
|
|
|
def __init__(self, world):
|
2018-12-20 03:17:15 +08:00
|
|
|
world.hud.notification("Press 'H' or '?' for help.", seconds=4.0)
|
|
|
|
|
2019-12-18 02:40:27 +08:00
|
|
|
def parse_events(self):
|
2018-12-20 03:17:15 +08:00
|
|
|
for event in pygame.event.get():
|
|
|
|
if event.type == pygame.QUIT:
|
|
|
|
return True
|
2020-03-17 18:31:05 +08:00
|
|
|
if event.type == pygame.KEYUP:
|
2018-12-20 03:17:15 +08:00
|
|
|
if self._is_quit_shortcut(event.key):
|
|
|
|
return True
|
2019-03-14 14:31:40 +08:00
|
|
|
|
2018-12-20 03:17:15 +08:00
|
|
|
@staticmethod
|
|
|
|
def _is_quit_shortcut(key):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Shortcut for quitting"""
|
2018-12-20 03:17:15 +08:00
|
|
|
return (key == K_ESCAPE) or (key == K_q and pygame.key.get_mods() & KMOD_CTRL)
|
2018-12-14 03:55:34 +08:00
|
|
|
|
|
|
|
# ==============================================================================
|
2019-03-14 14:31:40 +08:00
|
|
|
# -- HUD -----------------------------------------------------------------------
|
2018-12-14 03:55:34 +08:00
|
|
|
# ==============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
class HUD(object):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Class for HUD text"""
|
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
def __init__(self, width, height):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Constructor method"""
|
2018-12-14 03:55:34 +08:00
|
|
|
self.dim = (width, height)
|
|
|
|
font = pygame.font.Font(pygame.font.get_default_font(), 20)
|
2019-10-28 19:02:00 +08:00
|
|
|
font_name = 'courier' if os.name == 'nt' else 'mono'
|
|
|
|
fonts = [x for x in pygame.font.get_fonts() if font_name in x]
|
2018-12-20 03:17:15 +08:00
|
|
|
default_font = 'ubuntumono'
|
|
|
|
mono = default_font if default_font in fonts else fonts[0]
|
|
|
|
mono = pygame.font.match_font(mono)
|
2019-10-28 19:02:00 +08:00
|
|
|
self._font_mono = pygame.font.Font(mono, 12 if os.name == 'nt' else 14)
|
2018-12-14 03:55:34 +08:00
|
|
|
self._notifications = FadingText(font, (width, 40), (0, height - 40))
|
|
|
|
self.help = HelpText(pygame.font.Font(mono, 24), width, height)
|
2018-12-20 03:17:15 +08:00
|
|
|
self.server_fps = 0
|
2019-06-25 21:50:47 +08:00
|
|
|
self.frame = 0
|
2018-12-20 03:17:15 +08:00
|
|
|
self.simulation_time = 0
|
|
|
|
self._show_info = True
|
|
|
|
self._info_text = []
|
|
|
|
self._server_clock = pygame.time.Clock()
|
|
|
|
|
|
|
|
def on_world_tick(self, timestamp):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Gets informations from the world at every tick"""
|
2018-12-20 03:17:15 +08:00
|
|
|
self._server_clock.tick()
|
|
|
|
self.server_fps = self._server_clock.get_fps()
|
2020-03-17 18:31:05 +08:00
|
|
|
self.frame = timestamp.frame_count
|
2018-12-20 03:17:15 +08:00
|
|
|
self.simulation_time = timestamp.elapsed_seconds
|
2018-12-14 03:55:34 +08:00
|
|
|
|
|
|
|
def tick(self, world, clock):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""HUD method for every tick"""
|
2019-03-14 14:31:40 +08:00
|
|
|
self._notifications.tick(world, clock)
|
2018-12-20 03:17:15 +08:00
|
|
|
if not self._show_info:
|
|
|
|
return
|
2020-03-17 18:31:05 +08:00
|
|
|
transform = world.player.get_transform()
|
|
|
|
vel = world.player.get_velocity()
|
|
|
|
control = world.player.get_control()
|
|
|
|
heading = 'N' if abs(transform.rotation.yaw) < 89.5 else ''
|
|
|
|
heading += 'S' if abs(transform.rotation.yaw) > 90.5 else ''
|
|
|
|
heading += 'E' if 179.5 > transform.rotation.yaw > 0.5 else ''
|
|
|
|
heading += 'W' if -0.5 > transform.rotation.yaw > -179.5 else ''
|
2018-12-20 03:17:15 +08:00
|
|
|
colhist = world.collision_sensor.get_collision_history()
|
2019-06-25 21:50:47 +08:00
|
|
|
collision = [colhist[x + self.frame - 200] for x in range(0, 200)]
|
2018-12-20 03:17:15 +08:00
|
|
|
max_col = max(1.0, max(collision))
|
|
|
|
collision = [x / max_col for x in collision]
|
|
|
|
vehicles = world.world.get_actors().filter('vehicle.*')
|
2020-03-17 18:31:05 +08:00
|
|
|
|
2018-12-20 03:17:15 +08:00
|
|
|
self._info_text = [
|
2019-03-14 14:31:40 +08:00
|
|
|
'Server: % 16.0f FPS' % self.server_fps,
|
|
|
|
'Client: % 16.0f FPS' % clock.get_fps(),
|
2018-12-20 03:17:15 +08:00
|
|
|
'',
|
2019-03-14 14:31:40 +08:00
|
|
|
'Vehicle: % 20s' % get_actor_display_name(world.player, truncate=20),
|
2021-08-02 22:24:37 +08:00
|
|
|
'Map: % 20s' % world.map.name.split('/')[-1],
|
2018-12-20 03:17:15 +08:00
|
|
|
'Simulation time: % 12s' % datetime.timedelta(seconds=int(self.simulation_time)),
|
|
|
|
'',
|
2020-03-17 18:31:05 +08:00
|
|
|
'Speed: % 15.0f km/h' % (3.6 * math.sqrt(vel.x**2 + vel.y**2 + vel.z**2)),
|
|
|
|
u'Heading:% 16.0f\N{DEGREE SIGN} % 2s' % (transform.rotation.yaw, heading),
|
|
|
|
'Location:% 20s' % ('(% 5.1f, % 5.1f)' % (transform.location.x, transform.location.y)),
|
2019-03-14 14:31:40 +08:00
|
|
|
'GNSS:% 24s' % ('(% 2.6f, % 3.6f)' % (world.gnss_sensor.lat, world.gnss_sensor.lon)),
|
2020-03-17 18:31:05 +08:00
|
|
|
'Height: % 18.0f m' % transform.location.z,
|
2019-03-14 14:31:40 +08:00
|
|
|
'']
|
2020-03-17 18:31:05 +08:00
|
|
|
if isinstance(control, carla.VehicleControl):
|
2019-03-14 14:31:40 +08:00
|
|
|
self._info_text += [
|
2020-03-17 18:31:05 +08:00
|
|
|
('Throttle:', control.throttle, 0.0, 1.0),
|
|
|
|
('Steer:', control.steer, -1.0, 1.0),
|
|
|
|
('Brake:', control.brake, 0.0, 1.0),
|
|
|
|
('Reverse:', control.reverse),
|
|
|
|
('Hand brake:', control.hand_brake),
|
|
|
|
('Manual:', control.manual_gear_shift),
|
|
|
|
'Gear: %s' % {-1: 'R', 0: 'N'}.get(control.gear, control.gear)]
|
|
|
|
elif isinstance(control, carla.WalkerControl):
|
2019-03-14 14:31:40 +08:00
|
|
|
self._info_text += [
|
2020-03-17 18:31:05 +08:00
|
|
|
('Speed:', control.speed, 0.0, 5.556),
|
|
|
|
('Jump:', control.jump)]
|
2019-03-14 14:31:40 +08:00
|
|
|
self._info_text += [
|
2018-12-20 03:17:15 +08:00
|
|
|
'',
|
|
|
|
'Collision:',
|
|
|
|
collision,
|
|
|
|
'',
|
2019-03-14 14:31:40 +08:00
|
|
|
'Number of vehicles: % 8d' % len(vehicles)]
|
2020-03-17 18:31:05 +08:00
|
|
|
|
2018-12-20 03:17:15 +08:00
|
|
|
if len(vehicles) > 1:
|
|
|
|
self._info_text += ['Nearby vehicles:']
|
2019-03-19 19:20:59 +08:00
|
|
|
|
2020-03-17 18:31:05 +08:00
|
|
|
def dist(l):
|
|
|
|
return math.sqrt((l.x - transform.location.x)**2 + (l.y - transform.location.y)
|
|
|
|
** 2 + (l.z - transform.location.z)**2)
|
|
|
|
vehicles = [(dist(x.get_location()), x) for x in vehicles if x.id != world.player.id]
|
|
|
|
|
|
|
|
for dist, vehicle in sorted(vehicles):
|
|
|
|
if dist > 200.0:
|
|
|
|
break
|
|
|
|
vehicle_type = get_actor_display_name(vehicle, truncate=22)
|
|
|
|
self._info_text.append('% 4dm %s' % (dist, vehicle_type))
|
2018-12-14 03:55:34 +08:00
|
|
|
|
2018-12-20 03:17:15 +08:00
|
|
|
def toggle_info(self):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Toggle info on or off"""
|
2018-12-20 03:17:15 +08:00
|
|
|
self._show_info = not self._show_info
|
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
def notification(self, text, seconds=2.0):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Notification text"""
|
2018-12-14 03:55:34 +08:00
|
|
|
self._notifications.set_text(text, seconds=seconds)
|
|
|
|
|
|
|
|
def error(self, text):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Error text"""
|
2018-12-14 03:55:34 +08:00
|
|
|
self._notifications.set_text('Error: %s' % text, (255, 0, 0))
|
|
|
|
|
|
|
|
def render(self, display):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Render for HUD class"""
|
2018-12-20 03:17:15 +08:00
|
|
|
if self._show_info:
|
|
|
|
info_surface = pygame.Surface((220, self.dim[1]))
|
|
|
|
info_surface.set_alpha(100)
|
|
|
|
display.blit(info_surface, (0, 0))
|
|
|
|
v_offset = 4
|
|
|
|
bar_h_offset = 100
|
|
|
|
bar_width = 106
|
|
|
|
for item in self._info_text:
|
|
|
|
if v_offset + 18 > self.dim[1]:
|
|
|
|
break
|
|
|
|
if isinstance(item, list):
|
|
|
|
if len(item) > 1:
|
2020-03-17 18:31:05 +08:00
|
|
|
points = [(x + 8, v_offset + 8 + (1 - y) * 30) for x, y in enumerate(item)]
|
2018-12-20 03:17:15 +08:00
|
|
|
pygame.draw.lines(display, (255, 136, 0), False, points, 2)
|
|
|
|
item = None
|
|
|
|
v_offset += 18
|
|
|
|
elif isinstance(item, tuple):
|
|
|
|
if isinstance(item[1], bool):
|
|
|
|
rect = pygame.Rect((bar_h_offset, v_offset + 8), (6, 6))
|
|
|
|
pygame.draw.rect(display, (255, 255, 255), rect, 0 if item[1] else 1)
|
|
|
|
else:
|
|
|
|
rect_border = pygame.Rect((bar_h_offset, v_offset + 8), (bar_width, 6))
|
|
|
|
pygame.draw.rect(display, (255, 255, 255), rect_border, 1)
|
2020-03-17 18:31:05 +08:00
|
|
|
fig = (item[1] - item[2]) / (item[3] - item[2])
|
2018-12-20 03:17:15 +08:00
|
|
|
if item[2] < 0.0:
|
2020-03-17 18:31:05 +08:00
|
|
|
rect = pygame.Rect(
|
|
|
|
(bar_h_offset + fig * (bar_width - 6), v_offset + 8), (6, 6))
|
2018-12-20 03:17:15 +08:00
|
|
|
else:
|
2020-03-17 18:31:05 +08:00
|
|
|
rect = pygame.Rect((bar_h_offset, v_offset + 8), (fig * bar_width, 6))
|
2018-12-20 03:17:15 +08:00
|
|
|
pygame.draw.rect(display, (255, 255, 255), rect)
|
|
|
|
item = item[0]
|
2019-03-14 14:31:40 +08:00
|
|
|
if item: # At this point has to be a str.
|
2018-12-20 03:17:15 +08:00
|
|
|
surface = self._font_mono.render(item, True, (255, 255, 255))
|
|
|
|
display.blit(surface, (8, v_offset))
|
|
|
|
v_offset += 18
|
2018-12-14 03:55:34 +08:00
|
|
|
self._notifications.render(display)
|
|
|
|
self.help.render(display)
|
|
|
|
|
|
|
|
# ==============================================================================
|
2018-12-20 03:17:15 +08:00
|
|
|
# -- FadingText ----------------------------------------------------------------
|
2018-12-14 03:55:34 +08:00
|
|
|
# ==============================================================================
|
|
|
|
|
2019-03-14 14:31:40 +08:00
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
class FadingText(object):
|
2020-03-17 18:31:05 +08:00
|
|
|
""" Class for fading text """
|
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
def __init__(self, font, dim, pos):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Constructor method"""
|
2018-12-14 03:55:34 +08:00
|
|
|
self.font = font
|
|
|
|
self.dim = dim
|
|
|
|
self.pos = pos
|
|
|
|
self.seconds_left = 0
|
|
|
|
self.surface = pygame.Surface(self.dim)
|
|
|
|
|
|
|
|
def set_text(self, text, color=(255, 255, 255), seconds=2.0):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Set fading text"""
|
2018-12-14 03:55:34 +08:00
|
|
|
text_texture = self.font.render(text, True, color)
|
|
|
|
self.surface = pygame.Surface(self.dim)
|
|
|
|
self.seconds_left = seconds
|
|
|
|
self.surface.fill((0, 0, 0, 0))
|
|
|
|
self.surface.blit(text_texture, (10, 11))
|
|
|
|
|
|
|
|
def tick(self, _, clock):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Fading text method for every tick"""
|
2018-12-14 03:55:34 +08:00
|
|
|
delta_seconds = 1e-3 * clock.get_time()
|
|
|
|
self.seconds_left = max(0.0, self.seconds_left - delta_seconds)
|
|
|
|
self.surface.set_alpha(500.0 * self.seconds_left)
|
|
|
|
|
|
|
|
def render(self, display):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Render fading text method"""
|
2018-12-14 03:55:34 +08:00
|
|
|
display.blit(self.surface, self.pos)
|
|
|
|
|
|
|
|
# ==============================================================================
|
2018-12-20 03:17:15 +08:00
|
|
|
# -- HelpText ------------------------------------------------------------------
|
2018-12-14 03:55:34 +08:00
|
|
|
# ==============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
class HelpText(object):
|
2020-03-17 18:31:05 +08:00
|
|
|
""" Helper class for text render"""
|
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
def __init__(self, font, width, height):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Constructor method"""
|
2018-12-14 03:55:34 +08:00
|
|
|
lines = __doc__.split('\n')
|
|
|
|
self.font = font
|
|
|
|
self.dim = (680, len(lines) * 22 + 12)
|
2018-12-20 03:17:15 +08:00
|
|
|
self.pos = (0.5 * width - 0.5 * self.dim[0], 0.5 * height - 0.5 * self.dim[1])
|
2018-12-14 03:55:34 +08:00
|
|
|
self.seconds_left = 0
|
|
|
|
self.surface = pygame.Surface(self.dim)
|
|
|
|
self.surface.fill((0, 0, 0, 0))
|
2020-03-17 18:31:05 +08:00
|
|
|
for i, line in enumerate(lines):
|
2018-12-14 03:55:34 +08:00
|
|
|
text_texture = self.font.render(line, True, (255, 255, 255))
|
2020-03-17 18:31:05 +08:00
|
|
|
self.surface.blit(text_texture, (22, i * 22))
|
2018-12-14 03:55:34 +08:00
|
|
|
self._render = False
|
|
|
|
self.surface.set_alpha(220)
|
|
|
|
|
|
|
|
def toggle(self):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Toggle on or off the render help"""
|
2018-12-14 03:55:34 +08:00
|
|
|
self._render = not self._render
|
|
|
|
|
|
|
|
def render(self, display):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Render help text method"""
|
2018-12-14 03:55:34 +08:00
|
|
|
if self._render:
|
|
|
|
display.blit(self.surface, self.pos)
|
|
|
|
|
|
|
|
# ==============================================================================
|
2018-12-20 03:17:15 +08:00
|
|
|
# -- CollisionSensor -----------------------------------------------------------
|
2018-12-14 03:55:34 +08:00
|
|
|
# ==============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
class CollisionSensor(object):
|
2020-03-17 18:31:05 +08:00
|
|
|
""" Class for collision sensors"""
|
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
def __init__(self, parent_actor, hud):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Constructor method"""
|
2018-12-14 03:55:34 +08:00
|
|
|
self.sensor = None
|
2019-03-14 14:31:40 +08:00
|
|
|
self.history = []
|
2018-12-14 03:55:34 +08:00
|
|
|
self._parent = parent_actor
|
2019-03-14 14:31:40 +08:00
|
|
|
self.hud = hud
|
2018-12-14 03:55:34 +08:00
|
|
|
world = self._parent.get_world()
|
2020-03-17 18:31:05 +08:00
|
|
|
blueprint = world.get_blueprint_library().find('sensor.other.collision')
|
|
|
|
self.sensor = world.spawn_actor(blueprint, carla.Transform(), attach_to=self._parent)
|
|
|
|
# We need to pass the lambda a weak reference to
|
|
|
|
# self to avoid circular reference.
|
2018-12-14 03:55:34 +08:00
|
|
|
weak_self = weakref.ref(self)
|
2018-12-20 03:17:15 +08:00
|
|
|
self.sensor.listen(lambda event: CollisionSensor._on_collision(weak_self, event))
|
|
|
|
|
|
|
|
def get_collision_history(self):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Gets the history of collisions"""
|
2018-12-20 03:17:15 +08:00
|
|
|
history = collections.defaultdict(int)
|
2019-03-14 14:31:40 +08:00
|
|
|
for frame, intensity in self.history:
|
2018-12-20 03:17:15 +08:00
|
|
|
history[frame] += intensity
|
|
|
|
return history
|
2018-12-14 03:55:34 +08:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _on_collision(weak_self, event):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""On collision method"""
|
2018-12-14 03:55:34 +08:00
|
|
|
self = weak_self()
|
|
|
|
if not self:
|
|
|
|
return
|
2018-12-20 03:17:15 +08:00
|
|
|
actor_type = get_actor_display_name(event.other_actor)
|
2019-03-14 14:31:40 +08:00
|
|
|
self.hud.notification('Collision with %r' % actor_type)
|
2018-12-20 03:17:15 +08:00
|
|
|
impulse = event.normal_impulse
|
|
|
|
intensity = math.sqrt(impulse.x ** 2 + impulse.y ** 2 + impulse.z ** 2)
|
2019-06-25 21:50:47 +08:00
|
|
|
self.history.append((event.frame, intensity))
|
2019-03-14 14:31:40 +08:00
|
|
|
if len(self.history) > 4000:
|
|
|
|
self.history.pop(0)
|
2018-12-14 03:55:34 +08:00
|
|
|
|
|
|
|
# ==============================================================================
|
2018-12-20 03:17:15 +08:00
|
|
|
# -- LaneInvasionSensor --------------------------------------------------------
|
2018-12-14 03:55:34 +08:00
|
|
|
# ==============================================================================
|
|
|
|
|
2019-03-14 14:31:40 +08:00
|
|
|
|
2018-12-20 03:17:15 +08:00
|
|
|
class LaneInvasionSensor(object):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Class for lane invasion sensors"""
|
|
|
|
|
2018-12-20 03:17:15 +08:00
|
|
|
def __init__(self, parent_actor, hud):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Constructor method"""
|
2018-12-20 03:17:15 +08:00
|
|
|
self.sensor = None
|
|
|
|
self._parent = parent_actor
|
2019-03-14 14:31:40 +08:00
|
|
|
self.hud = hud
|
2018-12-20 03:17:15 +08:00
|
|
|
world = self._parent.get_world()
|
2019-03-27 16:36:45 +08:00
|
|
|
bp = world.get_blueprint_library().find('sensor.other.lane_invasion')
|
2018-12-20 03:17:15 +08:00
|
|
|
self.sensor = world.spawn_actor(bp, carla.Transform(), attach_to=self._parent)
|
|
|
|
# We need to pass the lambda a weak reference to self to avoid circular
|
|
|
|
# reference.
|
|
|
|
weak_self = weakref.ref(self)
|
|
|
|
self.sensor.listen(lambda event: LaneInvasionSensor._on_invasion(weak_self, event))
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _on_invasion(weak_self, event):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""On invasion method"""
|
2018-12-20 03:17:15 +08:00
|
|
|
self = weak_self()
|
|
|
|
if not self:
|
|
|
|
return
|
2019-03-30 19:27:47 +08:00
|
|
|
lane_types = set(x.type for x in event.crossed_lane_markings)
|
|
|
|
text = ['%r' % str(x).split()[-1] for x in lane_types]
|
2019-03-14 14:31:40 +08:00
|
|
|
self.hud.notification('Crossed line %s' % ' and '.join(text))
|
|
|
|
|
|
|
|
# ==============================================================================
|
|
|
|
# -- GnssSensor --------------------------------------------------------
|
|
|
|
# ==============================================================================
|
2018-12-20 03:17:15 +08:00
|
|
|
|
|
|
|
|
2019-03-14 14:31:40 +08:00
|
|
|
class GnssSensor(object):
|
2020-03-17 18:31:05 +08:00
|
|
|
""" Class for GNSS sensors"""
|
|
|
|
|
2019-03-14 14:31:40 +08:00
|
|
|
def __init__(self, parent_actor):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Constructor method"""
|
2019-03-14 14:31:40 +08:00
|
|
|
self.sensor = None
|
|
|
|
self._parent = parent_actor
|
|
|
|
self.lat = 0.0
|
|
|
|
self.lon = 0.0
|
|
|
|
world = self._parent.get_world()
|
2020-03-17 18:31:05 +08:00
|
|
|
blueprint = world.get_blueprint_library().find('sensor.other.gnss')
|
|
|
|
self.sensor = world.spawn_actor(blueprint, carla.Transform(carla.Location(x=1.0, z=2.8)),
|
2019-03-14 14:31:40 +08:00
|
|
|
attach_to=self._parent)
|
2020-03-17 18:31:05 +08:00
|
|
|
# We need to pass the lambda a weak reference to
|
|
|
|
# self to avoid circular reference.
|
2019-03-14 14:31:40 +08:00
|
|
|
weak_self = weakref.ref(self)
|
|
|
|
self.sensor.listen(lambda event: GnssSensor._on_gnss_event(weak_self, event))
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _on_gnss_event(weak_self, event):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""GNSS method"""
|
2019-03-14 14:31:40 +08:00
|
|
|
self = weak_self()
|
|
|
|
if not self:
|
|
|
|
return
|
|
|
|
self.lat = event.latitude
|
|
|
|
self.lon = event.longitude
|
|
|
|
|
2018-12-20 03:17:15 +08:00
|
|
|
# ==============================================================================
|
|
|
|
# -- CameraManager -------------------------------------------------------------
|
|
|
|
# ==============================================================================
|
2018-12-14 03:55:34 +08:00
|
|
|
|
2019-03-14 14:31:40 +08:00
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
class CameraManager(object):
|
2020-03-17 18:31:05 +08:00
|
|
|
""" Class for camera management"""
|
|
|
|
|
2021-06-21 21:32:49 +08:00
|
|
|
def __init__(self, parent_actor, hud):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Constructor method"""
|
2018-12-14 03:55:34 +08:00
|
|
|
self.sensor = None
|
2019-03-14 14:31:40 +08:00
|
|
|
self.surface = None
|
2018-12-14 03:55:34 +08:00
|
|
|
self._parent = parent_actor
|
2019-03-14 14:31:40 +08:00
|
|
|
self.hud = hud
|
|
|
|
self.recording = False
|
2022-04-20 20:44:27 +08:00
|
|
|
bound_x = 0.5 + self._parent.bounding_box.extent.x
|
2020-03-17 18:31:05 +08:00
|
|
|
bound_y = 0.5 + self._parent.bounding_box.extent.y
|
2022-04-20 20:44:27 +08:00
|
|
|
bound_z = 0.5 + self._parent.bounding_box.extent.z
|
2020-03-17 18:31:05 +08:00
|
|
|
attachment = carla.AttachmentType
|
2018-12-14 03:55:34 +08:00
|
|
|
self._camera_transforms = [
|
2022-09-28 06:46:06 +08:00
|
|
|
(carla.Transform(carla.Location(x=-2.0*bound_x, y=+0.0*bound_y, z=2.0*bound_z), carla.Rotation(pitch=8.0)), attachment.SpringArmGhost),
|
2022-04-20 20:44:27 +08:00
|
|
|
(carla.Transform(carla.Location(x=+0.8*bound_x, y=+0.0*bound_y, z=1.3*bound_z)), attachment.Rigid),
|
2022-09-28 06:46:06 +08:00
|
|
|
(carla.Transform(carla.Location(x=+1.9*bound_x, y=+1.0*bound_y, z=1.2*bound_z)), attachment.SpringArmGhost),
|
|
|
|
(carla.Transform(carla.Location(x=-2.8*bound_x, y=+0.0*bound_y, z=4.6*bound_z), carla.Rotation(pitch=6.0)), attachment.SpringArmGhost),
|
2022-04-20 20:44:27 +08:00
|
|
|
(carla.Transform(carla.Location(x=-1.0, y=-1.0*bound_y, z=0.4*bound_z)), attachment.Rigid)]
|
|
|
|
|
2019-03-14 14:31:40 +08:00
|
|
|
self.transform_index = 1
|
|
|
|
self.sensors = [
|
2018-12-20 03:17:15 +08:00
|
|
|
['sensor.camera.rgb', cc.Raw, 'Camera RGB'],
|
|
|
|
['sensor.camera.depth', cc.Raw, 'Camera Depth (Raw)'],
|
|
|
|
['sensor.camera.depth', cc.Depth, 'Camera Depth (Gray Scale)'],
|
|
|
|
['sensor.camera.depth', cc.LogarithmicDepth, 'Camera Depth (Logarithmic Gray Scale)'],
|
|
|
|
['sensor.camera.semantic_segmentation', cc.Raw, 'Camera Semantic Segmentation (Raw)'],
|
|
|
|
['sensor.camera.semantic_segmentation', cc.CityScapesPalette,
|
|
|
|
'Camera Semantic Segmentation (CityScapes Palette)'],
|
|
|
|
['sensor.lidar.ray_cast', None, 'Lidar (Ray-Cast)']]
|
2018-12-14 03:55:34 +08:00
|
|
|
world = self._parent.get_world()
|
|
|
|
bp_library = world.get_blueprint_library()
|
2019-03-14 14:31:40 +08:00
|
|
|
for item in self.sensors:
|
2020-03-17 18:31:05 +08:00
|
|
|
blp = bp_library.find(item[0])
|
2018-12-14 03:55:34 +08:00
|
|
|
if item[0].startswith('sensor.camera'):
|
2020-03-17 18:31:05 +08:00
|
|
|
blp.set_attribute('image_size_x', str(hud.dim[0]))
|
|
|
|
blp.set_attribute('image_size_y', str(hud.dim[1]))
|
2019-03-14 14:31:40 +08:00
|
|
|
elif item[0].startswith('sensor.lidar'):
|
2020-03-17 18:31:05 +08:00
|
|
|
blp.set_attribute('range', '50')
|
|
|
|
item.append(blp)
|
2019-03-14 14:31:40 +08:00
|
|
|
self.index = None
|
2018-12-20 03:17:15 +08:00
|
|
|
|
|
|
|
def toggle_camera(self):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Activate a camera"""
|
2019-03-14 14:31:40 +08:00
|
|
|
self.transform_index = (self.transform_index + 1) % len(self._camera_transforms)
|
2020-03-17 18:31:05 +08:00
|
|
|
self.set_sensor(self.index, notify=False, force_respawn=True)
|
2018-12-14 03:55:34 +08:00
|
|
|
|
2020-03-17 18:31:05 +08:00
|
|
|
def set_sensor(self, index, notify=True, force_respawn=False):
|
|
|
|
"""Set a sensor"""
|
2019-03-14 14:31:40 +08:00
|
|
|
index = index % len(self.sensors)
|
2020-03-17 18:31:05 +08:00
|
|
|
needs_respawn = True if self.index is None else (
|
|
|
|
force_respawn or (self.sensors[index][0] != self.sensors[self.index][0]))
|
2018-12-14 03:55:34 +08:00
|
|
|
if needs_respawn:
|
|
|
|
if self.sensor is not None:
|
|
|
|
self.sensor.destroy()
|
2019-03-14 14:31:40 +08:00
|
|
|
self.surface = None
|
2018-12-14 03:55:34 +08:00
|
|
|
self.sensor = self._parent.get_world().spawn_actor(
|
2019-03-14 14:31:40 +08:00
|
|
|
self.sensors[index][-1],
|
2020-03-17 18:31:05 +08:00
|
|
|
self._camera_transforms[self.transform_index][0],
|
|
|
|
attach_to=self._parent,
|
|
|
|
attachment_type=self._camera_transforms[self.transform_index][1])
|
|
|
|
|
|
|
|
# We need to pass the lambda a weak reference to
|
|
|
|
# self to avoid circular reference.
|
2018-12-14 03:55:34 +08:00
|
|
|
weak_self = weakref.ref(self)
|
2018-12-20 03:17:15 +08:00
|
|
|
self.sensor.listen(lambda image: CameraManager._parse_image(weak_self, image))
|
2018-12-14 03:55:34 +08:00
|
|
|
if notify:
|
2019-03-14 14:31:40 +08:00
|
|
|
self.hud.notification(self.sensors[index][2])
|
|
|
|
self.index = index
|
2018-12-14 03:55:34 +08:00
|
|
|
|
2018-12-20 03:17:15 +08:00
|
|
|
def next_sensor(self):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Get the next sensor"""
|
2019-03-14 14:31:40 +08:00
|
|
|
self.set_sensor(self.index + 1)
|
2018-12-20 03:17:15 +08:00
|
|
|
|
|
|
|
def toggle_recording(self):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Toggle recording on or off"""
|
2019-03-14 14:31:40 +08:00
|
|
|
self.recording = not self.recording
|
|
|
|
self.hud.notification('Recording %s' % ('On' if self.recording else 'Off'))
|
2018-12-20 03:17:15 +08:00
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
def render(self, display):
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Render method"""
|
2019-03-14 14:31:40 +08:00
|
|
|
if self.surface is not None:
|
|
|
|
display.blit(self.surface, (0, 0))
|
2018-12-14 03:55:34 +08:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _parse_image(weak_self, image):
|
|
|
|
self = weak_self()
|
|
|
|
if not self:
|
|
|
|
return
|
2019-03-14 14:31:40 +08:00
|
|
|
if self.sensors[self.index][0].startswith('sensor.lidar'):
|
2018-12-20 03:17:15 +08:00
|
|
|
points = np.frombuffer(image.raw_data, dtype=np.dtype('f4'))
|
2020-07-07 19:36:42 +08:00
|
|
|
points = np.reshape(points, (int(points.shape[0] / 4), 4))
|
2018-12-20 03:17:15 +08:00
|
|
|
lidar_data = np.array(points[:, :2])
|
2019-03-14 14:31:40 +08:00
|
|
|
lidar_data *= min(self.hud.dim) / 100.0
|
|
|
|
lidar_data += (0.5 * self.hud.dim[0], 0.5 * self.hud.dim[1])
|
2020-03-17 18:31:05 +08:00
|
|
|
lidar_data = np.fabs(lidar_data) # pylint: disable=assignment-from-no-return
|
2018-12-20 03:17:15 +08:00
|
|
|
lidar_data = lidar_data.astype(np.int32)
|
|
|
|
lidar_data = np.reshape(lidar_data, (-1, 2))
|
2019-03-14 14:31:40 +08:00
|
|
|
lidar_img_size = (self.hud.dim[0], self.hud.dim[1], 3)
|
2018-12-20 03:17:15 +08:00
|
|
|
lidar_img = np.zeros(lidar_img_size)
|
|
|
|
lidar_img[tuple(lidar_data.T)] = (255, 255, 255)
|
2019-03-14 14:31:40 +08:00
|
|
|
self.surface = pygame.surfarray.make_surface(lidar_img)
|
2018-12-20 03:17:15 +08:00
|
|
|
else:
|
2019-03-14 14:31:40 +08:00
|
|
|
image.convert(self.sensors[self.index][1])
|
2018-12-20 03:17:15 +08:00
|
|
|
array = np.frombuffer(image.raw_data, dtype=np.dtype("uint8"))
|
|
|
|
array = np.reshape(array, (image.height, image.width, 4))
|
|
|
|
array = array[:, :, :3]
|
|
|
|
array = array[:, :, ::-1]
|
2019-03-14 14:31:40 +08:00
|
|
|
self.surface = pygame.surfarray.make_surface(array.swapaxes(0, 1))
|
|
|
|
if self.recording:
|
2019-06-25 21:50:47 +08:00
|
|
|
image.save_to_disk('_out/%08d' % image.frame)
|
2018-12-14 03:55:34 +08:00
|
|
|
|
|
|
|
# ==============================================================================
|
2020-03-17 18:31:05 +08:00
|
|
|
# -- Game Loop ---------------------------------------------------------
|
2018-12-14 03:55:34 +08:00
|
|
|
# ==============================================================================
|
|
|
|
|
2020-03-17 18:31:05 +08:00
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
def game_loop(args):
|
2021-06-21 21:32:49 +08:00
|
|
|
"""
|
|
|
|
Main loop of the simulation. It handles updating all the HUD information,
|
|
|
|
ticking the agent and, if needed, the world.
|
|
|
|
"""
|
2020-03-17 18:31:05 +08:00
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
pygame.init()
|
|
|
|
pygame.font.init()
|
|
|
|
world = None
|
|
|
|
|
|
|
|
try:
|
2021-06-21 21:32:49 +08:00
|
|
|
if args.seed:
|
|
|
|
random.seed(args.seed)
|
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
client = carla.Client(args.host, args.port)
|
2022-07-02 00:30:56 +08:00
|
|
|
client.set_timeout(60.0)
|
2018-12-14 03:55:34 +08:00
|
|
|
|
2021-06-21 21:32:49 +08:00
|
|
|
traffic_manager = client.get_trafficmanager()
|
|
|
|
sim_world = client.get_world()
|
|
|
|
|
|
|
|
if args.sync:
|
|
|
|
settings = sim_world.get_settings()
|
|
|
|
settings.synchronous_mode = True
|
|
|
|
settings.fixed_delta_seconds = 0.05
|
|
|
|
sim_world.apply_settings(settings)
|
|
|
|
|
|
|
|
traffic_manager.set_synchronous_mode(True)
|
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
display = pygame.display.set_mode(
|
|
|
|
(args.width, args.height),
|
|
|
|
pygame.HWSURFACE | pygame.DOUBLEBUF)
|
|
|
|
|
|
|
|
hud = HUD(args.width, args.height)
|
2020-03-17 18:31:05 +08:00
|
|
|
world = World(client.get_world(), hud, args)
|
2019-12-18 02:40:27 +08:00
|
|
|
controller = KeyboardControl(world)
|
2021-06-19 00:06:25 +08:00
|
|
|
if args.agent == "Basic":
|
2022-04-20 20:44:27 +08:00
|
|
|
agent = BasicAgent(world.player, 30)
|
2022-07-02 00:30:56 +08:00
|
|
|
agent.follow_speed_limits(True)
|
2022-04-20 20:44:27 +08:00
|
|
|
elif args.agent == "Constant":
|
|
|
|
agent = ConstantVelocityAgent(world.player, 30)
|
|
|
|
ground_loc = world.world.ground_projection(world.player.get_location(), 5)
|
|
|
|
if ground_loc:
|
|
|
|
world.player.set_location(ground_loc.location + carla.Location(z=0.01))
|
2022-07-02 00:30:56 +08:00
|
|
|
agent.follow_speed_limits(True)
|
2022-04-20 20:44:27 +08:00
|
|
|
elif args.agent == "Behavior":
|
2020-03-17 18:31:05 +08:00
|
|
|
agent = BehaviorAgent(world.player, behavior=args.behavior)
|
2021-06-21 21:32:49 +08:00
|
|
|
|
|
|
|
# Set the agent destination
|
|
|
|
spawn_points = world.map.get_spawn_points()
|
|
|
|
destination = random.choice(spawn_points).location
|
|
|
|
agent.set_destination(destination)
|
2018-12-14 03:55:34 +08:00
|
|
|
|
2018-12-20 03:17:15 +08:00
|
|
|
clock = pygame.time.Clock()
|
2020-03-17 18:31:05 +08:00
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
while True:
|
2021-06-21 21:32:49 +08:00
|
|
|
clock.tick()
|
|
|
|
if args.sync:
|
|
|
|
world.world.tick()
|
|
|
|
else:
|
|
|
|
world.world.wait_for_tick()
|
2019-12-18 02:40:27 +08:00
|
|
|
if controller.parse_events():
|
2018-12-20 03:17:15 +08:00
|
|
|
return
|
2020-03-17 18:31:05 +08:00
|
|
|
|
2021-06-21 17:07:05 +08:00
|
|
|
world.tick(clock)
|
|
|
|
world.render(display)
|
|
|
|
pygame.display.flip()
|
2020-03-17 18:31:05 +08:00
|
|
|
|
2021-06-21 21:32:49 +08:00
|
|
|
if agent.done():
|
|
|
|
if args.loop:
|
|
|
|
agent.set_destination(random.choice(spawn_points).location)
|
2022-04-20 20:44:27 +08:00
|
|
|
world.hud.notification("Target reached", seconds=4.0)
|
2021-06-21 21:32:49 +08:00
|
|
|
print("The target has been reached, searching for another target")
|
|
|
|
else:
|
|
|
|
print("The target has been reached, stopping the simulation")
|
2020-03-17 18:31:05 +08:00
|
|
|
break
|
|
|
|
|
2021-06-21 17:07:05 +08:00
|
|
|
control = agent.run_step()
|
|
|
|
control.manual_gear_shift = False
|
|
|
|
world.player.apply_control(control)
|
2018-12-14 03:55:34 +08:00
|
|
|
|
|
|
|
finally:
|
2021-06-21 21:32:49 +08:00
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
if world is not None:
|
2021-06-21 21:32:49 +08:00
|
|
|
settings = world.world.get_settings()
|
|
|
|
settings.synchronous_mode = False
|
|
|
|
settings.fixed_delta_seconds = None
|
|
|
|
world.world.apply_settings(settings)
|
|
|
|
traffic_manager.set_synchronous_mode(True)
|
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
world.destroy()
|
|
|
|
|
|
|
|
pygame.quit()
|
|
|
|
|
|
|
|
|
|
|
|
# ==============================================================================
|
|
|
|
# -- main() --------------------------------------------------------------
|
|
|
|
# ==============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
2020-03-17 18:31:05 +08:00
|
|
|
"""Main method"""
|
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
argparser = argparse.ArgumentParser(
|
2020-03-17 18:31:05 +08:00
|
|
|
description='CARLA Automatic Control Client')
|
2018-12-14 03:55:34 +08:00
|
|
|
argparser.add_argument(
|
|
|
|
'-v', '--verbose',
|
|
|
|
action='store_true',
|
|
|
|
dest='debug',
|
2020-03-17 18:31:05 +08:00
|
|
|
help='Print debug information')
|
2018-12-14 03:55:34 +08:00
|
|
|
argparser.add_argument(
|
|
|
|
'--host',
|
|
|
|
metavar='H',
|
|
|
|
default='127.0.0.1',
|
|
|
|
help='IP of the host server (default: 127.0.0.1)')
|
|
|
|
argparser.add_argument(
|
|
|
|
'-p', '--port',
|
|
|
|
metavar='P',
|
|
|
|
default=2000,
|
|
|
|
type=int,
|
|
|
|
help='TCP port to listen to (default: 2000)')
|
|
|
|
argparser.add_argument(
|
|
|
|
'--res',
|
|
|
|
metavar='WIDTHxHEIGHT',
|
|
|
|
default='1280x720',
|
2020-03-17 18:31:05 +08:00
|
|
|
help='Window resolution (default: 1280x720)')
|
2021-06-21 21:32:49 +08:00
|
|
|
argparser.add_argument(
|
|
|
|
'--sync',
|
|
|
|
action='store_true',
|
|
|
|
help='Synchronous mode execution')
|
2019-03-14 14:31:40 +08:00
|
|
|
argparser.add_argument(
|
|
|
|
'--filter',
|
|
|
|
metavar='PATTERN',
|
|
|
|
default='vehicle.*',
|
2020-03-17 18:31:05 +08:00
|
|
|
help='Actor filter (default: "vehicle.*")')
|
2022-04-20 20:44:27 +08:00
|
|
|
argparser.add_argument(
|
|
|
|
'--generation',
|
|
|
|
metavar='G',
|
|
|
|
default='2',
|
|
|
|
help='restrict to certain actor generation (values: "1","2","All" - default: "2")')
|
2020-03-17 18:31:05 +08:00
|
|
|
argparser.add_argument(
|
|
|
|
'-l', '--loop',
|
|
|
|
action='store_true',
|
|
|
|
dest='loop',
|
|
|
|
help='Sets a new random destination upon reaching the previous one (default: False)')
|
2021-06-21 21:32:49 +08:00
|
|
|
argparser.add_argument(
|
|
|
|
"-a", "--agent", type=str,
|
2022-04-20 20:44:27 +08:00
|
|
|
choices=["Behavior", "Basic", "Constant"],
|
2021-06-21 21:32:49 +08:00
|
|
|
help="select which agent to run",
|
|
|
|
default="Behavior")
|
2020-03-17 18:31:05 +08:00
|
|
|
argparser.add_argument(
|
|
|
|
'-b', '--behavior', type=str,
|
|
|
|
choices=["cautious", "normal", "aggressive"],
|
|
|
|
help='Choose one of the possible agent behaviors (default: normal) ',
|
|
|
|
default='normal')
|
|
|
|
argparser.add_argument(
|
|
|
|
'-s', '--seed',
|
|
|
|
help='Set seed for repeating executions (default: None)',
|
|
|
|
default=None,
|
|
|
|
type=int)
|
|
|
|
|
2018-12-14 03:55:34 +08:00
|
|
|
args = argparser.parse_args()
|
|
|
|
|
|
|
|
args.width, args.height = [int(x) for x in args.res.split('x')]
|
|
|
|
|
|
|
|
log_level = logging.DEBUG if args.debug else logging.INFO
|
|
|
|
logging.basicConfig(format='%(levelname)s: %(message)s', level=log_level)
|
|
|
|
|
|
|
|
logging.info('listening to server %s:%s', args.host, args.port)
|
|
|
|
|
|
|
|
print(__doc__)
|
|
|
|
|
|
|
|
try:
|
|
|
|
game_loop(args)
|
|
|
|
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
print('\nCancelled by user. Bye!')
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|