Esempio n. 1
0
def getStaticScenario(testName):
    beamng = BeamNGpy('localhost', 64256, home=getBeamngDirectory()
                      )  # This is the host & port used to communicate over
    staticScenario = Scenario('smallgrid', str(testName))

    testVehicle = Vehicle('Test_Vehicule',
                          model=SelectCar(),
                          licence='LIFLAB',
                          colour='Blue')

    # Create an Electrics sensor and attach it to the vehicle
    electrics = Electrics()
    testVehicle.attach_sensor('electrics', electrics)

    # Create a Damage sensor and attach it to the vehicle if module is selected
    damage = Damage()
    testVehicle.attach_sensor('damage', damage)

    # Create a Gforce sensor and attach it to the vehicle if module is selected
    gForce = GForces()
    testVehicle.attach_sensor('GForces', gForce)

    staticScenario.add_vehicle(testVehicle, (0, 0, 0), (0, 0, -90))

    scenarioDict = {
        'beamng': beamng,
        'scenario': staticScenario,
        'vehicule': testVehicle
    }

    return scenarioDict
Esempio n. 2
0
def main(beamng, scenario_name):
    # Find a scenario in the smallgrid level called 'Case4'
    level = 'smallgrid'
    scenario = Scenario(level, scenario_name)
    # Update the scenario instance with its path
    scenario.find(beamng)

    bng = beamng.open(launch=True)
    bng.hide_hud()
    bng.set_deterministic()  # Set simulator to be deterministic mode

    # Load and start the scenario
    bng.load_scenario(scenario)

    # Gets vehicles placed in the scenario
    vehicle_bng = 'BeamNGVehicle'
    vehicles = create_vehicle(bng.find_objects_class(vehicle_bng))

    # bng.set_steps_per_second(10)
    for vehicle in vehicles:
        bng.connect_vehicle(vehicle)
        assert vehicle.skt

    bng.step(75, wait=True)
    bng.start_scenario()
    for _ in range(64):
        bng.step(30)
        s1 = bng.poll_sensors(vehicles[0])
        s2 = bng.poll_sensors(vehicles[1])
        print(s1)
        print(s2)
        print('------')
    def setup_BeamNG(self):
        # Create a scenario in test map
        self.scenario = Scenario('cruise-control', 'example')

        # Create an ETK800 with the licence plate 'PID'
        self.vehicle = Vehicle('ACC', model='etk800', licence='ACC')

        electrics = Electrics()
        self.vehicle.attach_sensor('electrics',
                                   electrics)  # Cars electric system

        # Add it to our scenario at this position and rotation
        self.scenario.add_vehicle(self.vehicle, pos=ACC_CAR_POS, rot=(0, 0, 0))

        self.vehicle2 = Vehicle('FRONT', model='etk800', licence='FRONT')
        self.vehicle2.attach_sensor('electrics',
                                    electrics)  # Cars electric system
        self.scenario.add_vehicle(self.vehicle2,
                                  pos=FRONT_CAR_POS,
                                  rot=(0, 0, 180))
        # Place files defining our scenario for the simulator to read
        self.scenario.make(self.bng)

        # Launch BeamNG.research

        self.bng.open()

        # Load and start our scenario

        self.bng.load_scenario(self.scenario)
        self.bng.start_scenario()
Esempio n. 4
0
    def bring_up(self):

        if self.reuse_beamng:
            # This assumes BeamNG is already running
            self.beamng.open(launch=False)
        else:
            self.beamng.open(launch=True)

        # After 1.18 to make a scenario one needs a running instance of BeamNG
        self.scenario = Scenario('tig', 'tigscenario')
        if self.vehicle:
            self.scenario.add_vehicle(self.vehicle,
                                      pos=self.vehicle_start_pose.pos,
                                      rot=self.vehicle_start_pose.rot)

        if self.camera:
            self.scenario.add_camera(self.camera.camera, self.camera.name)

        self.scenario.make(self.beamng)

        self.beamng.set_deterministic()

        self.beamng.load_scenario(self.scenario)

        self.beamng.start_scenario()

        # Pause the simulator only after loading and starting the scenario
        self.beamng.pause()
