Пример #1
0
def main():
    client = carla.Client('127.0.0.1', 2000)
    client.set_timeout(10.0)

    # Read the opendrive file to a string
    xodr_path = "speedway_5lanes.xodr"
    #xodr_path = "Crossing8Course.xodr"
    od_file = open(xodr_path)
    data = od_file.read()

    # Load the opendrive map
    vertex_distance = 2.0  # in meters
    max_road_length = 50.0  # in meters
    wall_height = 1.0  # in meters
    extra_width = 0.6  # in meters
    world = client.generate_opendrive_world(
        data,
        carla.OpendriveGenerationParameters(vertex_distance=vertex_distance,
                                            max_road_length=max_road_length,
                                            wall_height=wall_height,
                                            additional_width=extra_width,
                                            smooth_junctions=True,
                                            enable_mesh_visibility=True))

    spectator = world.get_spectator()

    blueprint = world.get_blueprint_library().filter('vehicle.*model3*')[0]
    waypoints = world.get_map().generate_waypoints(2.0)

    targetLane = -3
    waypoint = waypoints[0]
    waypoint = change_lane(waypoint, targetLane - waypoint.lane_id)

    location = waypoint.transform.location + carla.Vector3D(0, 0, 1.5)
    rotation = waypoint.transform.rotation

    print(location)
    print(rotation)

    vehicle = world.spawn_actor(blueprint, carla.Transform(location, rotation))
    actor_list.append(
        vehicle)  #Add actor to list in order to destroy when program completes

    vehicle.set_simulate_physics(False)
    physics_control = vehicle.get_physics_control()
    max_steer = physics_control.wheels[0].max_steer_angle
    rear_axle_center = (physics_control.wheels[2].position +
                        physics_control.wheels[3].position) / 200
    offset = rear_axle_center - vehicle.get_location()
    wheelbase = np.linalg.norm([offset.x, offset.y, offset.z])
    vehicle.set_simulate_physics(True)

    locations = first_lap(world, vehicle, targetLane, max_steer, wheelbase,
                          spectator)
    print(locations)
Пример #2
0
def main():
    global world
    global vehicle_list
    # global lock

    client = carla.Client('127.0.0.1', 2000)
    client.set_timeout(10.0)
    # Read the opendrive file to a string
    xodr_path = "speedway_5lanes.xodr"
    #xodr_path = "Crossing8Course.xodr"
    od_file = open(xodr_path)
    data = od_file.read()

    # Load the opendrive map
    vertex_distance = 2.0  # in meters
    max_road_length = 10.0 # in meters #Changed from 50.0 
    wall_height = 5.0      # in meters
    extra_width = 0.6      # in meters
    world = client.generate_opendrive_world(
        data, carla.OpendriveGenerationParameters(
        vertex_distance=vertex_distance,
        max_road_length=max_road_length,
        wall_height=wall_height,
        additional_width=extra_width,
        smooth_junctions=True,
        enable_mesh_visibility=True))
    
    # world = client.get_world()
    settings = world.get_settings()
    settings.synchronous_mode = True  # Enables synchronous mode
    settings.fixed_delta_seconds = 0.1  # simulation time between two frames
    world.apply_settings(settings)

    tick_rate = 10.0  # number of ticks per second, assuming tick() runs in zero time


    transform = waypoints = world.get_map().generate_waypoints(10.0)
    #Change targetLane and waypoint index depending on where you want the vehicle to spawn
    targetLane = -3 
    waypoint = waypoints[500] 
    waypoint = change_lane(waypoint, targetLane - waypoint.lane_id)
    location = waypoint.transform.location + carla.Vector3D(0, 0, 0.5)
    rotation = waypoint.transform.rotation
    transform = carla.Transform(location, rotation)

    vehicle_1 = Autonomous_Vehicle(['lidar', 'collision', 'camera'], transform, Disparity_Extender(), Pure_Pursuit_Controller())
    vehicle_list.append(vehicle_1)

    world.on_tick(lambda world_snapshot: vehicle_1.control_loop())

    while True:
        time.sleep(1/tick_rate)
        world.tick()
