BeamNGpy Reference
BeamNGpy
API
Vehicle
Sensors
API
- class beamngpy.api.vehicle.AIApi(vehicle: Vehicle)
Bases:
VehicleApiAn API class gathering AI-related functionality.
- Parameters:
vehicle (Vehicle) – An instance of a vehicle object.
- drive_in_lane(lane: bool) None
Sets the drive in lane flag of the AI. If True, the AI only drives within the lane it can legally drive in.
- Parameters:
lane (bool) – Lane flag to set.
- Return type:
None
- execute_script(script, cling: bool = True, start_delay: float = 0.0, no_reset: bool = False) None
- Parameters:
cling (bool)
start_delay (float)
no_reset (bool)
- Return type:
None
- get_initial_spawn_position_orientation(script)
- set_aggression(aggr: float) None
- Parameters:
aggr (float)
- Return type:
None
- set_line(line: List[Dict[str, Float3 | float]], cling: bool = True) None
Makes the AI follow a given polyline. The line is specified as a list of dictionaries where each dictionary has a
posentry specifying the supposed position as an(x, y, z)triplet and aspeedentry specifying the speed in m/s.- Parameters:
line (List[Dict[str, Float3 | float]]) – Polyline as list of dicts as described above.
cling (bool) – Whether or not to align the
zcoordinate of the polyline to the ground.
- Return type:
None
- set_mode(mode: str) None
Sets the desired mode of the simulator’s built-in AI for this vehicle. Possible values are:
disabled: Turn the AI off (default state)random: Drive from random points to random points on the mapspan: Drive along the entire road network of the mapmanual: Drive to a specific waypoint, target set separatelychase: Chase a target vehicle, target set separatelyflee: Flee from a vehicle, target set separatelystopping: Make the vehicle come to a halt (AI disables itself once the vehicle stopped.)
Note
Some AI methods automatically set appropriate modes, meaning a call to this method might be optional.
- Parameters:
mode (str) – The AI mode to set.
- Return type:
None
- set_script(script: List[Dict[str, float]], cling: bool = True) None
Makes the vehicle follow a given “script” – a script being a list of timestamped positions defining where a vehicle should be at what time. This can be used to make the vehicle drive a long a polyline with speed implicitly expressed in the time between points.
- Parameters:
script (List[Dict[str, float]]) – A list of nodes in the script. Each node is expected to be a dict-like that has
x,y, andzentries for the supposed position of the vehicle, and atentry for the time of the node along the path. Time values are in seconds relative to the time when script playback is started.cling (bool) – A flag that makes the simulator cling z-coordinates to the ground. Since computing z-coordinates in advance without knowing the level geometry can be cumbersome, this flag is used to automatically set z-coordinates in the script to the ground height. Defaults to True.
- Return type:
None
Notes
The AI follows the given script the best it can. It cannot drive along scripts that would be physically impossible, e.g. specifying a script with points A & B one kilometer apart and giving it a a second between those points will make the AI drive from A to B as fast as it can, but unlikely to reach it in the given time. Furthermore, if the AI falls behind schedule, it will start skipping points in the script in an effort to make up for lost time.
- Raises:
BNGValueError – If the script has fewer than three nodes, the minimum length of a script.
- Parameters:
script (List[Dict[str, float]])
cling (bool)
- Return type:
None
- set_speed(speed: float, mode: str = 'limit') None
Sets the target speed for the AI in m/s. Speed can be maintained in two modes:
limit: Drive speeds between 0 and the limit, as the AIsees fit.
set: Try to maintain the given speed at all times.
- Parameters:
speed (float) – The target speed in m/s.
mode (str) – The speed mode.
- Return type:
None
- set_target(target: str, mode: str = 'chase') None
Sets the target to chase or flee. The target should be the ID of another vehicle in the simulation. The AI is automatically set to the given mode.
- Parameters:
target (str) – ID of the target vehicle as a string.
mode (str) – How the target should be treated.
chaseto chase the target,fleeto flee from it.
- Return type:
None
- set_waypoint(waypoint: str) None
Sets the waypoint the AI should drive to in manual mode. The AI gets automatically set to manual mode when this method is called.
- Parameters:
waypoint (str) – ID of the target waypoint as a string.
- Return type:
None
- start_recording() None
- Return type:
None
- stop_recording(filename) None
- Return type:
None
- class beamngpy.api.vehicle.LoggingApi(vehicle: Vehicle)
Bases:
VehicleApiA base API class from which all the API communicating with a vehicle derive.
- Parameters:
vehicle (Vehicle) – An instance of a vehicle object.
- 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: <userpath>/<version_number>/<file_name>
- Parameters:
filename (str)
- Return type:
None
- 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: <userpath>/<BeamNG version number>/<output_dir>
- Return type:
None
- stop() None
Stops in game logging.
- Return type:
None
- 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: <userpath>/<BeamNG version number>/<fileName>
- Parameters:
filename (str) – not the absolute file path but the name of the json
- Return type:
None
- class beamngpy.api.vehicle.VehicleApi(vehicle: Vehicle)
Bases:
objectAn API class for in-game logging of vehicle data.
- Parameters:
vehicle (Vehicle) – An instance of a vehicle object.
Scenario
Procedural Objects
Roads
Sensors
Automated Sensors
Camera
Lidar
Ultrasonic Sensor
Powertrain Sensor
Advanced IMU
Radar
Ideal Radar
Mesh Sensor
GPS
Roads Sensor
Classical Sensors
Sensor
State
Electrics
IMU
Timer
Damage
GForces
Logging
- exception beamngpy.logging.BNGDisconnectedError
Exception class for BeamNGpy being disconnected when it shouldn’t.
- exception beamngpy.logging.BNGError
Generic BeamNG error.
- exception beamngpy.logging.BNGValueError
Value error specific to BeamNGpy.
- beamngpy.logging.config_logging(handlers: List[Handler], replace: bool = True, level: int = 10, redirect_warnings: bool = True, log_communication: bool = False) None
Function to configure logging.
- Parameters:
handlers (List[Handler]) – list of already configured logging.Handler objects
replace (bool) – whether to replace existing list of handlers with new ones or whether to add them, optional
level (int) – log level of the beamngpy logger object, optional. Defaults to
logging.DEBUG.redirect_warnings (bool) – whether to redirect warnings to the logger. Beware that this modifies the warnings settings.
log_communication (bool) – whether to log the BeamNGpy protocol messages between BeamNGpy and BeamNG.tech, optional
- Return type:
None
- beamngpy.logging.create_warning(msg: str, category: Any = None) None
Helper function for BeamNGpy modules to create warnings.
- Parameters:
msg (str) – message to be displayed
category (Any) – Category of warning to be issued. See warnings documentation for more details. Defaults to None.
- Return type:
None
- beamngpy.logging.set_up_simple_logging(log_file: str | None = None, redirect_warnings: bool = True, level: int = 20, log_communication: bool = False) None
Helper function that provides high-level control over beamng logging. For low-level control over the logging system use
config_logging(). Sets up logging tosys.stderrand optionally to a given file. Existing log files are moved to<log_file>.1. By default beamngpy logs warnings and errors tosys.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:
log_file (str | None) – log filename, optional
redirect_warnings (bool) – Whether to redirect warnings to the logger. Beware that this modifies the warnings settings.
level (int) – log level of handler that is created for the log file. Defaults to
logging.INFO.log_communication (bool) – whether to log the BeamNGpy protocol messages between BeamNGpy and BeamNG.tech, optional
- Return type:
None
Tools
Miscellaneous
Colors
- beamngpy.misc.colors.coerce_color(color: Color, alpha=0.0) Float4
Tries to coerce a color to a 4-tuple of floats.
- Parameters:
color (Color) – A vehicle color.
alpha – The alpha (transparency) value of the color. Defaults to 0.0.
- Returns:
An
(R, G, B, A)tuple of floats.- Return type:
Float4
- beamngpy.misc.colors.rgba_to_str(color: Float4) str
Converts an
(R, G, B, A)tuple of floats to a string format parsable by BeamNG.- Returns:
The converted string of format ‘R G B A’.
- Parameters:
color (Float4)
- Return type:
str
Quaternions
- beamngpy.misc.quat.angle_to_quat(angle: Float3) Quat
Converts an euler angle to a quaternion.
- Parameters:
angle (Float3) – Euler angle in degrees.
- Returns:
Quaternion with the order
(x, y, z, w)withwrepresenting the real component.- Return type:
Quat
- beamngpy.misc.quat.compute_rotation_matrix(quat: Quat) numpy.ndarray
Calculates the rotation matrix for the given quaternion to be used in a scenario prefab.
- Parameters:
quat (Quat) – Quaternion with the order
(x, y, z, w)withwrepresenting the real component.- Returns:
The rotation matrix as a
NumPyarray.- Return type:
numpy.ndarray
- beamngpy.misc.quat.flip_y_axis(q: Quat) Quat
Returns a rotation with a flipped y-axis.
- Parameters:
q (Quat) – Quaternion with the order
(x, y, z, w)withwrepresenting the real component.- Returns:
The flipped quaternion.
- Return type:
Quat
- beamngpy.misc.quat.normalize(q: Quat) Quat
Normalizes the given quaternion.
- Parameters:
q (Quat) – Quaternion with the order
(x, y, z, w)withwrepresenting the real component.- Returns:
The normalized quaternion.
- Return type:
Quat
- beamngpy.misc.quat.quat_as_rotation_mat_str(quat: Quat, delimiter: str = ' ') str
For a given quaternion, the function computes the corresponding rotation matrix and converts it into a string.
- Parameters:
quat (Quat) – Quaternion with the order
(x, y, z, w)withwrepresenting the real component.delimiter (str) – The string with which the elements of the matrix are divided.
- Returns:
Rotation matrix as a string.
- Return type:
str
- beamngpy.misc.quat.quat_multiply(a: Quat, b: Quat) Quat
Multiplies two quaternions.
- Parameters:
a (Quat) – Quaternion with the order
(x, y, z, w)withwrepresenting the real component.b (Quat) – Quaternion with the order
(x, y, z, w)withwrepresenting the real component.
- Returns:
The product of
aandbas a quaternion.- Return type:
Quat
Vec3
- class beamngpy.misc.vec3(x, y, z=0.0)
Bases:
objectA class for storing vectors in \(R^3\). Contains functions for operating within that vector space. Can also be used as a vec2 class, since the z component is optional.
- cross(b)
The cross product between this vector and a given vector.
- Parameters:
b – The given vector.
- Returns:
The cross product between the two vectors (a vector value)
- distance(b) float
The \(L^2\) (Euclidean) distance between this vector and a given vector. AKA the distance formula.
- Parameters:
b – The given vector.
- Returns:
The \(L^2\) (Euclidean) distance between the two vectors (a scalar value).
- Return type:
float
- distance_sq(b) float
The \(L^1\) (squared) distance between this vector and a given vector. AKA the distance formula.
- Parameters:
b – The given vector.
- Returns:
The squared distance between the two vectors (a scalar value).
- Return type:
float
- dot(b) float
The dot product between this vector and a given vector.
- Parameters:
b – The given vector.
- Returns:
The dot product between the two vectors (a scalar value).
- Return type:
float
- length() float
The length (magnitude) of this vector. [ ie \(length := |vector|\) ]
- Returns:
The length of this vector (a scalar value).
- Return type:
float
- normalize()
Normalizes this vector so that it becomes unit length (\(length = 1\)).
- Returns:
The normalized vector.
Types
- beamngpy.types.Color
Vehicle color. Can be either:
(R, G, B)tuple of floats between 0.0 and 1.0,(R, G, B, A)tuple of floats between 0.0 and 1.0,string of format
'R G B', whereR,G, andBare floats between 0.0 and 1.0,string of format
'R G B A', whereR,G,B, andAare floats between 0.0 and 1.0,a common color name (parsable by
matplotlib.colors).
alias of
Tuple[float,float,float] |Tuple[float,float,float,float] |str
- beamngpy.types.Float2
alias of
Tuple[float,float]
- beamngpy.types.Float3
alias of
Tuple[float,float,float]
- beamngpy.types.Float4
alias of
Tuple[float,float,float,float]
- beamngpy.types.Float5
alias of
Tuple[float,float,float,float,float]
- beamngpy.types.Int2
alias of
Tuple[int,int]
- beamngpy.types.Int3
alias of
Tuple[int,int,int]
- beamngpy.types.Quat
alias of
Tuple[float,float,float,float]
- beamngpy.types.StrDict
alias of
Dict[str,Any]
Connection
- class beamngpy.connection.CommBase(bng: BeamNGpy, vehicle: Vehicle | None)
Communication helper base class to make the socket communication easier to implement for derived classes.
- Parameters:
bng (BeamNGpy)
vehicle (Vehicle | None)
- send_ack_ge(type: str, ack: str, **kwargs: Any) None
Sends a request to the GE Lua with the provided type and data, and receives the acknowledgement.
- Parameters:
type (str) – Type of the request to send.
ack (str) – Type of the acknowledgement to be received.
kwargs (Any) – The other data being sent.
- Returns:
The response of the simulator.
- Return type:
None
- send_ack_veh(type: str, ack: str, **kwargs: Any) None
Sends a request to the Vehicle Lua with the provided type and data, and receives the acknowledgement.
- Parameters:
type (str) – Type of the request to send.
ack (str) – Type of the acknowledgement to be received.
kwargs (Any) – The other data being sent.
- Returns:
The response of the simulator.
- Return type:
None
- send_recv_ge(type: str, **kwargs: Any) StrDict
Sends a request to the GE Lua with the provided type and data, receives the answer and returns it.
- Parameters:
type (str) – Type of the request to send.
kwargs (Any) – The other data being sent.
- Returns:
The response of the simulator.
- Return type:
StrDict
- send_recv_veh(type: str, **kwargs: Any) StrDict
Sends a request to the Vehicle Lua with the provided type and data, receives the answer and returns it.
- Parameters:
type (str) – Type of the request to send.
kwargs (Any) – The other data being sent.
- Returns:
The response of the simulator.
- Return type:
StrDict
- class beamngpy.connection.Connection(host: str, port: int | None = None)
The class for handling socket communication between BeamNGpy and the simulator, including establishing connections to both the simulator and to its vehicles individually, and for sending and recieving data across these sockets.
Instantiates an instance of the Connection class, creating an unconnected socket ready to be connected when required.
- Parameters:
host (str) – The host to connect to.
port (int | None) – The port to connect to.
- PROTOCOL_VERSION = 'v1.22'
- connect_to_beamng(tries: int = 25, log_tries: bool = True) bool
Sets the socket of this connection instance and attempts to connect to the simulator over the host and port configuration set in this class. Upon failure, connections are re-attempted a limited amount of times.
- Parameters:
tries (int) – The number of connection attempts.
log_tries (bool) – True if the connection logs should be propagated to the caller. Defaults to True.
- Returns:
True if the connection was successful, False otherwise.
- Return type:
bool
- connect_to_vehicle(vehicle: Vehicle, tries: int = 25) None
Sets the socket of this Connection instance, and attempts to connect it to the given vehicle. Upon failure, connections are re-attempted a limited amount of times.
- Parameters:
vehicle (Vehicle) – The vehicle instance to be connected.
tries (int) – The number of connection attempts.
- Return type:
None
- disconnect() None
Closes socket communication for this Connection instance.
- Return type:
None
- hello() None
First function called after connections. Exchanges the protocol version with the connected simulator and raises an error upon mismatch.
- Return type:
None
- message(req: str, **kwargs: Any) Any
Generic message function which is parameterized with the type of message to send and all parameters that are to be embedded in the request. Responses are expected to have the same type as the request. If this is not the case, an error is raised.
- Parameters:
req (str) – The request type.
kwargs (Any)
- Returns:
The response received from the simulator as a dictionary.
- Return type:
Any
- recv(req_id: int) StrDict | BNGError | BNGValueError
- Parameters:
req_id (int)
- Return type:
StrDict | BNGError | BNGValueError
- class beamngpy.connection.Response(connection: Connection, req_id: int)
- Parameters:
connection (Connection)
req_id (int)
- ack(ack_type: str) None
- Parameters:
ack_type (str)
- Return type:
None
- recv(type: str | None = None) StrDict
- Parameters:
type (str | None)
- Return type:
StrDict