def main():
    bng_home = os.environ['BEAMNG_HOME']
    road = TrainingRoad(ASFAULT_PREFAB)
    road.calculate_road_line(back=True)

    bng = BeamNGpy('localhost', 64256, home=bng_home)
    scenario = Scenario('smallgrid', 'train')
    scenario.add_road(road.asphalt)
    scenario.add_road(road.mid_line)
    scenario.add_road(road.left_line)
    scenario.add_road(road.right_line)

    vehicle = Vehicle('ego_vehicle', model='etk800', licence='PYTHON')
    front_camera = Camera(pos=(0, 1.4, 1.8),
                          direction=(0, 1, -0.23),
                          fov=FOV,
                          resolution=(CAMERA_WIDTH, CAMERA_HEIGHT),
                          colour=True,
                          depth=False,
                          annotation=False)
    vehicle.attach_sensor("front_camera", front_camera)

    # Add it to our scenario at this position and rotation

    spawn_point = road.spawn_point()
    scenario.add_vehicle(vehicle, pos=spawn_point.pos(), rot=spawn_point.rot())
    # Place files defining our scenario for the simulator to read
    scenario.make(bng)

    prefab_path = scenario.get_prefab_path()
    update_prefab(prefab_path)
    bng.open()

    bng.set_nondeterministic()
    bng.set_steps_per_second(60)
    # Load and start our scenario
    bng.load_scenario(scenario)

    bng.start_scenario()
    vehicle.ai_set_mode('span')
    vehicle.ai_set_speed(5)
    vehicle.ai_set_line([{
        'pos': node.pos(),
        'speed': 10
    } for node in road.road_line])

    number_of_images = 0
    while number_of_images < 9000:
        bng.poll_sensors(vehicle)
        number_of_images += 1
        #print(number_of_images)
        bng.step(1)
        sensors = bng.poll_sensors(vehicle)
        image = sensors['front_camera']['colour'].convert('RGB')
        image = np.array(image)
        image = image[:, :, ::-1]
        dist = road.dist_to_center(vehicle.state['pos'])
        cv2.imwrite('datasets\\{}.jpg'.format(number_of_images), image)

    bng.close()
vut.attach_sensor('electrics', electrics)
vut.attach_sensor('damage', damage)
scenario.add_vehicle(vut, pos=(-198.5, -164.189, 119.7), rot=(0, 0, -126.25))

car_1 = Vehicle('car_1', model='etk800', licence='CAR 1', colour='Blue')
scenario.add_vehicle(car_1, pos=(-140, -121.233, 119.586), rot=(0, 0, 55))

scenario.make(beamng)
bng = beamng.open(launch=True)
bng.load_scenario(scenario)
bng.start_scenario()

vut.ai_set_mode('span')
vut.ai_drive_in_lane(True)

car_1.ai_set_line([{'pos': (-198.5, -164.189, 119.7), 'speed': 2000}])

for _ in range(240):
    sleep(0.1)
    vut.update_vehicle()
    sensors = bng.poll_sensors(vut)
    dmg = sensors['damage']

    # Below code snippet is generated form 'detect_obstacle_car' function for car_1
    scenario.update()
    dist_car_1 = np.linalg.norm(
        np.array(vut.state['pos']) - np.array(car_1.state['pos']))

    if dist_car_1 < 8:
        print('Car Detected')
        # path for striker vehicle
        node0 = {
            'pos': (striker_points[0][0], striker_points[0][1], 0),
            'speed': 0,
        }

        node1 = {
            'pos': (collision_points[0][0], collision_points[0][1], 0),
            'speed': striker_speeds[0],
        }

        script = list()
        script.append(node0)
        script.append(node1)

        vehicleStriker.ai_set_line(script)

        # path for victim vehicle
        node2 = {
            'pos': (victim_points[0][0], victim_points[0][1], 0),
            'speed': 0,
        }

        node3 = {
            'pos': (collision_points[0][0], collision_points[0][1], 0),
            'speed': victim_speeds[0],
        }

        script = list()
        script.append(node2)
        script.append(node3)