Пример #3
0
def main():
    global target_cartesian
    global lock

    client = carla.Client('127.0.0.1', 2000)
    client.set_timeout(10.0)

    # Read the opendrive file to a string
    xodr_path = "speedway_5lanes.xodr"
    #xodr_path = "Crossing8Course.xodr"
    od_file = open(xodr_path)
    data = od_file.read()

    # Load the opendrive map
    vertex_distance = 2.0  # in meters
    max_road_length = 10.0  # in meters #Changed from 50.0
    wall_height = 5.0  # in meters
    extra_width = 0.6  # in meters
    world = client.generate_opendrive_world(
        data,
        carla.OpendriveGenerationParameters(vertex_distance=vertex_distance,
                                            max_road_length=max_road_length,
                                            wall_height=wall_height,
                                            additional_width=extra_width,
                                            smooth_junctions=True,
                                            enable_mesh_visibility=True))

    spectator = world.get_spectator()

    vehicle, camera, controller = spawn_actor(world)

    if (target_cartesian is not None):  #wait until first Lidar scan
        while True:
            print(target_cartesian)
            time.sleep(1)
            #When all actors have been spawned
            vehicle_transform = vehicle.get_transform()
            speed = math.sqrt(vehicle.get_velocity().x**2 +
                              vehicle.get_velocity().y**2)
            throttle = controller.throttle_control(speed)

            #print("target polar: " + str(target_cartesian))

            steer = controller.cartesian_steering_control(target_cartesian)
            #steer = 0
            print("steer: " + str(steer))
            control = carla.VehicleControl(throttle, steer)
            spectator.set_transform(camera.get_transform())
            vehicle.apply_control(control)
Пример #4
0
def main():
    client = carla.Client('127.0.0.1', 2000)
    client.set_timeout(10.0)

    # Read the opendrive file to a string
    xodr_path = "speedway_5lanes.xodr"
    #xodr_path = "Crossing8Course.xodr"
    od_file = open(xodr_path)
    data = od_file.read()

    # Load the opendrive map
    vertex_distance = 2.0  # in meters
    max_road_length = 10.0  # in meters #Changed from 50.0
    wall_height = 5.0  # in meters
    extra_width = 0.6  # in meters
    world = client.generate_opendrive_world(
        data,
        carla.OpendriveGenerationParameters(vertex_distance=vertex_distance,
                                            max_road_length=max_road_length,
                                            wall_height=wall_height,
                                            additional_width=extra_width,
                                            smooth_junctions=True,
                                            enable_mesh_visibility=True))

    settings = world.get_settings()
    settings.synchronous_mode = True  # Enables synchronous mode
    settings.fixed_delta_seconds = None  # Set a variable time
    world.apply_settings(settings)

    world_snapshot = world.wait_for_tick()
    world.on_tick(lambda world_snapshot: do_something(world_snapshot))

    spectator = world.get_spectator()

    spawn_actor(world)

    while True:
        world.tick()
        #When all actors have been spawned
        if (len(actor_list) >= 4):
            control_vehicle(actor_list[0])
            camera = actor_list[1]
            spectator.set_transform(camera.get_transform())
        world.wait_for_tick()
Пример #5
0
def main():
    client = carla.Client('127.0.0.1', 2000)
    client.set_timeout(10.0)

    # Read the opendrive file to a string
    xodr_path = "speedway_5lanes.xodr"
    #xodr_path = "Crossing8Course.xodr"
    od_file = open(xodr_path)
    data = od_file.read()

    # Load the opendrive map
    vertex_distance = 2.0  # in meters
    max_road_length = 10.0  # in meters #Changed from 50.0
    wall_height = 5.0  # in meters
    extra_width = 0.6  # in meters
    world = client.generate_opendrive_world(
        data,
        carla.OpendriveGenerationParameters(vertex_distance=vertex_distance,
                                            max_road_length=max_road_length,
                                            wall_height=wall_height,
                                            additional_width=extra_width,
                                            smooth_junctions=True,
                                            enable_mesh_visibility=True))

    spectator = world.get_spectator()

    spawn_actor(world)

    while True:
        print(actor_list)
        #When all actors have been spawned
        if (len(actor_list) >= 4):
            print("true")
            control_vehicle(actor_list[0])
            camera = actor_list[1]
            spectator.set_transform(camera.get_transform())
        timestamp = world.wait_for_tick()
        delta_seconds = timestamp.delta_seconds
        time.sleep(delta_seconds)
        print("update")