Esempio n. 5
0
    def _init_beamNG(self) -> None:
        """
        Initialize beamNG:
            Create the scenario, vehicle, sensors, and load everything
        """
        self.scenario = Scenario(self.OPTIONS['scenario_map'],
                                 self.OPTIONS['scenario_name'],
                                 description=self.OPTIONS['scenario_desc'])

        self.vehicle = Vehicle(self.OPTIONS['vehicle_name'],
                               model=self.OPTIONS['vehicle_model'],
                               license=self.OPTIONS['vehicle_license'])
        self.lidar_sensor = Lidar(max_dist=180, vres=24, vangle=25)
        self.vehicle.attach_sensor('lidar', self.lidar_sensor)

        self.front_camera = Camera(self.OPTIONS['f_cam_pos'],
                                   self.OPTIONS['f_cam_dir'],
                                   self.OPTIONS['f_cam_fov'],
                                   self.OPTIONS['f_cam_res'],
                                   colour=True,
                                   annotation=True)
        self.vehicle.attach_sensor('front_camera', self.front_camera)

        self.scenario.add_vehicle(self.vehicle, self.OPTIONS['vehicle_pos'],
                                  self.OPTIONS['vehicle_rot'],
                                  self.OPTIONS['vehicle_rot_quat'])
        self.scenario.make(self.beamng)

        self.beamng.load_scenario(self.scenario)
Esempio n. 6
0
def test_find_scenario(beamng):
    with beamng as bng:
        scenario = Scenario('west_coast_usa', 'derby_asphalt')
        scenario.find(bng)
        assert scenario.get_info_path() is not None
        bng.load_scenario(scenario)
        assert bng.get_scenario_name(
        ) == 'scenarios.west_coast_usa.derby_asphalt.title'
Esempio n. 7
0
    def _start_simulation(self,
                          test_case: TestCase) -> Tuple[Scenario, ExtThread]:
        from threading import Thread
        from config import BEAMNG_LEVEL_NAME
        from beamngpy.beamngcommon import BNGValueError

        Simulation._start_simulation.lock.acquire()
        while not Simulation._is_port_available(
                Simulation._start_simulation.port):
            Simulation._start_simulation.port += 200  # Make sure to not interfere with previously started simulations
        self._bng_instance = DBBeamNGpy('localhost',
                                        Simulation._start_simulation.port)
        authors = ", ".join(test_case.authors)
        bng_scenario = Scenario(BEAMNG_LEVEL_NAME,
                                self._sim_name,
                                authors=authors)

        test_case.scenario.add_all(bng_scenario)
        bng_scenario.make(self._bng_instance)

        # Make manual changes to the scenario files
        self._make_lanes_visible()
        self._annotate_objects()
        self._add_waypoints_to_scenario(test_case.scenario.participants)
        self._enable_participant_movements(test_case.scenario.participants)
        waypoints = set()
        for wps in [p.movement for p in test_case.scenario.participants]:
            for wp in wps:
                if wp.id is not None:  # FIXME Waypoints are added in wrong order
                    waypoints.add(wp.id)
        # self._add_lap_config(waypoints)

        try:
            self._bng_instance.open(launch=True)
            self._bng_instance.load_scenario(bng_scenario)
            self._bng_instance.set_steps_per_second(test_case.stepsPerSecond)
            self._bng_instance.set_deterministic()
            test_case.scenario.set_time_of_day_to(self._bng_instance)
            self._bng_instance.hide_hud()
            self._bng_instance.start_scenario()
            self._bng_instance.pause()
        except OSError:
            _logger.exception("The start of a BeamNG instance failed (Port: " +
                              str(Simulation._start_simulation.port) + ").")
        except BNGValueError:
            _logger.exception(
                "Sending to or receiving from BeamNGpy failed and may corrupt the socket"
            )
        Simulation._start_simulation.lock.release()

        runtime_thread = Thread(target=Simulation._run_runtime_verification,
                                args=(self, test_case.aiFrequency))
        runtime_thread.daemon = True
        runtime_thread.start()

        while not runtime_thread.ident:  # Wait for the Thread to get an ID
            pass
        return bng_scenario, ExtThread(runtime_thread.ident)
    def __init__(self):
        super().__init__()

        # Break an episode upon user input.
        thread = Thread(target=self._intervene)
        thread.start()

        self.step = 0
        self.dist_driven = 0
        self.done = False
        self.last_action = (0.0, 0.0)
        self.bng = BeamNGpy('localhost', 64257, home=BEAMNG_HOME)
        self.scenario = Scenario('train',
                                 'train',
                                 authors='Vsevolod Tymofyeyev',
                                 description='Reinforcement learning')

        self.road = TrainingRoad(ASFAULT_PREFAB)
        self.road.calculate_road_line()

        spawn_point = self.road.spawn_point()
        self.last_pos = spawn_point.pos()
        self.scenario.add_road(self.road.asphalt)
        self.scenario.add_road(self.road.mid_line)
        self.scenario.add_road(self.road.left_line)
        self.scenario.add_road(self.road.right_line)

        self.vehicle = Vehicle('ego_vehicle',
                               model='etk800',
                               licence='RL FTW',
                               color='Red')
        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)
        self.vehicle.attach_sensor("front_camera", front_camera)

        self.scenario.add_vehicle(self.vehicle,
                                  pos=spawn_point.pos(),
                                  rot=spawn_point.rot())

        # At this point, BeamNG creates a prefab file which contains the specified roads.
        self.scenario.make(self.bng)
        prefab_path = self.scenario.get_prefab_path()
        # Update the road definitions in the prefab.
        update_prefab(prefab_path)

        self.bng.open()
        self.bng.set_deterministic()
        self.bng.set_steps_per_second(SPS)
        self.bng.load_scenario(self.scenario)
        self.bng.start_scenario()

        # self.bng.hide_hud()
        self.bng.pause()