Exemplo n.º 4
0
def main():
    beamng = BeamNGpy('localhost',
                      64256,
                      home='F:\Softwares\BeamNG_Research_SVN')

    scenario = Scenario('GridMap', 'road_test')
    road_a = Road('custom_track_center', looped=False)
    nodes = [
        (0, 0, 0, 4),
        (0, 400, 0, 4),
    ]
    road_a.nodes.extend(nodes)
    scenario.add_road(road_a)

    vehicle = Vehicle('ego', model='etk800', licence='PYTHON', colour='Black')
    scenario.add_vehicle(vehicle, pos=(0, 0, 0.163609),
                         rot=(0, 0, 180))  # 0.163609 ,
    scenario.make(beamng)

    script = list()

    node0 = {
        'pos': (0, 0, 0.163609),
        'speed': 20,
    }

    node1 = {
        'pos': (0, 100, 0.163609),
        'speed': 30,
    }

    script.append(node0)
    script.append(node1)

    bng = beamng.open(launch=True)
    try:
        bng.load_scenario(scenario)
        bng.start_scenario()
        vehicle.ai_set_line(script)
        # update the state of vehicle at impact.

        for _ in range(100):
            time.sleep(0.1)
            vehicle.update_vehicle(
            )  # Synchs the vehicle's "state" variable with the simulator
            sensors = bng.poll_sensors(
                vehicle
            )  # Polls the data of all sensors attached to the vehicle
            print(vehicle.state['pos'])
            if vehicle.state['pos'][1] > 99:
                print('free state')
                vehicle.control(throttle=0,
                                steering=0,
                                brake=0,
                                parkingbrake=0)
                vehicle.update_vehicle()

        bng.stop_scenario()

        for _ in range(20):
            time.sleep(0.1)

        bng.load_scenario(scenario)
        bng.start_scenario()

        node0 = {
            'pos': (0, 50, 0.163609),
            'speed': 20,
        }

        node1 = {
            'pos': (0, 100, 0.163609),
            'speed': 30,
        }

        script.append(node0)
        script.append(node1)

        vehicle.ai_set_line(script)

        input('Press enter when done...')
    finally:
        bng.close()
Exemplo n.º 5
0
def main() -> None:
    # Read CommonRoad scenario
    cr_scenario, cr_planning_problem_set = CommonRoadFileReader(cr_scenario_path) \
        .open()
    if cr_planning_problem_set:
        for _, pp in cr_planning_problem_set.planning_problem_dict.items():
            cr_planning_problem = pp
            break  # Read only the first one
    else:
        raise Exception(
            "The given CommonRoad scenario does not define a planning problem."
        )

    # Setup BeamNG
    bng = BeamNGpy('localhost', 64256, home=home_path, user=user_path)
    bng_scenario = Scenario(
        bng_scenario_environment,
        bng_scenario_name,
        authors='Stefan Huber',
        description='Simple visualization of the CommonRoad scenario ' +
        cr_scenario_name)

    # Add lane network
    lanes = cr_scenario.lanelet_network.lanelets
    for lane in lanes:
        lane_nodes = []
        for center in lane.center_vertices:
            lane_nodes.append((center[0], center[1], 0,
                               4))  # FIXME Determine appropriate width
        road = Road(cr_road_material)
        road.nodes.extend(lane_nodes)
        bng_scenario.add_road(road)

    # Add ego vehicle
    ego_vehicle = Vehicle('ego_vehicle',
                          model='etk800',
                          licence='EGO',
                          color='Cornflowerblue')
    ego_init_state = cr_planning_problem.initial_state
    ego_init_state.position[0] = 82.8235
    ego_init_state.position[1] = 31.5786
    add_vehicle_to_bng_scenario(bng_scenario, ego_vehicle, ego_init_state,
                                etk800_z_offset)

    obstacles_to_move = dict()

    # Add truck
    semi = Vehicle('truck', model='semi', color='Red')
    semi_init_state = cr_scenario.obstacle_by_id(206).initial_state
    add_vehicle_to_bng_scenario(bng_scenario, semi, semi_init_state,
                                semi_z_offset)
    obstacles_to_move[206] = semi

    # Add truck trailer
    tanker_init_state = copy(semi_init_state)
    tanker_init_state.position += [6, 3]
    add_vehicle_to_bng_scenario(
        bng_scenario, Vehicle('truck_trailer', model='tanker', color='Red'),
        tanker_init_state, tanker_z_offset)

    # Add other traffic participant
    opponent = Vehicle('opponent',
                       model='etk800',
                       licence='VS',
                       color='Cornflowerblue')
    add_vehicle_to_bng_scenario(bng_scenario, opponent,
                                cr_scenario.obstacle_by_id(207).initial_state,
                                etk800_z_offset)
    obstacles_to_move[207] = opponent

    # Add static obstacle
    obstacle_shape: Polygon = cr_scenario.obstacle_by_id(399).obstacle_shape
    obstacle_pos = obstacle_shape.center
    obstacle_rot_deg = rad2deg(semi_init_state.orientation) + rot_offset
    obstacle_rot_rad = semi_init_state.orientation + deg2rad(rot_offset)
    for w in range(3):
        for h in range(3):
            for d in range(2):
                obstacle = Vehicle('obstacle' + str(w) + str(h) + str(d),
                                   model='haybale',
                                   color='Red')
                haybale_pos_diff = obstacle_pos \
                    + pol2cart(1.3 * d, obstacle_rot_rad + pi / 4) \
                    + pol2cart(2.2 * w, pi / 2 - obstacle_rot_rad)
                bng_scenario.add_vehicle(obstacle,
                                         pos=(haybale_pos_diff[0],
                                              haybale_pos_diff[1], h * 1),
                                         rot=(0, 0, obstacle_rot_deg))

    bng_scenario.make(bng)

    # Manually set the overObjects attribute of all roads to True (Setting this option is currently not supported)
    prefab_path = os.path.join(user_path, 'levels', bng_scenario_environment,
                               'scenarios', bng_scenario_name + '.prefab')
    lines = open(prefab_path, 'r').readlines()
    for i in range(len(lines)):
        if 'overObjects' in lines[i]:
            lines[i] = lines[i].replace('0', '1')
    open(prefab_path, 'w').writelines(lines)

    # Start simulation
    bng.open(launch=True)
    try:
        bng.load_scenario(bng_scenario)
        bng.start_scenario()
        bng.pause()

        bng.display_gui_message(
            "The scenario is fully prepared and paused. You may like to position the camera first."
        )
        delay_to_resume = 15
        input("Press enter to continue the simulation... You have " +
              str(delay_to_resume) +
              " seconds to switch back to the BeamNG window.")
        sleep(delay_to_resume)
        bng.resume()

        for id, obstacle in obstacles_to_move.items():
            obstacle.ai_drive_in_lane(False)
            obstacle.ai_set_line(
                generate_node_list(cr_scenario.obstacle_by_id(id)))

        ego_vehicle.ai_drive_in_lane(False)
        # ego_vehicle.ai_set_speed(cr_planning_problem.initial_state.velocity * 3.6, mode='limit')
        speed = 65 / 3.6
        ego_vehicle.ai_set_line([{
            'pos': ego_vehicle.state['pos']
        }, {
            'pos': (129.739, 56.907, etk800_z_offset),
            'speed': speed
        }, {
            'pos': (139.4, 62.3211, etk800_z_offset),
            'speed': speed
        }, {
            'pos': (149.442, 64.3655, etk800_z_offset),
            'speed': speed
        }, {
            'pos': (150.168, 63.3065, etk800_z_offset),
            'speed': speed
        }, {
            'pos': (188.495, 78.8517, etk800_z_offset),
            'speed': speed
        }])
        # FIXME Setting the speed does not work as expected
        # ego_vehicle.ai_set_speed(cr_planning_problem.initial_state.velocity * 3.6, mode='set')

        input("Press enter to end simulation...")
    finally:
        bng.close()