Пример #6
0
def load_opendrive_world(client):
    # Read the opendrive file to a string
    xodr_path = "speedway_5lanes.xodr"
    od_file = open(xodr_path)
    data = od_file.read()
    # Load the opendrive map
    vertex_distance = 2.0  # in meters
    max_road_length = 10.0  # in meters #Changed from 50.0
    wall_height = 5.0      # in meters
    extra_width = 0.6      # in meters
    world = client.generate_opendrive_world(
        data, carla.OpendriveGenerationParameters(
            vertex_distance=vertex_distance,
            max_road_length=max_road_length,
            wall_height=wall_height,
            additional_width=extra_width,
            smooth_junctions=True,
            enable_mesh_visibility=True))
    settings = world.get_settings()
    settings.synchronous_mode = True  # Enables synchronous mode
    settings.fixed_delta_seconds = 0.05  # simulation time between two frames
    world.apply_settings(settings)
    return world
Пример #7
0
def main():
    argparser = argparse.ArgumentParser(description=__doc__)
    argparser.add_argument(
        '--host',
        metavar='H',
        default='localhost',
        help='IP of the host CARLA Simulator (default: localhost)')
    argparser.add_argument('-p',
                           '--port',
                           metavar='P',
                           default=2000,
                           type=int,
                           help='TCP port of CARLA Simulator (default: 2000)')
    argparser.add_argument('-d',
                           '--default',
                           action='store_true',
                           help='set default settings')
    argparser.add_argument(
        '-m', '--map', help='load a new map, use --list to see available maps')
    argparser.add_argument('-r',
                           '--reload-map',
                           action='store_true',
                           help='reload current map')
    argparser.add_argument(
        '--delta-seconds',
        metavar='S',
        type=float,
        help='set fixed delta seconds, zero for variable frame rate')
    argparser.add_argument(
        '--fps',
        metavar='N',
        type=float,
        help='set fixed FPS, zero for variable FPS (similar to --delta-seconds)'
    )
    argparser.add_argument('--rendering',
                           action='store_true',
                           help='enable rendering')
    argparser.add_argument('--no-rendering',
                           action='store_true',
                           help='disable rendering')
    argparser.add_argument('--no-sync',
                           action='store_true',
                           help='disable synchronous mode')
    argparser.add_argument(
        '--weather',
        help='set weather preset, use --list to see available presets')
    argparser.add_argument('-i',
                           '--inspect',
                           action='store_true',
                           help='inspect simulation')
    argparser.add_argument('-l',
                           '--list',
                           action='store_true',
                           help='list available options')
    argparser.add_argument(
        '-b',
        '--list-blueprints',
        metavar='FILTER',
        help=
        'list available blueprints matching FILTER (use \'*\' to list them all)'
    )
    argparser.add_argument(
        '-x',
        '--xodr-path',
        metavar='XODR_FILE_PATH',
        help=
        'load a new map with a minimum physical road representation of the provided OpenDRIVE'
    )

    if len(sys.argv) < 2:
        argparser.print_help()
        return

    args = argparser.parse_args()

    client = carla.Client(args.host, args.port, worker_threads=1)
    client.set_timeout(10.0)

    print(client.get_available_maps())

    if args.map is not None:
        print('load map %r.' % args.map)
        world = client.load_world(args.map)
    elif args.reload_map:
        print('reload map.')
        world = client.reload_world()
    elif args.xodr_path is not None:
        if os.path.exists(args.xodr_path):
            with open(args.xodr_path) as od_file:
                try:
                    data = od_file.read()
                except OSError:
                    print('file could not be readed.')
                    sys.exit()
            print('load opendrive map %r.' % os.path.basename(args.xodr_path))
            vertex_distance = 2.0  # in meters
            max_road_length = 500.0  # in meters
            wall_height = 1.0  # in meters
            extra_width = 0.6  # in meters
            world = client.generate_opendrive_world(
                data,
                carla.OpendriveGenerationParameters(
                    vertex_distance=vertex_distance,
                    max_road_length=max_road_length,
                    wall_height=wall_height,
                    additional_width=extra_width,
                    smooth_junctions=True,
                    enable_mesh_visibility=True))
        else:
            print('file not found.')

    else:
        world = client.get_world()

    settings = world.get_settings()

    if args.no_rendering:
        print('disable rendering.')
        settings.no_rendering_mode = True
    elif args.rendering:
        print('enable rendering.')
        settings.no_rendering_mode = False

    if args.no_sync:
        print('disable synchronous mode.')
        settings.synchronous_mode = False

    if args.delta_seconds is not None:
        settings.fixed_delta_seconds = args.delta_seconds
    elif args.fps is not None:
        settings.fixed_delta_seconds = (1.0 /
                                        args.fps) if args.fps > 0.0 else 0.0

    if args.delta_seconds is not None or args.fps is not None:
        if settings.fixed_delta_seconds > 0.0:
            print('set fixed frame rate %.2f milliseconds (%d FPS)' %
                  (1000.0 * settings.fixed_delta_seconds,
                   1.0 / settings.fixed_delta_seconds))
        else:
            print('set variable frame rate.')
            settings.fixed_delta_seconds = None

    world.apply_settings(settings)

    if args.weather is not None:
        if not hasattr(carla.WeatherParameters, args.weather):
            print('ERROR: weather preset %r not found.' % args.weather)
        else:
            print('set weather preset %r.' % args.weather)
            world.set_weather(getattr(carla.WeatherParameters, args.weather))

    if args.inspect:
        inspect(args, client)
    if args.list:
        list_options(client)
    if args.list_blueprints:
        list_blueprints(world, args.list_blueprints)