Esempio n. 9
0
    def __init__(self,
                 bng_home,
                 output,
                 config,
                 poolsize=2,
                 smallgrid=False,
                 sim_mtx=None,
                 similarity=0.5,
                 random_select=False,
                 single=False):
        self.bng_home = bng_home
        self.output = output
        self.config = config
        self.smallgrid = smallgrid
        self.single = single

        self.impactgen_mats = None
        if smallgrid:
            mats = materialmngr.get_impactgen_materials(bng_home)
            self.impactgen_mats = sorted(list(mats))

        self.poolsize = poolsize
        self.similarity = similarity
        self.sim_mtx = sim_mtx
        self.random_select = random_select

        self.pole_space = None
        self.t_bone_space = None
        self.linear_space = None
        self.nocrash_space = None

        self.post_space = None

        self.total_possibilities = 0

        self.bng = BeamNGpy('localhost', 64256, home=bng_home)

        self.scenario = None

        scenario_props = ImpactGenerator.wca
        if smallgrid:
            scenario_props = ImpactGenerator.smallgrid

        self.vehicle_a = Vehicle('vehicle_a', model='etk800')
        self.vehicle_b = Vehicle('vehicle_b', model='etk800')

        self.scenario = Scenario(scenario_props['level'], 'impactgen')
        self.scenario.add_vehicle(self.vehicle_a,
                                  pos=scenario_props['a_spawn'],
                                  rot=(0, 0, 0))
        self.scenario.add_vehicle(self.vehicle_b,
                                  pos=scenario_props['b_spawn'],
                                  rot=(0, 0, 0))

        self.vehicle_a_parts = defaultdict(set)
        self.vehicle_a_config = None
        self.vehicle_b_config = None
Esempio n. 10
0
def test_find_scenario(beamng):
    with beamng as bng:
        scenario = Scenario('west_coast_usa', 'derby_asphalt')
        assert scenario.find(bng) is not None
        bng.load_scenario(scenario)
        assert 'derby' in bng.get_scenario_name().lower()
        try:
            bng.start_scenario()
            assert True
        except socket.timeout:
            assert False
