Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def __init__(self, actor, target_location, name="BasicAgentBehavior"):
"""
Setup actor and maximum steer value
"""
super(BasicAgentBehavior, self).__init__(name, actor)
self.logger.debug("%s.__init__()" % (self.__class__.__name__))
self._agent = BasicAgent(actor) # pylint: disable=undefined-variable
self._agent.set_destination((target_location.x, target_location.y, target_location.z))
self._control = carla.VehicleControl()
self._target_location = target_location
vehicles = world.world.get_actors().filter('vehicle.*')
self._info_text = [
'Server: % 16d FPS' % self.server_fps,
'Client: % 16d FPS' % clock.get_fps(),
'',
'Vehicle: % 20s' % get_actor_display_name(world.player, truncate=20),
'Map: % 20s' % world.world.map_name,
'Simulation time: % 12s' % datetime.timedelta(seconds=int(self.simulation_time)),
'',
'Speed: % 15.0f km/h' % (3.6 * math.sqrt(v.x**2 + v.y**2 + v.z**2)),
u'Heading:% 16.0f\N{DEGREE SIGN} % 2s' % (t.rotation.yaw, heading),
'Location:% 20s' % ('(% 5.1f, % 5.1f)' % (t.location.x, t.location.y)),
'GNSS:% 24s' % ('(% 2.6f, % 3.6f)' % (world.gnss_sensor.lat, world.gnss_sensor.lon)),
'Height: % 18.0f m' % t.location.z,
'']
if isinstance(c, carla.VehicleControl):
self._info_text += [
('Throttle:', c.throttle, 0.0, 1.0),
('Steer:', c.steer, -1.0, 1.0),
('Brake:', c.brake, 0.0, 1.0),
('Reverse:', c.reverse),
('Hand brake:', c.hand_brake),
('Manual:', c.manual_gear_shift),
'Gear: %s' % {-1: 'R', 0: 'N'}.get(c.gear, c.gear)]
elif isinstance(c, carla.WalkerControl):
self._info_text += [
('Speed:', c.speed, 0.0, 5.556),
('Jump:', c.jump)]
self._info_text += [
'',
'Collision:',
collision,
def run_step(self, input_data, timestamp):
"""
Execute one step of navigation.
"""
control = carla.VehicleControl()
control.steer = 0.0
control.throttle = 0.0
control.brake = 0.0
control.hand_brake = False
if not self._agent:
hero_actor = None
for actor in CarlaDataProvider.get_world().get_actors():
if 'role_name' in actor.attributes and actor.attributes['role_name'] == 'hero':
hero_actor = actor
break
if hero_actor:
self._agent = BasicAgent(hero_actor)
return control
def getAction(self,actionID=4,steer=0, throttle=0):
if self.model == 'dqn':
throttleID = int(actionID / self.sStateNum)
steerID = int(actionID % self.sStateNum)
self.control = carla.VehicleControl(
throttle = self.step_T_pool[throttleID],
steer = self.step_S_pool[steerID],
brake = 0.0,
hand_brake = False,
reverse = False,
manual_gear_shift = False,
gear = 0)
else:
self.control = carla.VehicleControl(
throttle = throttle,
steer = steer,
brake = 0.0,
hand_brake = False,
reverse = False,
manual_gear_shift = False,
gear = 0)
return self.control
def parse_input(self, clock):
self._parse_events()
self._parse_mouse()
if not self._autopilot_enabled:
if isinstance(self.control, carla.VehicleControl):
self._parse_keys(clock.get_time())
self.control.reverse = self.control.gear < 0
if (self._world.hero_actor is not None):
self._world.hero_actor.apply_control(self.control)
center_offset = (int(self.module_hud.dim[0] / 2), int(self.module_hud.dim[1] / 2))
pygame.draw.circle(self.border_round_surface, COLOR_ALUMINIUM_1, center_offset, int(self.module_hud.dim[1] / 2))
pygame.draw.circle(self.border_round_surface, COLOR_WHITE, center_offset, int((self.module_hud.dim[1] - 8) / 2))
scaled_original_size = self.original_surface_size * (1.0 / 0.9)
self.hero_surface = pygame.Surface((scaled_original_size, scaled_original_size)).convert()
self.result_surface = pygame.Surface((self.surface_size, self.surface_size)).convert()
self.result_surface.set_colorkey(COLOR_BLACK)
# Start hero mode by default
self.select_hero_actor()
self.hero_actor.set_autopilot(False)
self.module_input.wheel_offset = HERO_DEFAULT_SCALE
self.module_input.control = carla.VehicleControl()
weak_self = weakref.ref(self)
self.world.on_tick(lambda timestamp: ModuleWorld.on_world_tick(weak_self, timestamp))
else:
# TODO build a better decision tree for the action
if(len(self._action.tags) == 1 and self._action.semanticTags["longitudinal"] in self._action.tags):
# set speed
if(self._action.longitudinal_dynamics_shape == "step"):
self._desiredSpeed = self._action.longitudinal_speed
else:
print("[WARNING][CarlaActor::handleEgo] Implementation Missing for longitudinal action!")
else:
print("[WARNING][CarlaActor::handleEgo] Implementation Missing. Unable to handle new action type")
self._action = None
# send data to carla
# TODO fix PID controller and reimplement vehicle control
carla_vehicle_control = carla.VehicleControl(cur_control["throttle"],
cur_control["steer"],
cur_control["brake"],
cur_control["hand_brake"],
cur_control["reverse"])
self.__carlaActor.apply_control(carla_vehicle_control)
# (egoPose, egoSpeed) = self._egoControlPathWorkaround()
# if egoPose is not None:
# # mind ros to carla corrections (-y, -roll, -yaw)
# transform = carla.Transform(carla.Location( egoPose.getPosition()[0],
# -egoPose.getPosition()[1],
# egoPose.getPosition()[2]),
# carla.Rotation( math.degrees(egoPose.getOrientation()[1]),
# math.degrees(-egoPose.getOrientation()[2]),
# math.degrees(-egoPose.getOrientation()[0])))
# print("--- --- ---")
start_rotation = carla.Rotation()
self.start_point = carla.Transform(location = start_location, rotation = start_rotation) # type : Transform (location, rotation)
self.client = carla.Client('127.0.0.1', 2000)
self.client.set_timeout(4.0)
self.display = pygame.display.set_mode((1280, 720),pygame.HWSURFACE | pygame.DOUBLEBUF)
self.hud = HUD(1280, 720)
self.world = World(self.client.get_world(), self.hud, 'vehicle.*', self.start_point, vehicleNum)
self.clock = pygame.time.Clock()
self.minDis = 0
self.collectFlag = collectFlag
self.traj_drawn_list = []
self.control = carla.VehicleControl(
throttle = 1,
steer = 0.0,
brake = 0.0,
hand_brake = False,
reverse = False,
manual_gear_shift = False,
gear = 0)
self.destinationFlag = False
self.away = False
self.collisionFlag = False
self.waypoints_ahead = []
self.waypoints_neighbor = []
self.steer_history = deque(maxlen=20)
self.throttle_history = deque(maxlen=20)
self.velocity_local = []
def reset(self):
self.data_frame_dict = dict()
self.data_frame_number_ = None
self.progress_index = 0
self.data_frame_buffer = set()
if self.camera_sensor_dict is not None:
for keyword in self.camera_sensor_dict.keys():
self.camera_sensor_dict[keyword].image_frame_number = None
self.camera_sensor_dict[keyword].image_frame = None
if self.segment_sensor_dict is not None:
for keyword in self.segment_sensor_dict.keys():
self.segment_sensor_dict[keyword].image_frame_number = None
self.segment_sensor_dict[keyword].image_frame = None
control = carla.VehicleControl()
control.steer = 0.0
control.throttle = 0.0
control.brake = 1.0
self.vehicle.apply_control(control)
def run_step(self, input_data, timestamp):
# Get the current directions for following the route
directions = self._get_current_direction(input_data['GPS'][1])
logging.debug("Directions {}".format(directions))
# Take the forward speed and normalize it for it to go from 0-1
norm_speed = input_data['can_bus'][1]['speed'] / g_conf.SPEED_FACTOR
norm_speed = torch.cuda.FloatTensor([norm_speed]).unsqueeze(0)
directions_tensor = torch.cuda.LongTensor([directions])
# Compute the forward pass processing the sensors got from CARLA.
model_outputs = self._model.forward_branch(self._process_sensors(input_data['rgb'][1]),
norm_speed,
directions_tensor)
steer, throttle, brake = self._process_model_outputs(model_outputs[0])
control = carla.VehicleControl()
control.steer = float(steer)
control.throttle = float(throttle)
control.brake = float(brake)
logging.debug("Output ", control)
# There is the posibility to replace some of the predictions with oracle predictions.
self.first_iter = False
return control