Пример #8
0
def main():
    client = carla.Client('127.0.0.1', 2000)
    client.set_timeout(10.0)

    # Read the opendrive file to a string
    xodr_path = "speedway_5lanes.xodr"
    #xodr_path = "Crossing8Course.xodr"
    od_file = open(xodr_path)
    data = od_file.read()

    # Load the opendrive map
    vertex_distance = 2.0  # in meters
    max_road_length = 50.0  # in meters
    wall_height = 5.0  # in meters
    extra_width = 0.6  # in meters
    world = client.generate_opendrive_world(
        data,
        carla.OpendriveGenerationParameters(vertex_distance=vertex_distance,
                                            max_road_length=max_road_length,
                                            wall_height=wall_height,
                                            additional_width=extra_width,
                                            smooth_junctions=True,
                                            enable_mesh_visibility=True))

    spectator = world.get_spectator()

    blueprint = world.get_blueprint_library().filter('vehicle.*model3*')[0]
    waypoints = world.get_map().generate_waypoints(2.0)

    targetLane = -3
    waypoint = waypoints[0]
    waypoint = change_lane(waypoint, targetLane - waypoint.lane_id)

    location = waypoint.transform.location + carla.Vector3D(0, 0, 1.5)
    rotation = waypoint.transform.rotation

    print(location)
    print(rotation)

    vehicle = world.spawn_actor(blueprint, carla.Transform(location, rotation))
    actor_list.append(
        vehicle)  #Add actor to list in order to destroy when program completes
    vehicle.set_simulate_physics(False)
    physics_control = vehicle.get_physics_control()
    max_steer = physics_control.wheels[0].max_steer_angle
    rear_axle_center = (physics_control.wheels[2].position +
                        physics_control.wheels[3].position) / 200
    offset = rear_axle_center - vehicle.get_location()
    wheelbase = np.linalg.norm([offset.x, offset.y, offset.z])
    vehicle.set_simulate_physics(True)

    transform = carla.Transform(carla.Location(x=0.8, z=1.7))

    #Configure collision sensor
    collision_bp = world.get_blueprint_library().find('sensor.other.collision')
    collision_sensor = world.spawn_actor(collision_bp,
                                         transform,
                                         attach_to=vehicle)
    actor_list.append(collision_sensor)

    #configure LIDAR sensor to only output 2d
    # Find the blueprint of the sensor.
    lidar_bp = world.get_blueprint_library().find('sensor.lidar.ray_cast')
    # Set the time in seconds between sensor captures
    lidar_bp.set_attribute('sensor_tick', '0.1')
    lidar_bp.set_attribute('channels', '1')
    lidar_bp.set_attribute('upper_fov', '0')
    #lidar_bp.set_attribute('lower_fov', '0')
    lidar_bp.set_attribute('range', '10')  #10 is default

    lidar_bp.set_attribute('points_per_second', '500')
    #With 2 channels, and 100 points per second, here are 250 points per scan

    lidar_sensor = world.spawn_actor(lidar_bp, transform, attach_to=vehicle)
    actor_list.append(lidar_sensor)
    lidar_sensor.listen(lambda data: save_lidar_image(data, world, vehicle))

    throttle = 0.85
    control = carla.VehicleControl(throttle, 0)
    vehicle.apply_control(control)

    while True:
        spectator.set_transform(get_transform(vehicle.get_location(), 145))