Esempio n. 11
0
    def execute_scenario(self, bng):
        scenario = Scenario(self.level, self.scenario)
        # Update the scenario instance with its path
        scenario.find(bng)

        # Configures BeamNG client
        bng.open(launch=True)
        bng.hide_hud()
        bng.set_deterministic()  # Set simulator to be deterministic mode

        # Load and start the scenario
        bng.load_scenario(scenario)

        # Gets vehicles placed in the scenario
        vehicle_bng = 'BeamNGVehicle'
        self.create_vehicle(bng.find_objects_class(vehicle_bng))

        # bng.set_steps_per_second(10)
        for car in self.cars:
            vehicle = car.vehicle
            bng.connect_vehicle(vehicle)
            assert vehicle.skt

        # Wait for 50 steps before start
        waiting_steps = 50
        bng.step(waiting_steps, wait=True)
        bng.start_scenario()  # Start scenario

        accident_log = {}
        for _ in range(self.timeout):
            empty = not bool(accident_log)
            if empty:
                # Collects sensor data every 30 steps
                bng.step(30)
                for car in self.cars:
                    vehicle = car.vehicle
                    sensor = bng.poll_sensors(vehicle)['damage']
                    if (sensor['damage'] != 0):  # Crash detected
                        print("Crash detected!")
                        self.isCrash = True
                        accident_log.update(
                            {vehicle.vid: sensor['part_damage']})
                        car.damage = sensor['part_damage']
            else:
                self.write_log(accident_log)  # Write log file
                waiting_steps = 175
                bng.step(waiting_steps, wait=True)
                print("Within time!")
                break

        # Timeout
        if not self.isCrash:
            print("Timed out!")
        self.close_scenario(bng)
 def __init__(self):
     self.collected_data = {"image_name": [], "steering": []}
     self.scenario = Scenario(config.get("data_collecting.scenario_level"),
                              config.get("data_collecting.scenario_name"))
     self.vehicle = Vehicle(
         'ego_vehicle',
         model=config.get("data_collecting.vehicle_model"),
         licence='PYTHON')
     self.bng = BeamNGpy(config.get("beamNG.host"),
                         int(config.get("beamNG.port")),
                         home=config.get("beamNG.home"))
Esempio n. 13
0
def main():
    beamng = BeamNGpy('localhost', 64256)

    scenario = Scenario('GridMap', 'road_test')
    road_a = Road('track_editor_C_center', looped=True)
    nodes = [
        (-25, 300, 0, 5),
        (25, 300, 0, 6),
        (25, 350, 0, 4),
        (-25, 350, 0, 5),
    ]
    road_a.nodes.extend(nodes)
    scenario.add_road(road_a)

    road_b = Road('track_editor_C_center')
    nodes = [
        (0, 325, 0, 5),
        (50, 375, 0, 5),
    ]
    road_b.nodes.extend(nodes)
    scenario.add_road(road_b)

    scenario.make(beamng)

    bng = beamng.open(launch=True)
    try:
        bng.load_scenario(scenario)
        bng.start_scenario()
        input('Press enter when done...')
    finally:
        bng.close()
Esempio n. 14
0
def test_camera_control(beamng):
    with beamng as bng:
        scenario = Scenario('smallgrid', 'camera_control_test')
        ego = Vehicle('ego', model='etk800')
        other = Vehicle('other', model='etk800')

        scenario.add_vehicle(ego, pos=(0, 0, 0))
        scenario.add_vehicle(other, pos=(5, 5, 0))
        scenario.make(bng)

        bng.load_scenario(scenario)
        bng.start_scenario()

        camera_configs = bng.get_player_camera_modes(ego.vid)

        for camera in camera_configs.keys():
            bng.set_player_camera_mode(ego.vid, camera, {})
            time.sleep(5)
            current_camera = bng.get_player_camera_modes(ego.vid)
            assert current_camera[camera]['focused']

        time.sleep(10)

        assert 'orbit' in camera_configs

        bng.set_player_camera_mode(ego.vid, 'orbit', {'distance': 50})
        time.sleep(5)
        current_camera = bng.get_player_camera_modes(ego.vid)

        assert current_camera['orbit']['focused']
        assert abs(current_camera['orbit']['camDist'] - 50) < 0.5
