Beispiel #1
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()
Beispiel #2
0
def test_camera(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)
    front_camera = Camera(pos,
                          direction,
                          fov,
                          resolution,
                          colour=True,
                          depth=True,
                          annotation=True)
    vehicle.attach_sensor('front_cam', front_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)

        sensors = bng.poll_sensors(vehicle)

        assert_image_different(sensors['front_cam']['colour'])
        assert_image_different(sensors['front_cam']['depth'])
        assert_image_different(sensors['front_cam']['annotation'])
Beispiel #3
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
    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()
Beispiel #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)
Beispiel #6
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
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()
Beispiel #8
0
    def run(self, debug=False):
        try:
            self.vehicle = Vehicle(car_model['id'])
            electrics = Electrics()
            self.vehicle.attach_sensor('electrics', electrics)

            # Connect to running beamng
            self.bng = BeamNGpy(
                'localhost', 64256
            )  #, home='C://Users//Alessio//BeamNG.research_unlimited//trunk')
            self.bng = self.bng.open(launch=False)

            # Put simulator in pause awaiting while planning the driving
            self.bng.pause()
            # Connect to the existing vehicle (identified by the ID set in the vehicle instance)
            self.bng.set_deterministic()  # Set simulator to be deterministic
            self.bng.connect_vehicle(self.vehicle)
            assert self.vehicle.skt

            # Get Initial state of the car. This assumes that the script is invoked after the scenario is started
            self.bng.poll_sensors(self.vehicle)
            # Compute the "optimal" driving path and program the ai_script
            self._compute_driving_path(self.vehicle.state,
                                       self.road_model['street'])

            self.script = self.road_profiler.compute_ai_script(
                LineString(self.driving_path), self.car_model)

            # Enforce initial car direction nad up
            start_dir = (self.vehicle.state['dir'][0],
                         self.vehicle.state['dir'][1],
                         self.vehicle.state['dir'][2])
            up_dir = (0, 0, 1)

            # Configure the ego car
            self.vehicle.ai_set_mode('disabled')
            # Note that set script teleports the car by default
            self.vehicle.ai_set_script(self.script,
                                       start_dir=start_dir,
                                       up_dir=up_dir)
            # Resume the simulation
            self.bng.resume()
            # At this point the controller can stop ? or wait till it is killed

            while True:
                if debug:
                    self.bng.pause()
                    self.bng.poll_sensors(self.vehicle)
                    self.plot_all(self.vehicle.state)
                    self.bng.resume()
                # Progress the simulation for some time...
                # self.bng.step(50)
                sleep(2)

        except Exception:
            # When we brutally kill this process there's no need to log an exception
            l.error("Fatal Error", exc_info=True)
        finally:
            self.bng.close()
    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()
Beispiel #10
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
Beispiel #11
0
def create_vehicle(vehicle_objs):
    vehicles = []
    for v in vehicle_objs:
        # Creates vehicle with associated id and attaches damage sensor to each vehicle
        vehicle = Vehicle(str(v.id))
        damage = Damage()
        vehicle.attach_sensor('damage', damage)  # Attach Sensor
        vehicles.append(vehicle)
    return vehicles
 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"))
Beispiel #13
0
    def __init__(self, host='localhost', port=64256):
        self.steps = WCARaceGeometry.sps // WCARaceGeometry.rate
        self.host = host
        self.port = port

        self.action_space = self._action_space()
        self.observation_space = self._observation_space()

        self.episode_steps = 0
        self.spine = None
        self.l_edge = None
        self.r_edge = None
        self.polygon = None

        front_factor = WCARaceGeometry.front_dist / WCARaceGeometry.front_step
        trail_factor = WCARaceGeometry.trail_dist / WCARaceGeometry.trail_step
        self.front = lambda step: +front_factor * step
        self.trail = lambda step: -trail_factor * step

        self.bng = BeamNGpy(self.host, self.port)

        self.vehicle = Vehicle('racecar',
                               model='sunburst',
                               licence='BEAMNG',
                               colour='red',
                               partConfig='vehicles/sunburst/hillclimb.pc')

        electrics = Electrics()
        damage = Damage()
        self.vehicle.attach_sensor('electrics', electrics)
        self.vehicle.attach_sensor('damage', damage)

        scenario = Scenario('west_coast_usa', 'wca_race_geometry_v0')
        scenario.add_vehicle(self.vehicle,
                             pos=(394.5, -247.925, 145.25),
                             rot=(0, 0, 90))

        scenario.make(self.bng)

        self.bng.open(launch=True)
        self.bng.set_deterministic()
        self.bng.set_steps_per_second(WCARaceGeometry.sps)
        self.bng.load_scenario(scenario)

        self._build_racetrack()

        self.observation = None
        self.last_observation = None
        self.last_spine_proj = None

        self.bng.start_scenario()
        self.bng.pause()