Пример #9
0
def main():
    global first_quarter_time, second_quarter_time, third_quarter_time, fourth_quarter_time
    global actor_list

    ##Modifiable Variables
    targetLane = -3

    client = carla.Client('127.0.0.1', 2000)
    client.set_timeout(10.0)

    # Read the opendrive file to a string
    xodr_path = "speedway_5lanes.xodr"
    #xodr_path = "Crossing8Course.xodr"
    od_file = open(xodr_path)
    data = od_file.read()

    # Load the opendrive map
    vertex_distance = 2.0  # in meters
    max_road_length = 50.0  # in meters
    wall_height = 1.0  # in meters
    extra_width = 0.6  # in meters
    world = client.generate_opendrive_world(
        data,
        carla.OpendriveGenerationParameters(vertex_distance=vertex_distance,
                                            max_road_length=max_road_length,
                                            wall_height=wall_height,
                                            additional_width=extra_width,
                                            smooth_junctions=True,
                                            enable_mesh_visibility=True))

    spectator = world.get_spectator()

    map = world.get_map()
    waypoint_list = map.generate_waypoints(40)

    print("Length: " + str(len(waypoint_list)))

    #Take only the waypoints from the targetLane
    waypoints = single_lane(waypoint_list, targetLane)

    #Remove all unneccesary waypoints along the straights
    curvy_waypoints = get_curvy_waypoints(waypoints)

    modify_waypoints(curvy_waypoints)

    #Save graph of plotted points as bezier.png
    x = [-p.transform.location.x for p in curvy_waypoints]
    y = [p.transform.location.y for p in curvy_waypoints]
    plt.plot(x, y, marker='o')

    i = 5  #initial point

    #Set spawning location as initial waypoint
    spawnpoint = curvy_waypoints[i]
    blueprint = world.get_blueprint_library().filter('vehicle.*model3*')[0]
    location = spawnpoint.transform.location + carla.Vector3D(0, 0, 1.5)
    rotation = spawnpoint.transform.rotation

    print("location: " + str(location))
    print("rotation: " + str(rotation))
    vehicle = world.spawn_actor(blueprint, carla.Transform(location, rotation))
    actor_list.append(vehicle)
    print("spawn location: " + str(vehicle.get_transform().location))
    print("spawn rotation: " + str(vehicle.get_transform().rotation))

    print(world.get_actor(vehicle.id).get_transform())

    print("SPAWNED!")
    #plt.plot(-vehicle.get_location().x, vehicle.get_location().y, marker = 'o', color = 'r')

    num = 8

    plt.axis([-1400, 400, -750, 50])
    plt.savefig("new_bezier.png")

    #Vehicle properties setup
    physics_control = vehicle.get_physics_control()
    max_steer = physics_control.wheels[0].max_steer_angle
    rear_axle_center = (physics_control.wheels[2].position +
                        physics_control.wheels[3].position) / 200
    offset = rear_axle_center - vehicle.get_location()
    wheelbase = np.linalg.norm([offset.x, offset.y, offset.z])
    vehicle.set_simulate_physics(True)

    #Add spectator camera to get the view to move with the car
    camera_bp = world.get_blueprint_library().find('sensor.camera.rgb')
    camera_transform = carla.Transform(carla.Location(x=-10, z=10),
                                       carla.Rotation(-30, 0, 0))
    camera = world.spawn_actor(camera_bp, camera_transform, attach_to=vehicle)
    actor_list.append(camera)

    transform = carla.Transform(carla.Location(x=0.8, z=1.7))

    ##INSERT MODIFYING WAYPOINTS HERE
    array = []
    for p in curvy_waypoints:
        x = '{0:.10f}'.format(float(p.transform.location.x))
        y = '{0:.10f}'.format(float(p.transform.location.y))

        array.append([x, y])
    np.savetxt("waypoints.csv", array)

    max_x = -10000
    max_y = -10000
    min_x = 10000
    min_y = 10000
    for waypoint in curvy_waypoints:
        if waypoint.transform.location.x < min_x:
            min_x = waypoint.transform.location.x
        if waypoint.transform.location.x > max_x:
            max_x = waypoint.transform.location.x
        if waypoint.transform.location.y < min_y:
            min_y = waypoint.transform.location.y
        if waypoint.transform.location.y > max_y:
            max_y = waypoint.transform.location.y

    mid_x = (max_x + min_x) / 2
    mid_y = (max_y + min_y) / 2

    print("mid_x, mid_y " + str(mid_x) + "  " + str(mid_y))

    start_time = time.clock()
    section = 1

    while True:

        loc = vehicle.get_location()
        #print(loc)

        if section == 1:
            if loc.y < mid_y:
                first_quarter_time = time.clock() - start_time
                section = 2
                start_time = time.clock()
                print("first time: " + str(first_quarter_time))
                continue
        if section == 2:
            if loc.x < mid_x:
                second_quarter_time = time.clock() - start_time
                section = 3
                start_time = time.clock()
        if section == 3:
            if loc.y > mid_y:
                third_quarter_time = time.clock() - start_time
                section = 4
                start_time = time.clock()
                continue
        if section == 4:
            if loc.x > mid_x:
                fourth_quarter_time = time.clock() - start_time
                section = 1
                start_time = time.clock()
                continue

        #Update the camera view
        spectator.set_transform(camera.get_transform())

        #Get next waypoint
        waypoint = curvy_waypoints[i]
        if (vehicle.get_location().distance(
                curvy_waypoints[i].transform.location) < 20):
            i = i + 1
        world.debug.draw_point(waypoint.transform.location, life_time=5)

        #Control vehicle's throttle and steering
        throttle = 0.5
        vehicle_transform = vehicle.get_transform()
        vehicle_location = vehicle_transform.location
        steer = control_pure_pursuit(vehicle_transform, waypoint.transform,
                                     max_steer, wheelbase, world)
        control = carla.VehicleControl(throttle, steer)
        vehicle.apply_control(control)
        #print("steer: " + str(steer))

        time.sleep(0.1)