Esempio n. 15
0
def getStrangeScenario():
    beamNGPAth = getBeamngDirectory()
    beamng = BeamNGpy(
        'localhost', 64256,
        home=beamNGPAth)  # This is the host & port used to communicate over
    wallCrashScenario = Scenario('smallgrid', 'road_test')
    wall = StaticObject(
        name="Crash_Test_Wall",
        pos=(10, 0, 0),
        rot=(0, 0, 0),
        scale=(1, 10, 1),
        shape='/levels/smallgrid/art/shapes/misc/gm_alpha_barrier.dae')
    testRoad = Road('track_editor_A_center', rid='Test_Road')
    roadNode = [(-10, 0, 0, 7), (20, 0, 62)]
    testRoad.nodes.extend(roadNode)
    testVehicle = Vehicle('Test_Vehicule',
                          model='etkc',
                          licence='LIFLAB',
                          colour='Blue')
    wallCrashScenario.add_road(testRoad)
    wallCrashScenario.add_object(wall)
    wallCrashScenario.add_vehicle(testVehicle,
                                  pos=(0, 0, 0),
                                  rot=(0, 180, -90))
    scenarioDict = {
        'beamng': beamng,
        'scenario': wallCrashScenario,
        'vehicule': testVehicle
    }
    return scenarioDict
Esempio n. 16
0
def test_ultrasonic(beamng):
    with beamng as bng:
        scenario = Scenario('smallgrid', 'ultrasonic_test')
        cube_dist = 4
        cube = ProceduralCube(name='cube',
                              pos=(0, -cube_dist, 5),
                              rot=None,
                              rot_quat=(0, 0, 0, 1),
                              size=(1, 20, 10))
        scenario.add_procedural_mesh(cube)

        pos = (0, 1, 2)
        rot = (0, 1, 0)
        ultrasonic = Ultrasonic(pos, rot)

        vehicle = Vehicle('test', model='pickup')
        vehicle.attach_sensor('ultrasonic', ultrasonic)

        scenario.add_vehicle(vehicle, pos=(0, 0, 0), rot_quat=(0, 0, 0, 1))
        scenario.make(beamng)

        bng.load_scenario(scenario)
        bng.start_scenario()
        vehicle.poll_sensors()
        assert 0 < vehicle.sensors['ultrasonic'].data['distance'] < cube_dist
Esempio n. 17
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 = {
        'x': 0,
        'y': 2,
        'z': 0.163609,
        't': 0.01,
    }

    node1 = {
        'x': 0,
        'y': 3,
        'z': 0.163609,
        't': 0.01,
    }

    node2 = {
        'x': 0,
        'y': 350,
        'z': 0.163609,
        't': 15,
    }

    node3 = {
        'x': 0,
        'y': 400,
        'z': 0.163609,
        't': 5,
    }

    script.append(node0)
    script.append(node1)
    script.append(node2)
    script.append(node3)

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

        input('Press enter when done...')
    finally:
        bng.close()
Esempio n. 18
0
def main():
    beamng = BeamNGpy('localhost',
                      64256,
                      home='C:/Users/merie/Documents/BeamNG.research.v1.7.0.0')

    scenario = Scenario('GridMap', 'road_test')
    road_a = Road('track_editor_C_center', rid='circle_road', looped=True)
    nodes = [
        (-25, 300, 0, 5),
        (25, 300, 0, 6),
        (25, 350, 0, 4),
        (-25, 350, 0, 5),
    ]
    road_a.nodes.extend(nodes)
    scenario.add_road(road_a)

    road_b = Road('track_editor_C_center', rid='center_road')
    nodes = [
        (0, 325, 0, 5),
        (50, 375, 0, 5),
    ]
    road_b.nodes.extend(nodes)
    scenario.add_road(road_b)

    scenario.make(beamng)

    bng = beamng.open(launch=True)
    try:
        bng.load_scenario(scenario)
        bng.start_scenario()
        input('Press enter when done...')
    finally:
        bng.close()
    def bring_up(self):
        self.scenario = Scenario('tig', 'tigscenario')
        if self.vehicle:
            self.scenario.add_vehicle(self.vehicle, pos=self.vehicle_start_pose.pos, rot=self.vehicle_start_pose.rot)

        if self.camera:
            self.scenario.add_camera(self.camera.camera, self.camera.name)

        self.scenario.make(self.beamng)
        if not self.beamng.server:
            self.beamng.open()
        self.beamng.pause()
        self.beamng.set_deterministic()
        self.beamng.load_scenario(self.scenario)
        self.beamng.start_scenario()