Exemplo n.º 6
0
def createCrashSimulation():
    print("Crash Simulation")

    beamng = BeamNGpy('localhost',
                      64256,
                      home='F:\Softwares\BeamNG_Research_SVN')
    scenario = Scenario('GridMap', 'road_crash_simulation')

    road_a = Road('track_editor_C_center', looped=False)
    road_b = Road('track_editor_C_center', looped=False)

    nodesa = [(30, 0, -4, 4), (0, 0, -4, 4)]

    nodesb = [(0, 30, -4, 4), (0, 0, -4, 4)]

    road_a.nodes.extend(nodesa)
    road_b.nodes.extend(nodesb)

    # Create an ETK800 with the licence plate 'PYTHON'
    vehicleA = Vehicle('ego_vehicleA', model='etk800', licence='PYTHON')
    # Add it to our scenario at this position and rotation

    damageS = Damage()
    vehicleA.attach_sensor('damagesS', damageS)

    scenario.add_vehicle(vehicleA, pos=(30, 0, 0), rot=(0, 0, 90))

    # Create an ETK800 with the licence plate 'PYTHON'
    vehicleB = Vehicle('ego_vehicleB', model='etk800', licence='PYTHON')
    # Add it to our scenario at this position and rotation

    damageV = Damage()
    vehicleB.attach_sensor('damagesV', damageV)

    scenario.add_vehicle(vehicleB, pos=(0, 30, 0), rot=(0, 0, 0))

    scenario.add_road(road_a)
    scenario.add_road(road_b)

    scenario.make(beamng)

    bng = beamng.open(launch=True)
    try:
        bng.load_scenario(scenario)
        bng.start_scenario()

        node0 = {
            'pos': (30, 0, 0),
            'speed': 0,
        }

        node1 = {
            'pos': (0, 0, 0),
            'speed': 20,
        }

        script = list()
        script.append(node0)
        script.append(node1)

        vehicleA.ai_set_line(script)

        node3 = {
            'pos': (0, 30, 0),
            'speed': 0,
        }

        node4 = {
            'pos': (0, 0, 0),
            'speed': 20,
        }

        script = list()
        script.append(node3)
        script.append(node4)

        vehicleB.ai_set_line(script)

        time.sleep(12)
        #       input('Press enter when done...')
        vehicleA.update_vehicle(
        )  # Synchs the vehicle's "state" variable with the simulator
        sensors = bng.poll_sensors(vehicleA)
        damage_striker = sensors['damagesS']
        print(sensors['damagesS'])
        print(vehicleA.state['pos'])

        vehicleB.update_vehicle(
        )  # Synchs the vehicle's "state" variable with the simulator
        sensors = bng.poll_sensors(vehicleB)
        damage_victim = sensors['damagesV']
        print(sensors['damagesV'])
        print(vehicleB.state['pos'])

        multiObjectiveFitnessFunction(123456789, damage_striker,
                                      vehicleA.state['pos'], (0, 0),
                                      damage_victim, vehicleB.state['pos'],
                                      (0, 0))
        # multiobjective fitness function.

        bng.stop_scenario()

        # bng.load_scenario(scenario)
        # bng.start_scenario()
        #
        # print("sleep")
        # time.sleep(10)
        # print("wake")
        #
        # node0 = {
        #     'pos': (30, 0, 0),
        #     'speed': 0,
        # }
        #
        # node1 = {
        #     'pos': (0, 0, 0),
        #     'speed': 30,
        # }
        #
        # script = list()
        # script.append(node0)
        # script.append(node1)
        #
        # vehicleA.ai_set_line(script)
        #
        # node0 = {
        #     'pos': (0, 30, 0),
        #     'speed': 0,
        # }
        #
        # node1 = {
        #     'pos': (0, 0, 0),
        #     'speed': 30,
        # }
        #
        # script = list()
        # script.append(node0)
        # script.append(node1)
        #
        # vehicleB.ai_set_line(script)
        #
        # input('Press enter when done...')

    finally:
        bng.close()