Пример #10
0
def main():
    global df
    global actor_list

    ### CONSTANTS ###

    target_lane = -3    #Center lane is -3

    target_speed = 30   #Target speed of vehicle

    i = 0               # Starting waypoint

    waypoint_spacing = 40 #Distance between each waypoints in 
    
    ### ###

    #Connect with Carla
    client = carla.Client('127.0.0.1', 2000)
    client.set_timeout(10.0)
    
    # Read the opendrive file to a string
    xodr_path = "speedway_5lanes.xodr"
    #xodr_path = "Crossing8Course.xodr"
    od_file = open(xodr_path)
    data = od_file.read()

    # Load the opendrive map
    vertex_distance = 2.0  # in meters
    max_road_length = 50.0 # in meters
    wall_height = 1.0      # in meters
    extra_width = 0.6      # in meters
    world = client.generate_opendrive_world(
        data, carla.OpendriveGenerationParameters(
        vertex_distance=vertex_distance,
        max_road_length=max_road_length,
        wall_height=wall_height,
        additional_width=extra_width,
        smooth_junctions=True,
        enable_mesh_visibility=True))
    map = world.get_map()


    #Setup spectator to be used to move the view with the car as it drives
    spectator = world.get_spectator()


    #Take only the waypoints from the targetLane
    waypoint_list = map.generate_waypoints(waypoint_spacing)
    waypoints = single_lane(waypoint_list, target_lane)
    waypoints = get_curvy_waypoints(waypoints)
    spawnpoint = waypoints[i]

    #SET CUSTOM WAYPOINTS HERE WITH PATH PLANNING

    #Spawn vehicle, attach the spectator camera, and add the controller
    vehicle, camera, controller = spawn_actor(world, spawnpoint)

    print("Vehicle spawned at " + str(spawnpoint))

    while True:

        #Plot point on pyplot graph
        loc = vehicle.get_location()
        plt.plot(loc.x,loc.y, marker = 'o', color = 'r', markersize = 2)
        
        #Log point for export in csv/excel
        #Rotate into the car's frame
        vehicle_rotation = vehicle.get_transform().rotation
        point = [[time.clock(), loc.x, loc.y, vehicle.get_velocity().x, vehicle.get_velocity().y, vehicle_rotation.yaw]]
        print(point)
        df = df.append(point, ignore_index=True,sort=False)

        #Update the camera view
        spectator.set_transform(camera.get_transform())

        # Replace this section to add local path planning 
        ###
        waypoint = waypoints[i]
        #Get next waypoint
        if(vehicle.get_location().distance(waypoints[i].transform.location) < 30):
            i = i + 1
            if i >= len(waypoints) - 1:
                i = 0
        world.debug.draw_point(waypoint.transform.location, life_time=5)
        plt.plot(waypoint.transform.location.x, waypoint.transform.location.y, color = 'g', marker = 'o', markersize = 2)
        ###

        #Control vehicle's throttle and steering
        vehicle_transform = vehicle.get_transform()
        speed = math.sqrt(vehicle.get_velocity().x ** 2 + vehicle.get_velocity().y ** 2)
        #print("speed: " + str(vehicle.get_velocity())) 
        throttle = controller.throttle_control(speed)
        #throttle = 0 # for set velocity
        steer = controller.steering_control(vehicle_transform, waypoint.transform)
        control = carla.VehicleControl(throttle, steer)
        #velocity_vector = carla.Vector3D(vehicle_transform.get_forward_vector())
        #velocity_vector = carla.Vector3D(20, 0, 0)
        #vehicle.set_velocity(velocity_vector)
        #print("VV " + str(velocity_vector))
        vehicle.apply_control(control)

        print("throttle, steer: " + str(throttle) + ", " + str(steer))

        plt.axis([-500, 1500, -800, 100])
        plt.savefig("path.png")