Esempio n. 20
0
 def add_participants_to_scenario(self, scenario: Scenario) -> None:
     from dbtypes.beamng import DBVehicle
     for participant in self.participants:
         # FIXME Adjust color
         vehicle = DBVehicle(participant.id,
                             model=participant.model,
                             color="White",
                             licence=participant.id)
         for request in participant.ai_requests:
             vehicle.apply_request(request)
         initial_state = participant.initial_state
         # NOTE Participants use degrees for rotation
         scenario.add_vehicle(vehicle,
                              pos=(initial_state.position[0],
                                   initial_state.position[1], 0),
                              rot=(0, 0, -initial_state.orientation - 90))
Esempio n. 21
0
    def _init_beamNG(self) -> None:
        self.scenario = Scenario(self.scenario_map,
                                 self.scenario_name,
                                 description=self.scenario_desc)

        self.vehicle = Vehicle(self.vehicle_name,
                               model=self.vehicle_model,
                               license=self.vehicle_license)
        self.lidar_sensor = Lidar()
        self.vehicle.attach_sensor('lidar', self.lidar_sensor)

        self.scenario.add_vehicle(self.vehicle, self.vehicle_pos,
                                  self.vehicle_rot, self.vehicle_rot_quat)
        self.scenario.make(self.beamng)

        self.beamng.load_scenario(self.scenario)
Esempio n. 22
0
def test_vehicle_spawn(beamng):
    scenario = Scenario('smallgrid', 'spawn_test')
    vehicle = Vehicle('irrelevant', model='pickup')
    scenario.add_vehicle(vehicle, pos=(0, 0, 0), rot=(0, 0, 0))
    scenario.make(beamng)

    with beamng as bng:
        bng.load_scenario(scenario)
        bng.start_scenario()

        other = Vehicle('relevant', model='etk800')
        scenario.add_vehicle(other, pos=(10, 10, 0), rot=(0, 0, 0))
        other.update_vehicle()
        assert 'pos' in other.state
        bng.step(120)
        scenario.remove_vehicle(other)
        bng.step(600)
        assert other.state is None
Esempio n. 23
0
def setup_beamng(traffic=2):
    global sp, beamng_home, beamng_user
    setup_logging()
    beamng = BeamNGpy('localhost', 64256, home=beamng_home, user=beamng_user)
    scenario = Scenario(
        'west_coast_usa',
        'lidar_tour',
        description=
        'Tour through highway with variable traffic vehicles gathering '
        'Lidar data')
    # setup vehicle
    vehicle = Vehicle('ego_vehicle',
                      model='etk800',
                      licence='LIDAR',
                      color='Red')
    vehicle = setup_sensors(vehicle)

    # setup vehicle poses
    lane = random.choice([1, 2, 3, 4])
    ego_sp = spawn_point(sp, lane)
    ego_pos = ego_sp['pos']
    ego_rot_quat = ego_sp['rot_quat']
    lane = ego_sp['lane']
    # add vehicles to scenario
    # print("adding vehicle to scenario...")
    scenario.add_vehicle(vehicle, pos=ego_pos, rot=None, rot_quat=ego_rot_quat)
    tvs = traffic_vehicles(traffic)
    ps = generate_vehicle_positions(ego_pos, ego_rot_quat, lane, tvs)
    for i in range(len(tvs)):
        print("adding vehicle {}...".format(i))
        scenario.add_vehicle(tvs[i], pos=ps[i], rot_quat=ego_rot_quat)
    print("making scenario...")
    scenario.make(beamng)
    print("opening beamNG...")
    bng = beamng.open(launch=True)
    st = time.time()

    print("loading scenario...")
    bng.load_scenario(scenario)

    bng.set_steps_per_second(60)
    bng.set_deterministic()
    #print("Bounding box: {}".format(vehicle.get_bbox()))
    bng.hide_hud()
    print("starting scenario...")
    bng.start_scenario()
    vehicle.ai_set_mode('traffic')
    #"DecalRoad31765_8"
    vehicle.ai_drive_in_lane(False)
    vehicle.ai_set_aggression(2.0)
    bng.start_traffic(tvs)
    bng.switch_vehicle(vehicle)
    bng.pause()
    return vehicle, bng