Beispiel #14
0
def test_dynamic_vehicle_spawn(beamng):
    with beamng as bng:
        scenario = Scenario('smallgrid', 'dynamic spawn test')
        unique_vehicle_name = 'unique'
        vehicle = Vehicle(unique_vehicle_name, model='pickup')
        scenario.add_vehicle(vehicle, pos=(0, 0, 0), rot=(0, 0, 0))
        scenario.make(beamng)

        bng.load_scenario(scenario)
        bng.start_scenario()

        duplicate = Vehicle(unique_vehicle_name, model="etk800")
        assert not bng.spawn_vehicle(duplicate, (0, 10, 0), None)
Beispiel #15
0
def test_bboxes(beamng):
    with beamng as bng:
        scenario = Scenario('west_coast_usa', 'bbox_test')

        ego = Vehicle('ego', model='etk800', color='White')
        scenario.add_vehicle(ego,
                             pos=(-725.365, 92.4684, 118.437),
                             rot_quat=(-0.006, -0.0076, 0.921, -0.389))

        camera = Camera((-0.3, 1, 1), (0, 1, 0),
                        75, (1024, 1024),
                        colour=True,
                        depth=True,
                        annotation=True,
                        instance=True)
        ego.attach_sensor('camera', camera)

        car1 = Vehicle('car1', model='etk800', color='Green')
        scenario.add_vehicle(car1,
                             pos=(-710.76, 101.50, 118.56),
                             rot_quat=(-0.006, -0.0076, 0.921, -0.389))

        car2 = Vehicle('car2', model='etk800', color='Red')
        scenario.add_vehicle(car2,
                             pos=(-715.83, 96.69, 118.53),
                             rot_quat=(-0.006, -0.0076, 0.921, -0.389))

        car3 = Vehicle('car3', model='etki', color='Blue')
        scenario.add_vehicle(car3,
                             pos=(-696.96, 126.9, 118.44),
                             rot_quat=(0.0181, -0.0065, 0.3816, 0.924))

        car4 = Vehicle('car4', model='miramar', color='Black')
        scenario.add_vehicle(car4,
                             pos=(-708.58203, 115.326, 118.60),
                             rot_quat=(0.0181, -0.00645, 0.3818, 0.9240))

        scenario.make(beamng)

        bng.load_scenario(scenario)
        bng.step(120)
        time.sleep(5)

        ego.poll_sensors()

        classes = bng.get_annotation_classes(bng.get_annotations())
        annotation = ego.sensors['camera'].data['annotation']
        instance = ego.sensors['camera'].data['instance']
        bboxes = Camera.extract_bboxes(annotation, instance, classes)
        bboxes = [b for b in bboxes if b['class'] == 'CAR']
        assert len(bboxes) == 5