Пример #11
0
    def _set_carla_town(self):
        """
        Extract the CARLA town (level) from the RoadNetwork information from OpenSCENARIO

        Note: The specification allows multiple Logics elements within the RoadNetwork element.
              Hence, there can be multiple towns specified. We just use the _last_ one.
        """
        for logic in self.xml_tree.find("RoadNetwork").findall("LogicFile"):
            self.town = logic.attrib.get('filepath', None)

        if self.town is not None and ".xodr" in self.town:
            if not os.path.isabs(self.town):
                self.town = os.path.dirname(os.path.abspath(self.filename)) + "/" + self.town
            if not os.path.exists(self.town):
                raise AttributeError("The provided RoadNetwork '{}' does not exist".format(self.town))

        # workaround for relative positions during init
        world = self.client.get_world()
        wmap = None
        if world:
            world.get_settings()
            wmap = world.get_map()

        if world is None or (wmap is not None and wmap.name.split('/')[-1] != self.town):
            if ".xodr" in self.town:
                with open(self.town, 'r', encoding='utf-8') as od_file:
                    data = od_file.read()
                index = data.find('<OpenDRIVE>')
                data = data[index:]

                old_map = ""
                if wmap is not None:
                    old_map = wmap.to_opendrive()
                    index = old_map.find('<OpenDRIVE>')
                    old_map = old_map[index:]

                if data != old_map:
                    self.logger.warning(" Wrong OpenDRIVE map in use. Forcing reload of CARLA world")

                    vertex_distance = 2.0  # in meters
                    wall_height = 1.0      # in meters
                    extra_width = 0.6      # in meters
                    world = self.client.generate_opendrive_world(str(data),
                                                                 carla.OpendriveGenerationParameters(
                                                                 vertex_distance=vertex_distance,
                                                                 wall_height=wall_height,
                                                                 additional_width=extra_width,
                                                                 smooth_junctions=True,
                                                                 enable_mesh_visibility=True))
            else:
                self.logger.warning(" Wrong map in use. Forcing reload of CARLA world")
                self.client.load_world(self.town)
                world = self.client.get_world()

            CarlaDataProvider.set_world(world)
            if CarlaDataProvider.is_sync_mode():
                world.tick()
            else:
                world.wait_for_tick()
        else:
            CarlaDataProvider.set_world(world)