Esempio n. 24
0
def test_vehicle_spawn(beamng):
    with beamng as bng:
        scenario = Scenario('smallgrid', 'spawn_test')
        vehicle = Vehicle('irrelevant', model='pickup')
        scenario.add_vehicle(vehicle, pos=(0, 0, 0), rot=(0, 0, 0))
        scenario.make(beamng)

        bng.load_scenario(scenario)
        bng.start_scenario()

        other = Vehicle('relevant', model='etk800')
        scenario.add_vehicle(other, pos=(10, 10, 0), rot=(0, 0, 0))
        other.poll_sensors()
        assert other.sensors['state'].connected
        assert 'pos' in other.sensors['state'].data
        bng.step(120, wait=True)
        scenario.remove_vehicle(other)
        bng.step(600, wait=True)
        assert not other.sensors['state'].connected
Esempio n. 25
0
def test_new_scenario(beamng):
    with beamng as bng:
        scenario = Scenario('smallgrid', 'test_scenario')
        vehicle = Vehicle('test_car', model='etk800')
        scenario.add_vehicle(vehicle, pos=(0, 0, 0), rot=(0, 0, 0))
        scenario.make(bng)
        bng.load_scenario(scenario)
        assert bng.get_scenario_name() == 'test_scenario'

    scenario.delete(beamng)

    with beamng as bng:
        with pytest.raises(BNGValueError):
            bng.load_scenario(scenario)
Esempio n. 26
0
def getSquareRoadScenario():
    beamng = BeamNGpy('localhost', 64256, home=getBeamngDirectory()
                      )  # This is the host & port used to communicate over
    squareRoadScenario = Scenario('smallgrid', 'Straight_Foward_Test')

    testRoad = Road('track_editor_C_center', rid='Test_Road', looped=True)
    roadNode = [(0, 0, 0, 7), (250, 0, 0, 7), (250, 250, 0, 7), (0, 250, 0, 7)]
    testRoad.nodes.extend(roadNode)

    testVehicle = Vehicle('Test_Vehicule',
                          model='etkc',
                          licence='LIFLAB',
                          colour='Blue')

    # Create an Electrics sensor and attach it to the vehicle
    electrics = Electrics()
    testVehicle.attach_sensor('electrics', electrics)

    # Create a Damage sensor and attach it to the vehicle if module is selected
    damage = Damage()
    testVehicle.attach_sensor('damage', damage)

    # Create a Gforce sensor and attach it to the vehicle if module is selected
    gForce = GForces()
    testVehicle.attach_sensor('GForces', gForce)

    squareRoadScenario.add_road(testRoad)
    squareRoadScenario.add_vehicle(testVehicle, pos=(0, 0, 0), rot=(0, 0, -90))
    scenarioDict = {
        'beamng': beamng,
        'scenario': squareRoadScenario,
        'vehicule': testVehicle
    }

    return scenarioDict
