### Basic BeamNGpy Usage Example Source: https://github.com/beamng/beamngpy/blob/master/README.md A basic example demonstrating how to set up a scenario, spawn a vehicle, and start the simulator. Ensure BeamNG.tech is installed and accessible via the BNG_HOME environment variable or specified path. ```python from beamngpy import BeamNGpy, Scenario, Vehicle # Instantiate BeamNGpy instance running the simulator from the given path, # communicating over localhost:25252 bng = BeamNGpy('localhost', 25252, home='/path/to/bng/tech', user='/path/to/bng/tech/userfolder') # Launch BeamNG.tech bng.open() # Create a scenario in west_coast_usa called 'example' scenario = Scenario('west_coast_usa', 'example') # Create an ETK800 with the licence plate 'PYTHON' vehicle = Vehicle('ego_vehicle', model='etk800', license='PYTHON') # Add it to our scenario at this position and rotation scenario.add_vehicle(vehicle, pos=(-717, 101, 118), rot_quat=(0, 0, 0.3826834, 0.9238795)) # Place files defining our scenario for the simulator to read scenario.make(bng) # Load and start our scenario bng.scenario.load(scenario) bng.scenario.start() # Make the vehicle's AI span the map vehicle.ai.set_mode('traffic') input('Hit Enter when done...') # Disconnect BeamNG bng.disconnect() # Or close the simulator # bng.close() ``` -------------------------------- ### start Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Starts the scenario, optionally restricting actions. ```APIDOC ## start(restrict_actions: bool | None = None) ### Description Starts the scenario; equivalent to clicking the “Start” button in the game after loading a scenario. This method blocks until the countdown to the scenario’s start has finished. ### Parameters #### Path Parameters - **restrict_actions** (bool | None) - Optional - Whether to keep scenario restrictions, such as limited menu options and controls. If None, defaults to the value set in the current Scenario object. ### Return type None ``` -------------------------------- ### Install documentation dependencies Source: https://github.com/beamng/beamngpy/blob/master/docs/README.md Install the required Python packages for building the documentation. ```bash pip install -r docs/source/requirements.txt ``` -------------------------------- ### Configure and Start Simulation Source: https://github.com/beamng/beamngpy/blob/master/examples/annotation_bounding_boxes.ipynb Sets the simulation's temporal resolution to 60 Hz, loads the created scenario, and starts the simulation. The ego vehicle is then switched to. ```python bng.settings.set_deterministic(60) # Set simulator to 60 Hz temporal resolution bng.scenario.load(scenario) bng.scenario.start() ego.switch() ``` -------------------------------- ### Load and Start Scenario Source: https://github.com/beamng/beamngpy/blob/master/examples/vehicle_state_plotting.ipynb Initializes the scenario within the simulator and triggers the start sequence. ```python beamng.scenario.load(scenario) beamng.scenario.start() # After loading, the simulator waits for further input to actually start ``` -------------------------------- ### beamng.scenario.start Source: https://github.com/beamng/beamngpy/blob/master/examples/feature_overview.ipynb Starts the loaded scenario. ```APIDOC ## beamng.scenario.start ### Description Starts the scenario; equivalent to clicking the "Start" button in the game after loading a scenario. This method blocks until the countdown to the scenario's start has finished. ### Parameters #### Request Body - **restrict_actions** (bool) - Optional - Whether to keep scenario restrictions, such as limited menu options and controls. Defaults to False. ``` -------------------------------- ### Run Development Server Source: https://github.com/beamng/beamngpy/blob/master/src/beamngpy/tools/template_car/README.md Start the FastAPI development server from the project root. ```bash cd beamngpy fastapi dev src/beamngpy/tools/template_car/api.py ``` -------------------------------- ### Initialize Scenario and Vehicle Source: https://github.com/beamng/beamngpy/blob/master/examples/feature_overview.ipynb Example demonstrating the creation of a scenario, adding a vehicle, and generating the scenario files. ```python scenario = Scenario("italy", "beamngpy_feature_overview") ego = Vehicle("ego", model="etk800", color="White", license="PYTHON") scenario.add_vehicle( ego, pos=(245.11, -906.94, 247.46), rot_quat=(0.0010, 0.1242, 0.9884, -0.0872) ) scenario.make(beamng) ``` -------------------------------- ### Start scenario and configure AI Source: https://github.com/beamng/beamngpy/blob/master/examples/scenario_control.ipynb Starts the simulation and sets the player vehicle to traffic mode with a defined speed. ```python beamng.scenario.start() player.ai.set_mode("traffic") player.ai.set_speed(80 / 3.6) ``` -------------------------------- ### Load and start the scenario Source: https://github.com/beamng/beamngpy/blob/master/examples/access_road_network.ipynb Loads the previously created scenario into the BeamNG simulator and starts its execution. The simulation needs to be running to fetch data. ```python beamng.scenario.load(scenario) beamng.scenario.start() ``` -------------------------------- ### Load and start the scenario Source: https://github.com/beamng/beamngpy/blob/master/examples/multi_client.ipynb Loads the previously defined scenario into the simulator via Client A and then starts the simulation. This makes the scenario active and ready for vehicle control. ```python client_a.scenario.load(scenario) client_a.scenario.start() ``` -------------------------------- ### BeamNGpy.open() - Start and Connect to BeamNG.tech Source: https://github.com/beamng/beamngpy/blob/master/examples/feature_overview.ipynb This method starts a BeamNG.tech process, opens a server socket, and waits for the spawned process to connect. It blocks until the process is ready. You can optionally provide extensions to load, control whether to launch a new process or connect to an existing one, and configure error handling for Lua scripts. ```APIDOC ## BeamNGpy.open() ### Description Starts a BeamNG.* process, opens a server socket, and waits for the spawned BeamNG.* process to connect. This method blocks until the process started and is ready. ### Method `open` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python beamng = BeamNGpy("localhost", 25252) beamng.open() ``` ### Response #### Success Response (200) Returns an instance of `BeamNGpy`. #### Response Example ``` ``` ### Error Handling - If `crash_lua_on_error` is True, BeamNG will not respond to BeamNGpy requests when a Lua error occurs and will print the stacktrace instead. This is only applicable when the process is launched by BeamNGpy. ### Arguments - **extensions** (List[str] | None): A list of non-default BeamNG Lua extensions to be loaded on start. - **launch** (bool): Whether to launch a new process or connect to a running one on the configured host/port. Defaults to True. - **crash_lua_on_error** (bool | None): If True, sets BeamNG to not respond to BeamNGpy requests when a Lua error happens and prints the stacktrace instead. Defaults to False. - **listen_ip** (str): The IP address that the BeamNG process will be listening on. Only relevant when `launch` is True. Set to `*` if you want BeamNG to listen on ALL network interfaces. Defaults to '127.0.0.1'. - ***args** (str): Additional string arguments. - ****opts** (str): Additional keyword options. ``` -------------------------------- ### Ultrasonic Sensor Example Usage Source: https://github.com/beamng/beamngpy/blob/master/examples/feature_overview.ipynb Example of how to initialize, use, and remove an ultrasonic sensor. ```APIDOC ## Ultrasonic Sensor Example ### Description This example demonstrates initializing an Ultrasonic sensor, setting up the vehicle, polling for data, and removing the sensor. ### Code Example ```python # Initialize the sensor ultrasonic = Ultrasonic("ultrasonic1", beamng, ego) # Configure the vehicle and environment ego.ai.set_mode("disabled") ego.teleport(pos=(464.23, 1504.52, 139.23), rot_quat=(0, 0, 0, 1), reset=True) ego.set_shift_mode("arcade") ego.control(throttle=0.1) # Poll for sensor data and print distance for _ in range(20): ultrasonic_data = ultrasonic.poll() print("Distance to obstacle:", ultrasonic_data["distance"]) beamng.step(30) # Remove the sensor when done ultrasonic.remove() ``` ### Output Example ``` Distance to obstacle: 9999.900390625 Distance to obstacle: 9999.900390625 ... Distance to obstacle: 2.137571096420288 ``` ``` -------------------------------- ### Registering and loading the mod Source: https://github.com/beamng/beamngpy/blob/master/examples/modInterface/using_mods_with_bngpy.ipynb Reconnect to the simulator with the specified extensions and start the scenario. ```python beamng.disconnect() beamng.open(extensions=["util/gameEngineCode"]) ``` ```python scenario.make(beamng) beamng.scenario.load(scenario) beamng.scenario.start() ``` -------------------------------- ### Add Vehicle and Start Scenario Source: https://github.com/beamng/beamngpy/blob/master/examples/radar_analysis.ipynb Adds the configured vehicle to the scenario at a specific position and orientation, generates necessary scenario files, loads the scenario in BeamNG, and starts the simulation with deterministic settings and a fixed step rate. ```python scenario.add_vehicle(vehicle, pos=(-767.1, 402.8, 142.8), rot_quat=(0, 0, 0.027, 1)) scenario.make(beamng) beamng.scenario.load(scenario) beamng.settings.set_deterministic() beamng.settings.set_steps_per_second(60) beamng.scenario.start() ``` -------------------------------- ### Install BeamNGpy using pip Source: https://github.com/beamng/beamngpy/blob/master/README.md Install the BeamNGpy library using pip. This is the standard method for most Python environments. ```bash pip install beamngpy ``` -------------------------------- ### TemplateCarGenerator.install_path Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Property that returns the path to the BeamNG installation folder. ```APIDOC ## install_path: str ### Description Return path to BeamNG install folder. ### Return type str ``` -------------------------------- ### start_recording Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Starts the recording of the vehicle's actions. ```APIDOC ## start_recording() -> None ### Description Starts the recording of the vehicle's actions. ### Return type None ``` -------------------------------- ### Example Usage: Attaching Sensors and Adding Vehicle Source: https://github.com/beamng/beamngpy/blob/master/examples/feature_overview.ipynb Demonstrates how to create vehicle, attach sensors (Electrics, Damage, Timer), and add the vehicle to a scenario. ```APIDOC ```python # Assuming 'scenario' is an initialized Scenario object ego = Vehicle("ego", model="etk800", color="White", licence="PYTHON") electrics = Electrics() damage = Damage() timer = Timer() ego.sensors.attach("electrics", electrics) ego.sensors.attach("damage", damage) ego.sensors.attach("timer", timer) scenario.add_vehicle( ego, pos=(-696.25, -1330.46, 140.48), rot_quat=(0.0000, 0.0000, 0.8567, -0.5154) ) # To remove the vehicle later: # scenario.remove_vehicle(ego) ``` ``` -------------------------------- ### Add vehicles to scenario, make, load, and start simulation Source: https://github.com/beamng/beamngpy/blob/master/examples/advanced_comfort_analysis.ipynb Adds the created vehicles to the scenario at specified positions and orientations. Generates scenario files, loads the scenario into the simulator, and starts the simulation with deterministic settings and a fixed step rate. ```python scenario.add_vehicle(careful, pos=(-767.1, 402.8, 142.8), rot_quat=(0, 0, 0.027, 1)) scenario.add_vehicle(aggressive, pos=(-770.1, 398.8, 142.8), rot_quat=(0, 0, 0.027, 1)) scenario.make(beamng) beamng.scenario.load(scenario) beamng.settings.set_deterministic() beamng.settings.set_steps_per_second(60) beamng.scenario.start() ``` -------------------------------- ### Initialize and connect Client B Source: https://github.com/beamng/beamngpy/blob/master/examples/multi_client.ipynb Initializes the second BeamNGpy client (Client B) to connect to the same simulator instance. Crucially, `launch=False` prevents Client B from starting its own simulator process. It then retrieves the active scenario and vehicles, attaching an Electrics sensor to 'vehicleA' and connecting both vehicles to Client B. ```python client_b = BeamNGpy("localhost", 25252) client_b.open(launch=False) running_scenario = client_b.scenario.get_current() print(running_scenario.name) active_vehicles = client_b.vehicles.get_current() bv_a = active_vehicles["vehicleA"] bv_b = active_vehicles["vehicleB"] # B attaches their own sensor to get the current controls of A bv_a.sensors.attach("electrics", Electrics()) bv_a.connect(client_b) bv_b.connect(client_b) ``` -------------------------------- ### Inspect BeamNGpy.open method documentation Source: https://github.com/beamng/beamngpy/blob/master/examples/feature_overview.ipynb Use the IPython help operator to view the documentation for the open method used to start the simulation. ```python ?BeamNGpy.open ``` -------------------------------- ### Setup BeamNGpy Simulation and Scenario Source: https://github.com/beamng/beamngpy/blob/master/examples/annotation_bounding_boxes.ipynb Initializes the BeamNGpy simulator and sets up a scenario with multiple vehicles. Vehicles are added to the scenario at specific positions and orientations. ```python # Start up the simulator. bng = BeamNGpy("localhost", 25252) bng.open(launch=True) scenario = Scenario("italy", "annotation_bounding_boxes") # Create some vehicles which will appear in the camera images. ego = Vehicle("ego", model="etk800", color="White") scenario.add_vehicle( ego, pos=(237.90, -894.42, 246.10), rot_quat=(0.0173, -0.0019, -0.6354, 0.7720) ) car1 = Vehicle("car1", model="etk800", color="Green") scenario.add_vehicle( car1, pos=(246.94, -901.64, 247.58), rot_quat=(-0.0099, 0.0206, 0.9348, -0.3543) ) car2 = Vehicle("car2", model="etk800", color="Red") scenario.add_vehicle( car2, pos=(276.27, -881.42, 247.84), rot_quat=(-0.0106, 0.0405, 0.4845, 0.8738) ) car3 = Vehicle("car3", model="etki", color="Blue") scenario.add_vehicle( car3, pos=(261.52, -894.68, 248.04), rot_quat=(0.0026, 0.01758, -0.8344, 0.5508) ) car4 = Vehicle("car4", model="miramar", color="Black") scenario.add_vehicle( car4, pos=(267.06, -892.03, 248.32), rot_quat=(0.0065, 0.0194, -0.8501, 0.5262) ) # Create the files required for the scenario. scenario.make(bng) ``` -------------------------------- ### Initialize and Use Ultrasonic Sensor Source: https://github.com/beamng/beamngpy/blob/master/examples/feature_overview.ipynb This example demonstrates how to initialize an Ultrasonic sensor, set up a vehicle's state, and then poll the sensor data in a loop. It prints the detected distance to obstacles and steps the simulation forward. ```python ultrasonic = Ultrasonic("ultrasonic1", beamng, ego) ego.ai.set_mode("disabled") ego.teleport(pos=(464.23, 1504.52, 139.23), rot_quat=(0, 0, 0, 1), reset=True) ego.set_shift_mode("arcade") ego.control(throttle=0.1) for _ in range(20): ultrasonic_data = ultrasonic.poll() print("Distance to obstacle:", ultrasonic_data["distance"]) beamng.step(30) ``` -------------------------------- ### Load a scenario Source: https://github.com/beamng/beamngpy/blob/master/examples/scenario_control.ipynb Use the load function to start a scenario in the simulation. It accepts a Scenario instance as an argument. ```python ?beamng.scenario.load ``` -------------------------------- ### Import Required Libraries Source: https://github.com/beamng/beamngpy/blob/master/examples/annotation_bounding_boxes.ipynb Imports necessary libraries for BeamNGpy, plotting, and numerical operations. Ensure these are installed before running the example. ```python %matplotlib inline import matplotlib.pyplot as plt import numpy as np from beamngpy import BeamNGpy, Scenario, Vehicle from beamngpy.sensors import Camera from time import sleep ``` -------------------------------- ### Set Up Logging Source: https://github.com/beamng/beamngpy/blob/master/CHANGELOG.rst Use set_up_simple_logging and config_logging for logging configuration, as setup_logging is superseded. ```python beamngpy.set_up_simple_logging(level=log_level, filename=log_filename, rotation_max_bytes=log_rotation_max_bytes, rotation_backup_count=log_rotation_backup_count) ``` -------------------------------- ### set_up Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Sets the up vector of the sensor. ```APIDOC ## set_up(up: Float3) ### Description Sets the current up vector of this sensor. ### Parameters #### Path Parameters - **up** (Float3) - Required - The new up vector. ### Returns - None ``` -------------------------------- ### Dynamically Identify Player Vehicle and Start Source: https://github.com/beamng/beamngpy/blob/master/examples/scenario_control.ipynb Retrieves the player vehicle ID dynamically for flowgraph scenarios and starts the simulation. ```python player_vid = beamng.vehicles.get_player_vehicle_id()["vid"] player = vehicles[player_vid] ``` ```python beamng.scenario.start() player.control(steering=0.2) ``` -------------------------------- ### open Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Establishes a connection to a BeamNG.tech instance. It can connect to an existing instance or launch a new one if specified. Configuration options for launching and debugging are available. ```APIDOC ## open(extensions: List[str] | None = None, *args: str, launch: bool = True, debug: bool | None = None, listen_ip: str = '127.0.0.1', **opts: str) -> BeamNGpy ### Description Open a connection to a BeamNG.tech instance. This method blocks until the connection is established. First, it tries to connect to an existing instance on the given host/port. If no instance is found, it will start a new one if the `launch` argument is True. ### Parameters * **extensions** (*List* *[*str*]* *|* *None*) – A list of non-default BeamNG Lua extensions to be loaded on start. * **args** (*str*) – Additional arguments to pass when launching a new process. * **launch** (*bool*) – Whether to launch a new process. Defaults to True. * **debug** (*bool* *|* *None*) – If True, then sets BeamNG.tech communication to debug mode. That means: > 1. BeamNG will not respond to BeamNGpy requests when a Lua error > happens and prints the stacktrace instead. > 2. The `techCapture.*.log` files are created automatically in the userfolder, > they log every protocol call and can be replayed using the `tech/capturePlayer` > Lua extension. This option is applicable only when the process is launched by this instance of BeamNGpy, as it sets a launch argument of the process. Defaults to False. * **listen_ip** (*str*) – The IP address that the BeamNG process will be listening on. Only relevant when `launch` is True. Set to `*` if you want BeamNG to listen on ALL network interfaces. * **opts** (*str*) – Additional key-value options to pass when launching a new process. ### Return type BeamNGpy ``` -------------------------------- ### Build all documentation versions Source: https://github.com/beamng/beamngpy/blob/master/docs/README.md Build documentation for all versions using sphinx-multiversion and set up the root index. ```bash cd docs sphinx-multiversion source build cp root_template.html build/index.html ``` -------------------------------- ### Install BeamNGpy using conda Source: https://github.com/beamng/beamngpy/blob/master/README.md Install the BeamNGpy library from the conda-forge channel using conda. This is recommended if you are using the Anaconda or Miniconda distribution. ```bash conda install beamngpy -c conda-forge ``` -------------------------------- ### Initializing the simulator Source: https://github.com/beamng/beamngpy/blob/master/examples/modInterface/using_mods_with_bngpy.ipynb Connect to the BeamNG.tech instance to determine the user path. ```python # open the simulator to find out the user path beamng = BeamNGpy("localhost", 25252) beamng.open() ``` -------------------------------- ### Initialize BeamNGpy and scenario Source: https://github.com/beamng/beamngpy/blob/master/examples/powertrain_data.ipynb Establishes a connection to the BeamNGpy simulator and sets up a new scenario named 'powertrain_analysis' on the 'west_coast_usa' map. Two 'etk800' vehicles are created with distinct names and licenses. ```python beamng = BeamNGpy("localhost", 25252) beamng.open() scenario = Scenario("west_coast_usa", "powertrain_analysis") careful = Vehicle("careful", model="etk800", license="CAREFUL", color="Green") aggressive = Vehicle("aggressive", model="etk800", license="AGGRO", color="Red") ``` -------------------------------- ### Timer Sensor Initialization Source: https://github.com/beamng/beamngpy/blob/master/examples/feature_overview.ipynb Initializes the Timer sensor, used to track the time elapsed since the simulation started. It handles simulation pausing correctly and provides time in seconds relative to the scenario start. ```python timer = Timer() ``` -------------------------------- ### Initialize Multishot Camera Environment Source: https://github.com/beamng/beamngpy/blob/master/examples/multishot_camera.ipynb Sets up the BeamNGpy simulator, spawns a vehicle, and initializes the camera sensor with helper functions for coordinate calculations. ```python %matplotlib inline import matplotlib.pyplot as plt import numpy as np from beamngpy import BeamNGpy, Scenario, Vehicle from beamngpy.sensors import Camera from time import sleep def get_bounding_box_center(bbox): rbl = np.array(bbox["rear_bottom_left"]) fbr = np.array(bbox["front_bottom_right"]) rtl = np.array(bbox["rear_top_left"]) center = rbl + ((fbr - rbl) / 2) + ((rtl - rbl) / 2) return center def rotate(vec, h, v): rot_x = np.cos(h) * vec[0] - np.sin(h) * vec[1] rot_y = np.sin(h) * vec[0] + np.cos(h) * vec[1] rot_z = np.sin(v) * rot_y + np.cos(v) * vec[2] return np.array([rot_x, rot_y, rot_z]) # Start the simulator. beamng = BeamNGpy("localhost", 25252) beamng.open() # Create a vehicle. vehicle = Vehicle("ego_vehicle", model="etki", license="PYTHON", color="Green") # Create a scenario. scenario = Scenario( "tech_ground", "multishot", description="Demo of the camera sensor used like a multishot camera", ) scenario.add_vehicle(vehicle) scenario.make(beamng) beamng.scenario.load(scenario) beamng.scenario.start() camera = Camera( "camera1", beamng, vehicle ) # Create a default camera sensor, attached to the vehicle. center = get_bounding_box_center(vehicle.get_bbox()) center[1] -= 0.75 # An offset to move center back a bit to get more of the vehicle. pos_offset = center + np.array( [3.5, 0, 0] ) # An offset to move the camera a few metres in front of the center. variations = [np.radians(a) for a in [-10, 0, 10]] ``` -------------------------------- ### Initialize and open Client A Source: https://github.com/beamng/beamngpy/blob/master/examples/multi_client.ipynb Initializes the first BeamNGpy client (Client A) to connect to the simulator on localhost and port 25252, then opens the connection. This client will be responsible for launching the simulator and creating the scenario. ```python client_a = BeamNGpy("localhost", 25252) client_a.open() ``` -------------------------------- ### Initialize and run BeamNG simulation Source: https://github.com/beamng/beamngpy/blob/master/examples/roads_plot.ipynb Sets up the BeamNGpy instance, scenario, and vehicle, then runs the animation loop. ```python if __name__ == "__main__": set_up_simple_logging() # Start up the simulator. bng = BeamNGpy("localhost", 25252) bng.open(launch=True) scenario = Scenario( "italy", "roads_sensor_demo", description="Spanning the map with the roads sensor", ) vehicle = Vehicle("ego_vehicle", model="etk800", license="RED", color="Red") scenario.add_vehicle( vehicle, pos=(-361.76326635601, 1169.0963008935, 168.6981158547), rot_quat=angle_to_quat((0, 0, 270)), ) scenario.make(bng) bng.settings.set_deterministic(60) # Set simulator to 60hz temporal resolution bng.scenario.load(scenario) bng.scenario.start() rs = RoadsSensor("rs1", bng, vehicle, physics_update_time=1.0) print("Collecting roads readings...") vehicle.ai.set_mode("traffic") sleep(3.0) fig, ax = plt.subplots() frames = [] # Create the animation frames for k in range(20): update() # Create the animation animation = FuncAnimation(fig, update, frames, interval=50) plt.show() # Close the simulation. print("to disconnect...") bng.disconnect() ``` -------------------------------- ### start_connection Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Establishes a connection for a vehicle with optional extensions. ```APIDOC ## start_connection ### Parameters #### Path Parameters - **vehicle** (Vehicle) - Required - **extensions** (List[str] | None) - Optional ### Returns StrDict ``` -------------------------------- ### AccApi.start Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Starts Adaptive Cruise Control (ACC) for a vehicle. ```APIDOC ## AccApi.start(vehid: str, sp: float, inputFlag: bool) -> None ### Description Starts ACC for the associated vehicle. This is an experimental feature. ### Parameters #### Path Parameters - **vehid** (str) - Required - The ID of the vehicle. - **sp** (float) - Required - The target speed of the vehicle when it doesn't follow an ACC-eligible preceding vehicle. - **inputFlag** (bool) - Required - Used for debugging purposes. ### Return type None ``` -------------------------------- ### Build current documentation version Source: https://github.com/beamng/beamngpy/blob/master/docs/README.md Build the documentation for the currently checked out version. ```bash cd docs sphinx-build -M html source build ``` -------------------------------- ### Initialize and Poll Camera Source: https://github.com/beamng/beamngpy/blob/master/examples/feature_overview.ipynb Create a camera instance and retrieve the most recent sensor readings. ```python camera = Camera( "camera1", beamng, ego, is_render_instance=True, is_render_annotations=True, is_render_depth=True, ) time.sleep(2) data = camera.poll() data ``` -------------------------------- ### BeamNGpy logging output Source: https://github.com/beamng/beamngpy/blob/master/examples/roads_plot.ipynb Example of the log output generated by the BeamNGpy library. ```text 2025-04-01 10:20:35,212 |INFO |beamngpy |Started BeamNGpy logging. ``` -------------------------------- ### Configuring Scenario and Vehicle Source: https://github.com/beamng/beamngpy/blob/master/examples/vehicle_state_plotting.ipynb Instantiates the BeamNGpy connection, attaches an Electrics sensor to the vehicle, and compiles the scenario. ```python # Instantiate a BeamNGpy instance the other classes use for reference & communication # This is the host & port used to communicate over beamng = BeamNGpy("localhost", 25252) beamng.open() # Create a vehile instance that will be called 'ego' in the simulation # using the etk800 model the simulator ships with vehicle = Vehicle("ego", model="etk800", license="PYTHON", color="Green") # Create an Electrics sensor and attach it to the vehicle electrics = Electrics() vehicle.sensors.attach("electrics", electrics) # Create a scenario called vehicle_state taking place in the west_coast_usa map the simulator ships with scenario = Scenario("west_coast_usa", "vehicle_state") # Add the vehicle and specify that it should start at a certain position and orientation. # The position & orientation values were obtained by opening the level in the simulator, # hitting F11 to open the editor and look for a spot to spawn and simply noting down the # corresponding values. # 45 degree rotation around the z-axis scenario.add_vehicle( vehicle, pos=(-717.121, 101, 118.675), rot_quat=angle_to_quat((0, 0, 45)) ) # The make function of a scneario is used to compile the scenario and produce a scenario file the simulator can load scenario.make(beamng) ``` -------------------------------- ### get_is_visualised Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Gets a flag indicating whether the ultrasonic sensor is currently visualized. ```APIDOC ## get_is_visualised() ### Description Gets a flag which indicates if this ultrasonic sensor is visualised or not. ### Returns - **bool**: A flag which indicates if this ultrasonic sensor is visualised or not. ``` -------------------------------- ### get_states Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Gets the states (position, direction, velocity) of specified vehicles in the simulator. ```APIDOC ## get_states ### Description Gets the states of the vehicles provided as the argument to this function. The returned state includes position, direction vectors and the velocities. ### Parameters #### Path Parameters - **vehicles** (Iterable[str]) - Required - A list of the vehicle IDs to query state from. ### Returns A mapping of the vehicle IDs to their state stored as a dictionary with `pos`, `dir`, `up`, `vel` keys. ### Return Type Dict[str, Dict[str, Float3]] ``` -------------------------------- ### SystemApi Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Provides an API for getting information about the host system running the simulator. ```APIDOC ## class beamngpy.api.beamng.SystemApi Bases: [`Api`](#beamngpy.api.beamng.Api) An API for getting info about the host system running the simulator. * **Parameters:** **beamng** ([*BeamNGpy*](#beamngpy.BeamNGpy)) – An instance of the simulator. ### get_environment_paths() Returns the environment filesystem paths of the BeamNG simulator. * **Returns:** A dictionary with the following keys: * `home`: The root directory of the simulator. * `user`: The directory of the user path. * **Return type:** StrDict ### get_info(os: bool = True, cpu: bool = False, gpu: bool = False, power: bool = False) Returns the information about the host’s system. * **Parameters:** * **os** (*bool*) – Whether to include information about the operating system of the host. * **cpu** (*bool*) – Whether to include information about the CPU of the host. * **gpu** (*bool*) – Whether to include information about the GPU of the host. * **power** (*bool*) – Whether to include information about the power options of the host. * **Return type:** StrDict ``` -------------------------------- ### beamngpy.logging.set_up_simple_logging Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Provides high-level control over BeamNG logging, setting up logging to sys.stderr and optionally to a file. ```APIDOC ## beamngpy.logging.set_up_simple_logging(log_file: str | None = None, redirect_warnings: bool = True, level: int = 20, log_communication: bool = False) -> None ### Description Helper function that provides high-level control over beamng logging. For low-level control over the logging system use [`config_logging()`](#beamngpy.logging.config_logging). Sets up logging to `sys.stderr` and optionally to a given file. Existing log files are moved to `.1`. By default beamngpy logs warnings and errors to `sys.stderr`, so this function is only of use, if the log output should additionaly be written to a file, or if the log level needs to be adjusted. ### Parameters #### Parameters - **log_file** (str | None) - Optional - log filename - **redirect_warnings** (bool) - Optional - Whether to redirect warnings to the logger. Beware that this modifies the warnings settings. - **level** (int) - Optional - log level of handler that is created for the log file. Defaults to `logging.INFO`. - **log_communication** (bool) - Optional - whether to log the BeamNGpy protocol messages between BeamNGpy and BeamNG.tech ### Return type None ``` -------------------------------- ### Verify Vehicle Connections and Start Scenario Source: https://github.com/beamng/beamngpy/blob/master/examples/scenario_control.ipynb Checks if vehicles are connected and initiates the scenario simulation. ```python player, opponent = vehicles["scenario_player0"], vehicles["scenario_crew"] assert player.is_connected() and opponent.is_connected(), "Vehicles not connected!" ``` ```python beamng.scenario.start() player.control(throttle=1.0) ``` -------------------------------- ### Initialize BeamNGpy and Create Scenario Source: https://github.com/beamng/beamngpy/blob/master/examples/object_placement.ipynb Establishes a connection to the BeamNG simulator and initializes a new scenario on the 'west_coast_usa' map with a specific name. ```python beamng = BeamNGpy("localhost", 25252) beamng.open() scenario = Scenario("west_coast_usa", "object_placement") ``` -------------------------------- ### stream Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Gets the streamed LiDAR point cloud data from the associated shared memory location. ```APIDOC ## stream() -> StrDict ### Description Gets the streamed LiDAR point cloud data from the associated shared memory location. ### Returns - **StrDict** - The LiDAR point cloud data. ``` -------------------------------- ### LoggingApi Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Manages in-game logging for vehicle data, including starting, stopping, and configuring logging options. ```APIDOC ## class beamngpy.api.vehicle.LoggingApi ### Description A base API class from which all the API communicating with a vehicle derive. ### Methods #### set_options_from_json(filename: str) -> None Updates the in game logging with the settings specified in the given file/json. The file is expected to be in the following location: // * **Parameters:** * **filename** (*str*) #### start(output_dir: str) -> None Starts in game logging. Beware that any data from previous logging sessions is overwritten in the process. * **Parameters:** * **output_dir** (*str*) – to avoid overwriting logging from other vehicles, specify the output directory, overwrites the output_dir set through the json. The data can be found in: // #### stop() -> None Stops in game logging. #### write_options_to_json(filename: str = 'template.json') -> None Writes all available options from the in-game-logger to a json file. The purpose of this functionality is to facilitate the acquisition of a valid template to adjust the options/settings of the in game logging as needed. Depending on the executable used the file can be found at the following location: // * **Parameters:** * **filename** (*str*) – not the absolute file path but the name of the json ``` -------------------------------- ### Upgrade BeamNGpy using pip Source: https://github.com/beamng/beamngpy/blob/master/README.md Upgrade an existing BeamNGpy installation to the latest version using pip. ```bash pip install --upgrade beamngpy ``` -------------------------------- ### Initialize BeamNGpy and Scenario Source: https://github.com/beamng/beamngpy/blob/master/examples/radar_analysis.ipynb Initializes the BeamNGpy connection, creates a new scenario, and sets up a vehicle with specified model, license, and color. ```python beamng = BeamNGpy("localhost", 25252) beamng.open() scenario = Scenario("west_coast_usa", "radar_analysis") vehicle = Vehicle("vehicle1", model="etk800", license="RADAR", color="Blue") ``` -------------------------------- ### Import necessary libraries Source: https://github.com/beamng/beamngpy/blob/master/examples/access_road_network.ipynb Imports required classes from beamngpy, matplotlib, and shapely. Ensure these libraries are installed. ```python from beamngpy import BeamNGpy, Scenario, Vehicle from matplotlib import pyplot as plt from shapely.geometry import MultiLineString ``` -------------------------------- ### Creating and Loading a Scenario Source: https://github.com/beamng/beamngpy/blob/master/examples/vehicle_road_bounding_box.ipynb Configures the BeamNGpy instance, defines the road geometry, places the vehicle, and initializes the camera sensor. ```python beamng = BeamNGpy("localhost", 25252) beamng.open() scenario = Scenario("gridmap_v2", "vehicle_bbox_example") road = Road("track_editor_C_center", rid="main_road", texture_length=5) orig = (-107, 20, 100) goal = (-300, 20, 100) road.add_nodes((*orig, 7), (*goal, 7)) scenario.add_road(road) vehicle = Vehicle("ego_vehicle", model="etk800", license="PYTHON") scenario.add_vehicle(vehicle, pos=(-104.30, 20.37, 100.21), rot_quat=(0, 0, 0.71, 0.71)) scenario.make(beamng) beamng.settings.set_deterministic(60) beamng.scenario.load(scenario) beamng.scenario.start() overhead = Camera( "overhead", beamng, vehicle, pos=(0, 10, 5), dir=(0, -1, -0.75), field_of_view_y=60, resolution=(1024, 1024), is_render_annotations=False ) ``` -------------------------------- ### Timer Sensor Source: https://github.com/beamng/beamngpy/blob/master/examples/feature_overview.ipynb The Timer sensor tracks the elapsed time since the simulation or scenario started, handling pauses correctly. ```APIDOC ## Timer Sensor ### Description Keeps track of the time elapsed since the simulation started, relative to the scenario start. The timer correctly handles simulation pauses, meaning time does not progress when the simulation is paused. ### Init Signature `Timer()` ### Polling When polled, this sensor provides the time in seconds since the start of the scenario in a dictionary under the ``time`` key. ### File c:\dev\beamngpy\src\beamngpy\sensors\timer.py ### Type type ``` -------------------------------- ### Initialize data storage lists Source: https://github.com/beamng/beamngpy/blob/master/examples/powertrain_data.ipynb Sets up empty lists to store the collected powertrain data (output torque and timestamps) for both the 'careful' and 'aggressive' vehicles. ```python careful_data_x = [] careful_data_y = [] careful_data_t = [] aggressive_data_x = [] aggressive_data_y = [] aggressive_data_t = [] ``` -------------------------------- ### Import necessary libraries Source: https://github.com/beamng/beamngpy/blob/master/examples/powertrain_data.ipynb Imports required libraries for plotting, data manipulation, and BeamNGpy interaction. Ensure these are installed before running. ```python %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from time import sleep from beamngpy import BeamNGpy, Scenario, Vehicle from beamngpy.sensors import PowertrainSensor sns.set_theme() ``` -------------------------------- ### poll Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Gets the most-recent readings for this sensor. Note: if this sensor was created with a negative update rate, then there may have been no readings taken. ```APIDOC ## poll() -> StrDict ### Description Gets the most-recent readings for this sensor. ### Returns - **StrDict** - A dictionary with the following keys: - **pointCloud** (dict) - The point cloud readings, as a dictionary of vectors. - **colours** (dict) - The semantic annotation data, as a dictionary of colours for each corresponding point in the point cloud. ### Notes If this sensor was created with a negative update rate, then there may have been no readings taken. ``` -------------------------------- ### GET /camera/get_full_poll_request Source: https://github.com/beamng/beamngpy/blob/master/examples/feature_overview.ipynb Performs a blocking request to retrieve a full set of camera data, including semantic and instance annotations. ```APIDOC ## GET /camera/get_full_poll_request ### Description Gets a full camera request (semantic annotation and instance annotation data included). NOTE: this function blocks the simulation until the data request is completed. ### Response #### Success Response (200) - **data** (Dictionary) - The camera data as images. ``` -------------------------------- ### Initialize and Open BeamNGpy Source: https://github.com/beamng/beamngpy/blob/master/examples/feature_overview.ipynb Initializes the BeamNGpy instance and opens the connection to the simulator process. ```python beamng = BeamNGpy("localhost", 25252) beamng.open() ``` -------------------------------- ### get_launch_arguments Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Retrieves the command-line arguments used to launch the BeamNG simulator. This is useful for debugging or understanding the current simulation setup. ```APIDOC ## get_launch_arguments() ### Description Returns the full command-line that were or would be used to launch a BeamNG instance using this BeamNGpy object, including all command-line switches. ### Return type str ``` -------------------------------- ### POST /scenario/make Source: https://github.com/beamng/beamngpy/blob/master/examples/feature_overview.ipynb Generates the necessary files to describe the scenario and outputs them to the simulator. ```APIDOC ## POST /scenario/make ### Description Generates necessary files to describe the scenario in the simulation and outputs them to the simulator. ### Parameters #### Request Body - **bng** (BeamNGpy) - Required - The BeamNGpy instance to generate the scenario for. ``` -------------------------------- ### Initialize Vehicle AI Script Source: https://github.com/beamng/beamngpy/blob/master/examples/vehicle_road_bounding_box.ipynb Applies a script to a vehicle and advances the simulation to ensure the vehicle is correctly positioned at the start of the path. ```python vehicle.ai.set_script(script) beamng.control.pause() beamng.control.step(100) ``` -------------------------------- ### Initialize BeamNGpy Simulator Source: https://github.com/beamng/beamngpy/blob/master/examples/scenario_control.ipynb Establishes a connection to the BeamNG simulator instance running on the specified host and port. ```python from beamngpy import BeamNGpy, Scenario beamng = BeamNGpy("localhost", 25252) beamng.open() ``` -------------------------------- ### Get List of All Vehicle IDs Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Retrieve a list of all vehicle IDs that have been configured or generated. This is useful for managing multiple vehicle mods. ```python vehicle_ids = generator.get_vehicle_list() ``` -------------------------------- ### Create and Configure Vehicle with Sensors Source: https://github.com/beamng/beamngpy/blob/master/examples/feature_overview.ipynb Creates a new vehicle, attaches electrics, damage, and timer sensors to it, and then adds the vehicle to the scenario at a specified position and rotation. ```python ego = Vehicle("ego", model="etk800", color="White", licence="PYTHON") electrics = Electrics() damage = Damage() timer = Timer() ego.sensors.attach("electrics", electrics) ego.sensors.attach("damage", damage) ego.sensors.attach("timer", timer) scenario.add_vehicle( ego, pos=(-696.25, -1330.46, 140.48), rot_quat=(0.0000, 0.0000, 0.8567, -0.5154) ) ``` -------------------------------- ### Retrieve a Specific Template Vehicle Source: https://github.com/beamng/beamngpy/blob/master/docs/source/beamngpy.md Get a TemplateVehicle object by its unique ID. This allows for programmatic access and modification of vehicle parameters. ```python vehicle_data = generator.get_vehicle(vehicle_id='my_custom_car') ```