Beispiel #16
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
Beispiel #17
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
Beispiel #18
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)))
Beispiel #19
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)))
Beispiel #20
0
 def add_sensor_to(self, vehicle: Vehicle) -> None:
     from beamngpy.sensors import Camera
     from cmath import pi
     # NOTE rotation range: -pi to pi
     # NOTE Reference point is the point of the model
     # NOTE First rotate camera, then shift based on rotated axis of the camera
     # NOTE x-axis points rightwards, y-axis points forwards, z-axis points upwards
     # FIXME These values are specialized for etk800
     if self.direction is CameraDirection.FRONT:
         x_pos = -0.3
         y_pos = 2.1
         z_pos = 0.3
         x_rot = 0
         y_rot = pi
         z_rot = 0
     elif self.direction is CameraDirection.RIGHT:
         x_pos = 0
         y_pos = 0.5
         z_pos = 0.3
         x_rot = pi
         y_rot = 0
         z_rot = 0
     elif self.direction is CameraDirection.BACK:
         x_pos = 0
         y_pos = 2.6
         z_pos = 0.3
         x_rot = 0
         y_rot = -pi
         z_rot = 0
     elif self.direction is CameraDirection.LEFT:
         x_pos = 0
         y_pos = 1.2
         z_pos = 0.3
         x_rot = -pi
         y_rot = 0
         z_rot = 0
     elif self.direction is CameraDirection.DASH:
         x_pos = 0
         y_pos = 0.4
         z_pos = 1
         x_rot = 0
         y_rot = pi
         z_rot = 0
     else:
         _logger.warning("The camera direction " + str(self.direction.value) + " is not implemented.")
         return
     vehicle.attach_sensor(self.rid,
                           Camera((x_pos, y_pos, z_pos), (x_rot, y_rot, z_rot), self.fov, (self.width, self.height),
                                  colour=True, depth=True, annotation=False))
Beispiel #21
0
 def setup_vehicle(self) -> Vehicle:
     assert self.vehicle is None
     self.vehicle = Vehicle('ego_vehicle',
                            model='etk800',
                            licence='TIG',
                            color='Red')
     return self.vehicle
Beispiel #22
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)
def main():
    beamng = BeamNGpy('localhost', 64256)

    scenario = Scenario('smallgrid', 'mesh_test')

    cylinder = ProceduralCylinder(pos=(10, -10, 0),
                                  rot=(0, 0, 0),
                                  radius=3.5,
                                  height=5)
    scenario.add_procedural_mesh(cylinder)

    cone = ProceduralCone(pos=(-10, -10, 0),
                          rot=(45, 0, 0),
                          radius=3.5,
                          height=5)
    scenario.add_procedural_mesh(cone)

    cube = ProceduralCube(pos=(0, -20, 0),
                          rot=(0, 0, 0),
                          size=(5, 2, 3))
    scenario.add_procedural_mesh(cube)

    vehicle = Vehicle('ego_vehicle', model='etk800')
    scenario.add_vehicle(vehicle, pos=(0, 0, 0), rot=(0, 0, 0))

    scenario.make(beamng)

    bng = beamng.open(launch=True)
    try:
        bng.load_scenario(scenario)
        bng.start_scenario()
        input('Press enter when done...')
    finally:
        bng.close()
Beispiel #24
0
def traffic_vehicles(length):
    t1 = Vehicle('traffic1', model='etk800', licence='traffic1', color='White')
    t2 = Vehicle('traffic2', model='etk800', licence='traffic2', color='White')
    t3 = Vehicle('traffic3', model='etk800', licence='traffic3', color='White')
    t4 = Vehicle('traffic4', model='etk800', licence='traffic4', color='White')
    t5 = Vehicle('traffic5', model='etk800', licence='traffic5', color='White')
    t6 = Vehicle('traffic6', model='etk800', licence='traffic6', color='White')
    t7 = Vehicle('traffic7', model='etk800', licence='traffic7', color='White')
    t8 = Vehicle('traffic8', model='etk800', licence='traffic7', color='White')
    t9 = Vehicle('traffic9', model='etk800', licence='traffic7', color='White')
    t10 = Vehicle('traffic10',
                  model='etk800',
                  licence='traffic7',
                  color='White')
    tvs = [t1, t2, t3, t4, t5, t6, t7, t8, t9, t10]
    return tvs[0:length]