Exemplo n.º 7
0
def main():
    """
    Generate a bunch of images by driving along a predefined sequence of points, while capturing camera images
    to JPG files.

    :return: (None)
    """
    bng_home = os.environ['BEAMNG_HOME']
    road = TrainingRoad(ASFAULT_PREFAB)
    road.calculate_road_line(back=True)

    bng = BeamNGpy('localhost', 64256, home=bng_home)
    scenario = Scenario('smallgrid', 'train')

    # Asphalt and lines are actually considered as differently colored roads by beamngpy.
    scenario.add_road(road.asphalt)
    scenario.add_road(road.mid_line)
    scenario.add_road(road.left_line)
    scenario.add_road(road.right_line)

    vehicle = Vehicle('ego_vehicle', model='etk800', licence='PYTHON')
    # Create a dash cam that is somewhat down-sloped.
    front_camera = Camera(pos=(0, 1.4, 1.8),
                          direction=(0, 1, -0.23),
                          fov=FOV,
                          resolution=(CAMERA_WIDTH, CAMERA_HEIGHT),
                          colour=True,
                          depth=False,
                          annotation=False)
    vehicle.attach_sensor("front_camera", front_camera)

    # Get a spawn point and initial rotation of the vehicle.
    spawn_point = road.spawn_point()
    scenario.add_vehicle(vehicle, pos=spawn_point.pos(), rot=spawn_point.rot())
    # Place files defining our scenario for the simulator to read.
    scenario.make(bng)

    prefab_path = scenario.get_prefab_path()
    update_prefab(prefab_path)
    bng.open()

    bng.set_nondeterministic()
    bng.set_steps_per_second(60)
    # Load and start our scenario
    bng.load_scenario(scenario)

    bng.start_scenario()
    vehicle.ai_set_mode('span')
    vehicle.ai_set_speed(5)
    vehicle.ai_set_line([{
        'pos': node.pos(),
        'speed': 10
    } for node in road.road_line])

    number_of_images = 0
    while number_of_images < NUMBER_OF_IMAGES:
        bng.poll_sensors(vehicle)
        number_of_images += 1
        bng.step(1)
        sensors = bng.poll_sensors(vehicle)
        image = sensors['front_camera']['colour'].convert('RGB')
        image = np.array(image)
        image = image[:, :, ::-1]
        dist = road.dist_to_center(vehicle.state['pos'])
        cv2.imwrite('datasets\\{}.jpg'.format(number_of_images), image)

    bng.close()