Пример #12
0
def main():
    client = carla.Client('127.0.0.1', 2000)
    client.set_timeout(10.0)

    # Read the opendrive file to a string
    xodr_path = "speedway_5lanes.xodr"
    #xodr_path = "Crossing8Course.xodr"
    od_file = open(xodr_path)
    data = od_file.read()

    # Load the opendrive map
    vertex_distance = 2.0  # in meters
    max_road_length = 50.0  # in meters
    wall_height = 1.0  # in meters
    extra_width = 0.6  # in meters
    world = client.generate_opendrive_world(
        data,
        carla.OpendriveGenerationParameters(vertex_distance=vertex_distance,
                                            max_road_length=max_road_length,
                                            wall_height=wall_height,
                                            additional_width=extra_width,
                                            smooth_junctions=True,
                                            enable_mesh_visibility=True))

    blueprint_library = world.get_blueprint_library()

    blueprint = blueprint_library.filter('vehicle.*model3*')[0]
    spawn_points = world.get_map().get_spawn_points(
    )  # get_spawn_points() returns list(carla.Transform)
    spawn_point = spawn_points[0]
    #world.spawn_actor(blueprint, spawn_point)
    vehicle = world.spawn_actor(blueprint, spawn_point)
    vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=0.0))
    actor_list.append(vehicle)

    cam_bp = blueprint_library.find("sensor.camera.rgb")
    cam_bp.set_attribute("image_size_x", f"{IM_WIDTH}")
    cam_bp.set_attribute("image_size_y", f"{IM_HEIGHT}")
    cam_bp.set_attribute("fov", "110")

    spawn_point = carla.Transform(carla.Location(x=2.5, z=0.7))
    sensor = world.spawn_actor(cam_bp, spawn_point, attach_to=vehicle)
    actor_list.append(sensor)

    #sensor.listen(lambda data: process_img(data))
    l_images = []
    sensor.listen(lambda data: process_img(data, l_images))

    time.sleep(1)

    sensor.stop()

    for im in l_images:
        cv2.imshow('image', im)
        cv2.waitKey(16)

    #dir() - to see all the attributes?

    for i in range(10):
        location = vehicle.get_location()
        print(location)
        time.sleep(1)