Beispiel #25
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
def setup_beamng(vehicle_model='etk800',
                 camera_pos=(-0.5, 0.38, 1.3),
                 camera_direction=(0, 1.0, 0),
                 pitch_euler=0.0):
    global base_filename, default_color, default_scenario, default_spawnpoint, steps_per_sec
    global integral, prev_error, setpoint
    integral = 0.0
    prev_error = 0.0

    # version==keras
    # sm = DAVE2Model()
    # model = sm.define_dual_model_BeamNG()
    # model = sm.load_weights("BeamNGmodel-racetrackdual-comparison100K-PIDcontrolset-2.h5")
    # model = sm.load_weights("BeamNGmodel-racetrackdual-comparison100K-PIDcontrolset-3-sanitycheckretraining-model.h5")
    # version==pytorch
    # model = torch.load("C:/Users/merie/Downloads/dave/test_model_20.pt", map_location=torch.device('cpu')).eval()
    # model = torch.load("F:/MODELS-FOR-MERIEL/models/model-100000D-1000B-100E-1p000000e-04LR-100.pt.pt", map_location=torch.device('cpu')).eval()
    # model = torch.load("F:/MODELS-FOR-MERIEL/models/model-292757D-1000B-100E-1p000000e-04LR-100.pt", map_location=torch.device('cpu')).eval()
    model = torch.load(
        "H:/GitHub/DAVE2-Keras/test7-trad-50epochs-64batch-1e4lr-ORIGDATASET-singleoutput-model.pt",
        map_location=torch.device('cpu')).eval()

    random.seed(1703)
    setup_logging()

    beamng = BeamNGpy('localhost',
                      64256,
                      home='H:/BeamNG.research.v1.7.0.1clean',
                      user='******')
    scenario = Scenario(default_scenario, 'research_test')
    vehicle = Vehicle('ego_vehicle',
                      model=vehicle_model,
                      licence='EGO',
                      color=default_color)
    vehicle = setup_sensors(vehicle,
                            pos=camera_pos,
                            direction=camera_direction)
    spawn = spawn_point(default_scenario, default_spawnpoint)
    scenario.add_vehicle(
        vehicle, pos=spawn['pos'], rot=None,
        rot_quat=spawn['rot_quat'])  #, partConfig=parts_config)
    add_barriers(scenario)
    add_qr_cubes(scenario)
    # Compile the scenario and place it in BeamNG's map folder
    scenario.make(beamng)

    # Start BeamNG and enter the main loop
    bng = beamng.open(launch=True)
    #bng.hide_hud()
    bng.set_deterministic()  # Set simulator to be deterministic
    bng.set_steps_per_second(steps_per_sec)  # With 60hz temporal resolution
    bng.load_scenario(scenario)
    bng.start_scenario()
    # Put simulator in pause awaiting further inputs
    bng.pause()
    assert vehicle.skt
    # bng.resume()
    # find_width_of_road(bng)
    return vehicle, bng, model
Beispiel #27
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
Beispiel #28
0
def test_multi_vehicle(beamng):
    """
    Test that a second client can connect to a running instance, check for
    active vehicles, connect to one, and control it
    """
    with beamng as a_client:
        scenario = Scenario('smallgrid', 'multi_vehicle')
        first = Vehicle('first', model='etk800')
        scenario.add_vehicle(first, pos=(2, 2, 0))
        second = Vehicle('second', model='etki')
        scenario.add_vehicle(second, pos=(-2, -2, 0))
        scenario.make(a_client)

        a_client.load_scenario(scenario)
        a_client.start_scenario()

        b_client = BeamNGpy('localhost', 64256)
        #  Do not deploy mod zip or launch new process
        b_client.open(deploy=False, launch=False)
        vehicles = b_client.get_current_vehicles()
        assert 'second' in vehicles
        vehicle = vehicles['second']
        vehicle.connect(b_client)
        assert vehicle.skt is not None

        a_veh = second
        b_veh = vehicle

        b_veh.control(throttle=1.0)

        for _ in range(8):
            # Verify position updating in both clients
            a_veh.poll_sensors()
            b_veh.poll_sensors()
            a_ref = a_veh.sensors['state'].data['pos']
            b_ref = b_veh.sensors['state'].data['pos']
            b_client.step(100)
            a_veh.poll_sensors()
            b_veh.poll_sensors()
            a_new = a_veh.sensors['state'].data['pos']
            b_new = b_veh.sensors['state'].data['pos']

            assert a_ref[0] != a_new[0] or a_ref[1] != a_new[1]
            assert b_ref[0] != b_new[0] or b_ref[1] != b_new[1]
Beispiel #29
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
Beispiel #30
0
def test_state(beamng):
    scenario = Scenario('smallgrid', 'vehicle_state_test')
    vehicle = Vehicle('test_car', model='pickup')

    state = State()
    vehicle.attach_sensor('state', state)

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

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

        sensors = bng.poll_sensors(vehicle)

        assert sensors["state"] != None
        assert vehicle.state == sensors["state"]