Esempio n. 27
0
def test_noise(beamng):
    scenario = Scenario('west_coast_usa', 'camera_test')
    vehicle = Vehicle('test_car', model='etk800')

    pos = (-0.3, 1, 1.0)
    direction = (0, 1, 0)
    fov = 120
    resolution = (64, 64)

    reference_camera = Camera(pos, direction, fov, resolution, colour=True)
    vehicle.attach_sensor('reference_camera', reference_camera)

    noise_camera = Camera(pos, direction, fov, resolution, colour=True)
    noise_camera = WhiteGaussianRGBNoise(noise_camera, .5, 0)
    vehicle.attach_sensor('noise_cam', noise_camera)

    scenario.add_vehicle(vehicle, pos=(-717.121, 101, 118.675), rot=(0, 0, 45))
    scenario.make(beamng)

    with beamng as bng:
        bng.load_scenario(scenario)
        bng.step(120)
        vehicle.poll_sensors()

        noise_img = np.asarray(noise_camera.data['colour'])
        reference_img = np.asarray(reference_camera.data['colour'])
        # since this is based on two different renders this will always be different
        assert (not (np.array_equal(noise_img, reference_img)))
Esempio n. 28
0
def main():
    random.seed(1703)
    setup_logging()

    beamng = BeamNGpy('localhost', 64256)

    scenario = Scenario('west_coast_usa', 'lidar_demo',
                        description='Spanning the map with a lidar sensor')

    vehicle = Vehicle('ego_vehicle', model='etk800',
                      licence='RED', color='Red')

    lidar = Lidar(offset=(0, 0, 1.6))
    vehicle.attach_sensor('lidar', lidar)

    scenario.add_vehicle(vehicle, pos=(-717.121, 101, 118.675), rot=(0, 0, 45))
    scenario.make(beamng)

    bng = beamng.open(launch=True)
    try:
        bng.set_deterministic()  # Set simulator to be deterministic
        bng.set_steps_per_second(60)  # With 60hz temporal resolution

        bng.load_scenario(scenario)
        bng.hide_hud()
        bng.start_scenario()

        vehicle.ai_set_mode('span')
        print('Driving around for 60 seconds...')
        sleep(60)
    finally:
        bng.close()
Esempio n. 29
0
def test_gforces(beamng):
    with beamng as bng:
        scenario = Scenario('west_coast_usa', 'gforce_test')
        vehicle = Vehicle('test_car', model='etk800')

        gforces = GForces()
        vehicle.attach_sensor('gforces', gforces)

        scenario.add_vehicle(vehicle,
                             pos=(-717.121, 101, 118.675),
                             rot=(0, 0, 45))
        scenario.make(beamng)

        gx = []
        gy = []
        bng.load_scenario(scenario)
        bng.start_scenario()
        bng.step(120)

        vehicle.ai_set_aggression(2)
        vehicle.ai_set_mode('span')

        for _ in range(64):
            bng.step(30)
            vehicle.poll_sensors()
            gx.append(gforces.data['gx'])
            gy.append(gforces.data['gy'])

    assert np.var(gx) > 1 and np.var(gy) > 1
Esempio n. 30
0
def test_noise(beamng):
    with beamng as bng:
        scenario = Scenario('west_coast_usa', 'camera_test')
        vehicle = Vehicle('test_car', model='etk800')

        pos = (-0.3, 1, 1.0)
        direction = (0, 1, 0)
        fov = 120
        resolution = (64, 64)

        cam = Camera(pos, direction, fov, resolution, colour=True, depth=True)
        noise_cam = RandomImageNoise(cam)
        vehicle.attach_sensor('noise_cam', noise_cam)

        lidar = Lidar()
        noise_lidar = RandomLIDARNoise(lidar, mean=0, var=.5)
        vehicle.attach_sensor('noise_lidar', noise_lidar)

        scenario.add_vehicle(vehicle,
                             pos=(-717.121, 101, 118.675),
                             rot=(0, 0, 45))
        scenario.make(beamng)

        bng.load_scenario(scenario)
        bng.step(120)
        time.sleep(20)
        vehicle.poll_sensors()

        reference_img = np.array(noise_cam._sensor.data['colour'])
        noise_img = np.array(noise_cam.data['colour'])
        assert (not (np.array_equal(noise_img, reference_img)))

        ref_pc = lidar.data['points']
        noise_pc = noise_lidar.data['points']
        assert (not (np.array_equal(ref_pc, noise_pc)))