pybullet_fleet package
Subpackages
- pybullet_fleet.controllers package
- pybullet_fleet.devices package
- pybullet_fleet.plugins package
Submodules
pybullet_fleet.action module
action.py Base classes and implementations for robot actions.
Provides a unified interface for different types of robot actions: - MoveAction: Path following - PickAction: Object picking with approach - DropAction: Object dropping with approach - WaitAction: Timed waiting (e.g., charging)
Actions are executed through an action queue system in the Agent class.
- pybullet_fleet.action.DEFAULT_MOVE_SKIP_THRESHOLD: float = 0.05
Default minimum distance (m) for MOVING_TO_PICK / MOVING_TO_DROP.
When the robot is already closer than this to the pick/drop pose, the MoveAction sub-step is skipped entirely. Prevents edge-case hangs with zero-distance paths.
- pybullet_fleet.action.DEFAULT_MAX_FORCE: float = 500.0
Default maximum motor force (N) for joint/EE control.
- pybullet_fleet.action.DEFAULT_JOINT_TOLERANCE: float = 0.01
Default joint-space tolerance (rad or m) for convergence checks.
- pybullet_fleet.action.DEFAULT_EE_TOLERANCE: float = 0.02
Default Cartesian end-effector tolerance (m) for convergence checks.
- class pybullet_fleet.action.PickPhase(value)
Bases:
EnumPhases of pick action execution.
- INIT = 'init'
- APPROACHING = 'approaching'
- MOVING_TO_PICK = 'moving_to_pick'
- PICKING = 'picking'
- RETREATING = 'retreating'
- class pybullet_fleet.action.DropPhase(value)
Bases:
EnumPhases of drop action execution.
- INIT = 'init'
- APPROACHING = 'approaching'
- MOVING_TO_DROP = 'moving_to_drop'
- DROPPING = 'dropping'
- RETREATING = 'retreating'
- class pybullet_fleet.action.Action
Bases:
ABCBase class for all robot actions.
Actions represent high-level tasks that agents can perform: - MoveAction: Navigate along a path - PickAction: Pick up an object - DropAction: Drop an object - WaitAction: Wait for a duration
Actions are executed through Agent.add_action() or Agent.add_action_sequence(). Each action manages its own state and returns True when complete.
- status
Current execution status
- start_time
When action started (simulation time)
- end_time
When action completed (simulation time)
- error_message
Error description if action failed
- abstractmethod execute(agent, dt)
Execute action for one timestep.
- abstractmethod reset()
Reset action state for re-execution.
- cancel()
Cancel action execution.
- get_duration()
Get action execution duration.
- is_complete()
Check if action has completed (successfully or with failure).
- Return type:
- class pybullet_fleet.action.MoveAction(path, auto_approach=True, final_orientation_align=True, direction=MovementDirection.FORWARD)
Bases:
ActionMove along a path.
Wraps the existing Agent path following functionality into the Action interface.
The action sends one
PathRequest(request) and follows what becomes of it (Agent.path_request_state):COMPLETEDonce the agent has followed it to its end,CANCELLEDas soon as it is no longer the agent’s – replaced by another request, dropped while held, braked (Agent.brake), stopped or cancelled – without waiting for the newer motion to end. (Underwait_completea request from outside is held rather than replacing this one: the action completes, and the held path runs before the next action.) A path the agent refuses for good (a fixed base, an empty path)FAILED; one it refuses only while it is moving is tried again on the next update. With a controller that does not track requests, the action ends when the agent rests:COMPLETEDat the path’s last waypoint,CANCELLEDelsewhere.- Parameters:
path (
Path) – Path object with waypoints to followauto_approach (
bool) – Add approach waypoint if far from start (default: True)final_orientation_align (
bool) – Align to final orientation after reaching end (default: True)direction (
Union[MovementDirection,str]) – Movement direction - MovementDirection.FORWARD (default, face movement direction) or MovementDirection.BACKWARD (maintain orientation, move backward). Can also accept string “forward” or “backward” for convenience.
Example:
# Move forward (normal) path = Path.from_positions([[0, 0, 0], [1, 0, 0], [1, 1, 0]]) action = MoveAction(path=path) agent.add_action(action) # Move backward action = MoveAction(path=path, direction=MovementDirection.BACKWARD) agent.add_action(action)
- path: Path
- auto_approach: bool = True
- final_orientation_align: bool = True
- direction: MovementDirection | str = 'forward'
- property request: PathRequest
its fields, built once per run.
- Type:
The request this action sends
- execute(agent, dt)
Execute move action.
- Return type:
- END_TOLERANCE = 0.0001
Distance (m) from the last waypoint that counts as having reached it.
- reset()
Reset action state; a rerun sends a new request.
- class pybullet_fleet.action.JointAction(target_joint_positions, max_force=500.0, tolerance=None)
Bases:
ActionJoint positions control as an Action.
- Parameters:
target_joint_positions (
Union[list,dict]) – List of target joint positions (radians for revolute, metres for prismatic)max_force (
float) – Maximum force to apply (default: 500.0)tolerance (
Union[float,list,dict,None]) –Position tolerance to consider as reached. Accepts a single float (applied to all joints), a list (one per joint), or a dict
{joint_name: tol}. WhenNone(the default), the tolerance is resolved fromagent.joint_toleranceat the firstexecute()call and written back to this attribute so the resolved value is inspectable after the action starts.Note
A scalar tolerance applies the same value to every joint regardless of type. For mixed prismatic / revolute chains, consider specifying per-joint tolerances so that prismatic joints (metres) can be tighter than revolute joints (radians).
wait_time – Optional seconds to wait after reaching target (default: 0.0)
Example:
# Scalar tolerance (same for all joints) action = JointAction(target_joint_positions=[0.0, 1.0, 0.0, 0.0]) agent.add_action(action) # Per-joint tolerance for mixed prismatic/revolute action = JointAction( target_joint_positions={"rail_joint": 0.5, "elbow_to_wrist": -0.3}, tolerance={"rail_joint": 0.005, "elbow_to_wrist": 0.05}, # 5 mm / 0.05 rad )
- max_force: float = 500.0
- execute(agent, dt)
Execute action for one timestep.
- reset()
Reset action state for re-execution.
- class pybullet_fleet.action.PoseAction(target_position, target_orientation=None, end_effector_link=None, max_force=500.0, tolerance=0.02)
Bases:
ActionEnd-effector pose control via inverse kinematics.
Calls
agent.move_end_effector()on the first step. When IK returns a candidate, the action waits for its joint targets to settle. After settling, it completes withCOMPLETEDonly when both the initial reachability check and final EE Cartesian check pass; otherwise it completes withFAILED.toleranceis used for both the IK reachability pre-check (viamove_end_effector()) and the final EE Cartesian distance verification (viaare_ee_at_target()). Joint convergence uses the default joint tolerance (not this value).- Parameters:
target_position (
List[float]) – Target EE position [x, y, z] in world frame.target_orientation (
Optional[tuple]) – Target EE orientation as quaternion [qx, qy, qz, qw] (optional).end_effector_link (
Union[int,str,None]) – Link index (int), name (str), or None for auto-detect.max_force (
float) – Maximum force for motor control (default: 500.0).tolerance (
float) – EE Cartesian distance tolerance in metres (default: 0.02).
Example:
action = PoseAction(target_position=[0.3, 0.0, 0.5]) agent.add_action(action) action = PoseAction( target_position=[0.3, 0.0, 0.5], target_orientation=[0, 0, 0, 1], ) agent.add_action(action)
- max_force: float = 500.0
- tolerance: float = 0.02
- execute(agent, dt)
Execute action for one timestep.
- reset()
Reset action state for re-execution.
- class pybullet_fleet.action.WaitAction(duration, action_type='idle')
Bases:
ActionWait for a specified duration.
Useful for simulating charging, loading, or other time-based operations.
- Parameters:
Example:
# Wait for 5 seconds (charging) action = WaitAction(duration=5.0, action_type="charge") agent.add_action(action)
- duration: float
- action_type: str = 'idle'
- execute(agent, dt)
Execute wait action.
- Return type:
- reset()
Reset action state.
- class pybullet_fleet.action.PickAction(target_object_id=None, target_position=None, search_radius=0.5, use_2d_search=True, use_approach=True, approach_pose=None, approach_offset=1.0, pick_offset=0.0, move_skip_threshold=0.05, attach_link=-1, attach_relative_pose=<factory>, joint_targets=None, joint_tolerance=None, joint_max_force=500.0, ee_target_position=None, ee_target_orientation=None, ee_end_effector_link=None, ee_tolerance=0.02, continue_on_ik_failure=True)
Bases:
ActionPick an object and attach it to the robot.
Kinematic implementation: 1. Move to approach pose (if specified or auto-calculated) 2. Teleport object to attachment position 3. Attach object using constraint
- Parameters:
target_object_id (
Optional[int]) – Specific object body ID to pick (optional)target_position (
Optional[List[float]]) – Pick from position - auto-select nearest pickable object (optional)search_radius (
float) – Search radius when using target_position (default: 0.5m)approach_pose (
Optional[Pose]) – Explicit approach pose (optional, auto-calculated if None)approach_offset (
float) – Auto-calculate approach offset distance (default: 1.0m)pick_offset (
float) – Distance from target where pick is executed (default: 0.0m)attach_link (
Union[int,str]) – Link to attach to - can be index (int) or name (str). -1 or “base_link” for base link (default: -1)attach_relative_pose (
Pose) – Position and orientation offset in link’s frame as Pose object
Note
Path visualization is controlled by agent.path_visualize setting.
Example:
# Pick specific object with position offset (using link index) action = PickAction( target_object_id=pallet.body_id, approach_offset=1.0, pick_offset=0.3, attach_link=-1, # Base link attach_relative_pose=Pose.from_euler(0.6, 0, -0.2, roll=np.pi/2, pitch=0, yaw=0) ) agent.add_action(action) # Pick using link name action = PickAction( target_object_id=pallet.body_id, attach_link="sensor_mast", # Attach to named link attach_relative_pose=Pose.from_euler(0, 0, 0.5) ) agent.add_action(action) # Pick nearest object at location action = PickAction( target_position=[5, 0, 0.1], search_radius=0.5 ) agent.add_action(action)
- search_radius: float = 0.5
- use_2d_search: bool = True
- use_approach: bool = True
- approach_pose: Pose | None = None
- approach_offset: float = 1.0
- pick_offset: float = 0.0
- move_skip_threshold: float = 0.05
- attach_relative_pose: Pose
- joint_max_force: float = 500.0
- ee_tolerance: float = 0.02
- continue_on_ik_failure: bool = True
- execute(agent, dt)
Execute pick action.
- Return type:
- reset()
Reset action state.
- class pybullet_fleet.action.DropAction(drop_pose, use_approach=True, approach_pose=None, approach_offset=1.0, drop_offset=0.0, move_skip_threshold=0.05, place_gently=True, drop_height=0.1, target_object_id=None, drop_relative_pose=None, joint_targets=None, joint_tolerance=None, joint_max_force=500.0, ee_target_position=None, ee_target_orientation=None, ee_end_effector_link=None, ee_tolerance=0.02, continue_on_ik_failure=True)
Bases:
ActionDrop an attached object at a specified location.
Kinematic implementation: 1. Move to approach pose (if specified or auto-calculated) 2. Detach object 3. Teleport object to drop position
- Parameters:
drop_pose (
Pose) – Where to drop the object (position and orientation). Orientation defaults to no rotation[0, 0, 0, 1].approach_pose (
Optional[Pose]) – Explicit approach pose (optional, auto-calculated if None)approach_offset (
float) – Auto-calculate approach offset distance (default: 0.2m)place_gently (
bool) – Place at exact position vs drop from height (default: True)drop_height (
float) – Height above drop_pose to release if not gentle (default: 0.1m)target_object_id (
Optional[int]) – Specific object to drop (None = drop first attached)
Example:
# Drop at specific location action = DropAction( drop_pose=Pose(position=[10, 5, 0.1]), place_gently=True ) agent.add_action(action) # Drop with specific orientation action = DropAction( drop_pose=Pose(position=[10, 5, 0.1], orientation=[0, 0, 0.7, 0.7]), )
Note
Path visualization is controlled by agent.path_visualize setting.
- drop_pose: Pose
- use_approach: bool = True
- approach_pose: Pose | None = None
- approach_offset: float = 1.0
- drop_offset: float = 0.0
- move_skip_threshold: float = 0.05
- place_gently: bool = True
- drop_height: float = 0.1
- drop_relative_pose: Pose | None = None
- joint_max_force: float = 500.0
- ee_tolerance: float = 0.02
- continue_on_ik_failure: bool = True
- execute(agent, dt)
Execute drop action.
- Return type:
- reset()
Reset action state.
pybullet_fleet.action_parser module
Parse generic action commands into PyBulletFleet Action objects.
- pybullet_fleet.action_parser.parse_action_goal(action_type, action_params_json)
Parse an action type and JSON parameter payload.
- Return type:
Optional[Action]
pybullet_fleet.agent module
core/agent.py Agent class for goal-based position control with max velocity and acceleration constraints. Supports both mobile (use_fixed_base=False) and fixed (use_fixed_base=True) robots. Supports both Mesh and URDF loading.
- class pybullet_fleet.agent.AgentSpawnParams(visual_shape=None, collision_shape=None, initial_pose=<factory>, mass=0.0, pickable=False, name=None, visual_frame_pose=None, collision_frame_pose=None, collision_mode=CollisionMode.NORMAL_3D, user_data=<factory>, urdf_path=None, motion_mode=MotionMode.DIFFERENTIAL, use_fixed_base=False, ik_params=None, controller=None, plugins=None, global_scaling=1.0, joint_tolerance=None)
Bases:
SimObjectSpawnParamsAgent spawn parameters extending SimObjectSpawnParams.
These parameters define the physical properties, appearance, and initial state of an agent. They are used by Agent.from_params() and AgentManager.spawn_agents_grid().
Supports three types of robots: 1. Mesh robots: Specify visual_shape (and optionally collision_shape) 2. URDF robots: Specify urdf_path (for robots with joints) 3. Virtual agents: Specify neither (invisible, no collision, useful for tracking/planning)
- urdf_path
Path to robot URDF file (for URDF-based robots with joints)
- motion_mode
MotionMode.OMNIDIRECTIONAL (move in any direction) or MotionMode.DIFFERENTIAL (rotate then move forward)
- use_fixed_base
If True, robot base is fixed and doesn’t move (default: False)
- plugins
List of plugin config dicts for per-agent plugins. Each entry is
{"type": "battery", "config": {...}}or{"class": "my.Module", "config": {...}}.
- controller
Movement controller selector / configuration. Accepts a registry-name string (
"omni"), a flat dict, a list of dicts, aControllerParams, or a pre-builtController. Each dict entry uses eithertype:(registry name) orclass:(dotted import path), plus controller-specific config inline. KinematicController entries (omni, differential) replace the base controller; high-level entries (patrol, random_walk) are appended on top of it. A lone high-level entry auto-creates the base frommotion_mode. Example single:{"type": "patrol", "waypoints": [...], "loop": True}Example custom:{"class": "my_pkg.MyController", "max_linear_vel": 1.5}Example list:[{"type": "differential", ...}, {"type": "patrol", ...}]
See
Agent.__init__for thecontrollerargument (selector / configuration for the Agent’s movement controller; supports str / dict / list / Controller / ControllerParams).- Inherited from SimObjectSpawnParams:
- name: Optional string name for human-readable identification.
Duplicates allowed - use for debugging/filtering, not unique lookup. For unique identification, use object_id after spawning.
Note
AgentManager.spawn_agents_grid() calculates positions automatically and may override initial_pose.
- pickable: bool = False
Agents are not pickable by default – a robot is usually the one doing the picking – which narrows SimObjectSpawnParams’ default of True. Redeclared rather than set elsewhere so the value a caller passes is the value the agent gets; Agent.__init__ used to overwrite it unconditionally, which made the field inert.
- motion_mode: MotionMode | str = 'differential'
- use_fixed_base: bool = False
- ik_params: IKParams | None = None
- controller: str | Dict[str, Any] | List[Dict[str, Any]] | ControllerParams | Controller | None = None
- global_scaling: float = 1.0
- classmethod from_dict(config)
Create AgentSpawnParams from configuration dictionary.
- Parameters:
Dictionary with robot parameters including:
visual_shape/collision_shapeorurdf_pathinitial_pose:Poseobject (optional)controller: dict / str /None— seecontrollerand the Controller Configuration how-touse_fixed_base,motion_mode,ik_params(optional)
- Returns:
AgentSpawnParams instance
Example:
config = { 'visual_shape': ShapeParams( shape_type='mesh', mesh_path='robot.obj', mesh_scale=[1.0, 1.0, 1.0], rgba_color=[0.2, 0.2, 0.2, 1.0] ), 'collision_shape': ShapeParams( shape_type='box', half_extents=[0.2, 0.1, 0.2] ), 'initial_pose': Pose.from_xyz(1.0, 2.0, 0.0), 'controller': {'max_linear_vel': 2.0, 'max_linear_accel': 5.0}, 'use_fixed_base': False } params = AgentSpawnParams.from_dict(config) # Or for URDF: config = { 'urdf_path': 'robots/mobile_robot.urdf', 'initial_pose': Pose.from_xyz(1.0, 2.0, 0.0), 'use_fixed_base': False } params = AgentSpawnParams.from_dict(config)
- class pybullet_fleet.agent.IKParams(max_outer_iterations=5, convergence_threshold=0.01, max_inner_iterations=200, residual_threshold=0.0001, reachability_tolerance=0.02, seed_quartiles=(0.25, 0.5, 0.75), ik_joint_names=None)
Bases:
objectInverse kinematics solver configuration.
Controls the multi-seed iterative IK solver used by
Agent._solve_ik()andAgent.move_end_effector().- max_outer_iterations
Maximum refinement iterations per seed.
- convergence_threshold
EE-to-target distance (m) below which the IK solution is accepted early.
- max_inner_iterations
maxNumIterationspassed topybullet.calculateInverseKinematics.
- residual_threshold
residualThresholdpassed topybullet.calculateInverseKinematics.
- reachability_tolerance
Maximum EE distance (m) for
Agent.move_end_effector()to report reachable.
- seed_quartiles
Tuple of joint-range fractions (0–1) used to build diversified rest-pose seeds. Each value
qproduces a seed atlower + q * rangefor every joint.
- ik_joint_names
Explicit tuple of joint names that the IK solver is allowed to move. All other movable joints are locked at their current position. When
None(default), the solver falls back to the automatic heuristic (continuous joints are locked, everything else is free).
Example:
cfg = IKParams(max_outer_iterations=10, seed_quartiles=(0.1, 0.5, 0.9)) arm = Agent.from_urdf("arm.urdf", ik_params=cfg) # Mobile manipulator — solve only for arm joints cfg = IKParams(ik_joint_names=( "mount_to_shoulder", "shoulder_to_elbow", "elbow_to_wrist", "wrist_to_end", )) robot = Agent.from_urdf("mobile_manipulator.urdf", ik_params=cfg)
- max_outer_iterations: int = 5
- convergence_threshold: float = 0.01
- max_inner_iterations: int = 200
- residual_threshold: float = 0.0001
- reachability_tolerance: float = 0.02
- pybullet_fleet.agent.validate_joint_motion_profile(max_velocity=None, max_accel=None, max_decel=None, current_accel=None)
Refuse an unusable joint motion profile from the values alone.
Agent.set_joint_motion_profile()needs a body to resolve the joint against, which is too late for a caller that spawns the body and then configures it: a profile refused at that point leaves the half-configured object registered with the simulation. This checks everything that does not need the body, so such a caller can refuse before spawning.- Parameters:
- Raises:
ValueError – If a value given is not a finite number above zero, or if
max_decelis given for a joint that has no acceleration.- Return type:
- class pybullet_fleet.agent.Agent(body_id, urdf_path=None, motion_mode=MotionMode.DIFFERENTIAL, use_fixed_base=False, collision_mode=CollisionMode.NORMAL_3D, sim_core=None, name=None, user_data=None, mass=None, ik_params=None, joint_tolerance=None, controller=None, notify_spawn=True, pickable=False)
Bases:
SimObjectAgent class with goal-based position control.
Inherits from SimObject to get attach/detach and callback functionality. Supports both mobile robots (use_fixed_base=False) and fixed robots (use_fixed_base=True). Supports both Mesh and URDF loading.
- Class Attributes:
- _spawn_params_cls: The SpawnParams dataclass used by config-driven
grid spawning (
AgentSpawnParams).
- Class Constants:
- _KINEMATIC_JOINT_FALLBACK_VELOCITY: Default max joint velocity for
revolute joints (rad/s) used when the URDF
<limit velocity="...">is 0 or missing.- _KINEMATIC_PRISMATIC_FALLBACK_VELOCITY: Default max joint velocity
for prismatic joints (m/s) used when the URDF limit is 0 or missing.
- _DEFAULT_JOINT_TOLERANCE: Default tolerance (rad / m) for joint
target comparison methods.
Features: - Accepts Pose goals (compatible with ROS2 geometry_msgs/Pose) - Max velocity and acceleration constraints (for mobile robots) - Current pose query API - Shared shape optimization for fast spawning - Fixed robot support (non-moving objects) - URDF support with joint control - Attach/detach objects (inherited from SimObject)
Object Identification (inherited from SimObject): - object_id: Unique integer ID (assigned by sim_core, use for lookups) - name: Optional string name (duplicates allowed, use for debugging/filtering)
This class is designed to be eventually controlled by ROS2 nodes, so the API follows ROS message conventions.
- __init__(body_id, urdf_path=None, motion_mode=MotionMode.DIFFERENTIAL, use_fixed_base=False, collision_mode=CollisionMode.NORMAL_3D, sim_core=None, name=None, user_data=None, mass=None, ik_params=None, joint_tolerance=None, controller=None, notify_spawn=True, pickable=False)
Initialize Agent.
- Parameters:
body_id (
int) – PyBullet body IDurdf_path (
Optional[str]) – Path to robot URDF file (if URDF-based)motion_mode (
Union[MotionMode,str]) –MotionMode.OMNIDIRECTIONAL or MotionMode.DIFFERENTIAL drive. Used as the default controller selector when
controllerhas no"type"key. Ifcontroller={"type": ...}is given and disagrees withmotion_mode, a warning is logged andcontroller.typewins.Deprecated since version Prefer:
controller="omni"/controller="differential"(or a fullcontroller={...}dict).motion_modeis retained for backward compatibility and as a coarse “2D mobile base shape” hint for batched controllers.use_fixed_base (
bool) – If True, robot base is fixed and doesn’t movecollision_mode (
CollisionMode) – Collision detection mode (default: NORMAL_3D)sim_core – Reference to simulation core (optional)
ik_params (
Optional[IKParams]) – IK solver configuration (default:IKParams()).joint_tolerance (
Union[float,list,dict,None]) – Default joint tolerance for convergence checks. Acceptsfloat(all joints),list(per-joint), ordict({joint_name: tol}). IfNone, uses the class default (0.01). For mixed prismatic / revolute chains, a dict is recommended so prismatic joints (metres) can use a tighter tolerance than revolute joints (radians).controller (
Union[str,Dict[str,Any],ControllerParams,Controller,None]) –Controller selector / configuration. Accepts:
None— framework defaults;motion_modeselectsOmniControllerorDifferentialController.str— registry name, e.g."omni","differential","patrol". Equivalent to{"type": <str>}.dict—{"type": "...", "max_linear_vel": 1.5, "wheel_separation": 0.3, ...}.ControllerParamsfields populateControllerParams; impl-specific extras (e.g.wheel_separation) flow through to the controller’s__init__. Recommended for YAML / config-file workflows.Controllerinstance — any pre-built controller (built-in or custom). Installed as-is;self.controller_paramsis taken fromcontroller.params. Recommended for Python workflows that need custom controllers or want type-safe construction.ControllerParamsinstance — params only;motion_modestill picks the Omni/Diff class. Use this only when you want to tweak shared params but keep the default class.
Note
For spawning robots from AgentSpawnParams, use Agent.from_params() instead. For mesh robots, use Agent.from_mesh() factory method. For URDF robots, use Agent.from_urdf() factory method.
- path_visualize: bool
- path_visualize_width: float
- controller_params: ControllerParams
- property max_linear_vel: ndarray
- property max_linear_accel: ndarray
- property max_linear_decel: ndarray
Effective deceleration limit; mirrors
max_linear_accelwhen unset.
- property max_angular_vel: ndarray
- property max_angular_accel: ndarray
- property max_angular_decel: ndarray
Effective angular deceleration limit; mirrors
max_angular_accelwhen unset.
- property joint_tolerance: float | list | dict
Default joint tolerance used by convergence checks.
Returns the instance-level tolerance if set, otherwise the class default (
_DEFAULT_JOINT_TOLERANCE = 0.01).For robots with mixed prismatic (metres) and revolute (radians) joints, set this to a
dictso each joint type can have an appropriate tolerance:agent = Agent.from_urdf( ..., joint_tolerance={"rail_joint": 0.005, "elbow_to_wrist": 0.05}, )
- property is_moving: bool
Check if robot is currently moving.
To change movement state, use set_goal_pose(), set_path(), or stop().
- Returns:
True if robot is moving, False otherwise
- Type:
Read-only property
- property battery_soc: float
Current state of charge [0.0, 1.0].
Always returns
1.0when noBatteryPluginis attached.
- property is_charging: bool
Whether the agent is currently charging.
- property battery_plugin
The
BatteryPlugininstance, orNone.
- set_charging(charging)
Start or stop charging.
- property plugins: List[AgentPlugin]
Read-only list of active per-agent plugins.
- add_plugin(plugin)
Attach a per-agent plugin.
- Parameters:
plugin (
AgentPlugin) – AnAgentPlugininstance bound to this agent.- Raises:
ValueError – If plugin is not bound to this agent.
- Return type:
- remove_plugin(plugin_or_cls)
Remove a plugin by instance or class.
When a class is given, the first instance of that class is removed. When an instance is given, that exact instance is removed.
- Parameters:
plugin_or_cls – An
AgentPlugininstance or subclass.- Return type:
- get_plugin(cls)
Return the first plugin matching cls, or
None.
- property motion_mode: MotionMode
Get current motion mode.
To change motion mode, use set_motion_mode() method.
- Returns:
Current MotionMode (OMNIDIRECTIONAL or DIFFERENTIAL)
- Type:
Read-only property
- property velocity: ndarray
Get current velocity vector.
- Returns:
Velocity [vx, vy, vz] in m/s (copy of internal state)
- Type:
Read-only property
- property angular_velocity: float
Get current angular velocity.
- Returns:
Angular velocity in rad/s
- Type:
Read-only property
- property goal_pose: Pose | None
Get current goal pose.
To set a new goal, use set_goal_pose() or set_path().
- Returns:
Current goal Pose, or None if no goal is set
- Type:
Read-only property
- property current_waypoint_index: int
Get current waypoint index in the path.
- Returns:
Current waypoint index (0-based), or 0 if no path is set
- Type:
Read-only property
- property path: List[Pose]
Current waypoint path. Empty when idle.
- Type:
Read-only property
- classmethod from_params(spawn_params, sim_core=None)
Create an Agent from AgentSpawnParams.
This is the recommended way to spawn robots when using AgentSpawnParams. Automatically detects whether to use mesh, URDF, or virtual agent based on spawn_params.
- Parameters:
spawn_params (
AgentSpawnParams) – AgentSpawnParams instance with all robot parameterssim_core – Reference to simulation core (optional)
- Return type:
Agent- Returns:
Agent instance
The recommended way to choose a controller is to set
controller={"type": "omni" | "differential" | ...}explicitly.motion_modestill works as a shortcut and as the default whencontroller.typeis omitted, but if both are given,controller.typewins and a warning is emitted on mismatch.Example (Mesh, omni — recommended explicit form):
params = AgentSpawnParams( visual_shape=ShapeParams( shape_type="mesh", mesh_path="robot.obj", mesh_scale=[1.0, 1.0, 1.0], rgba_color=[0.2, 0.2, 0.2, 1.0] ), collision_shape=ShapeParams( shape_type="box", half_extents=[0.2, 0.1, 0.2] ), initial_pose=Pose.from_xyz(1.0, 2.0, 0.0), controller={"type": "omni", "max_linear_vel": 3.0}, ) robot = Agent.from_params(spawn_params=params)
Example (URDF):
params = AgentSpawnParams( urdf_path="arm_robot.urdf", initial_pose=Pose.from_xyz(0.0, 0.0, 0.0), use_fixed_base=True, ) robot = Agent.from_params(spawn_params=params)
Example (Virtual Agent - invisible, no collision):
params = AgentSpawnParams( initial_pose=Pose.from_xyz(0.0, 0.0, 0.0), controller={"type": "omni", "max_linear_vel": 2.0}, ) virtual_agent = Agent.from_params(spawn_params=params)
- classmethod from_dict(config, sim_core=None)
Create an Agent from a raw config dict.
Combines
AgentSpawnParams.from_dict()andfrom_params()in a single call. Usescls._spawn_params_clsso subclasses (e.g. Door, Elevator) automatically use their own SpawnParams.
- classmethod from_mesh(visual_shape=None, collision_shape=None, pose=None, mass=0.0, motion_mode=MotionMode.DIFFERENTIAL, use_fixed_base=False, collision_mode=CollisionMode.NORMAL_3D, sim_core=None, name=None, user_data=None, controller=None, notify_spawn=True, pickable=False)
Create a mesh-based Agent with flexible shape control.
- Parameters:
visual_shape (
Optional[ShapeParams]) – ShapeParams for visual geometrycollision_shape (
Optional[ShapeParams]) – ShapeParams for collision geometrypose (
Pose) – Initial Pose (position and orientation)mass (
float) – Robot mass (kg), 0.0 for kinematic controlmotion_mode (
Union[MotionMode,str]) – MotionMode.OMNIDIRECTIONAL or MotionMode.DIFFERENTIALuse_fixed_base (
bool) – If True, robot base is fixed and doesn’t movesim_core – Reference to simulation core
controller (
Union[str,Dict[str,Any],ControllerParams,Controller,None]) – Controller selector / config. SeeAgent.__init__()for accepted forms (None/str/dict/ControllerParams).
- Return type:
Agent- Returns:
Agent instance
- classmethod from_urdf(urdf_path, pose=None, mass=None, motion_mode=MotionMode.DIFFERENTIAL, use_fixed_base=False, collision_mode=CollisionMode.NORMAL_3D, sim_core=None, name=None, user_data=None, ik_params=None, joint_tolerance=None, controller=None, notify_spawn=True, global_scaling=1.0, pickable=False)
Create a URDF-based Agent (with joints).
- Parameters:
urdf_path (
str) – Robot model name (e.g."panda") or path to URDF file. Names are resolved viaresolve_model()pose (
Pose) – Initial Pose (position and orientation). Defaults to originmass (
Optional[float]) – Mass override. - None (default): Use URDF file’s mass values as-is - 0.0: Override all links to mass=0 for kinematic control (no physics)motion_mode (
Union[MotionMode,str]) – MotionMode.OMNIDIRECTIONAL or MotionMode.DIFFERENTIALuse_fixed_base (
bool) – If True, robot base is fixed in spaceglobal_scaling (
float) – Uniform scale factor applied when loading.pickable (
bool) – Whether the agent may be attached to another body (default: False – a robot is usually the one doing the picking).attach_object()refuses a non-pickable body.sim_core – Reference to simulation core
ik_params (
Optional[IKParams]) – IK solver configuration (default:IKParams()).joint_tolerance (
Union[float,list,dict,None]) – Default joint tolerance for convergence. Seejoint_toleranceproperty for details.controller (
Union[str,Dict[str,Any],ControllerParams,Controller,None]) – Controller selector / config. SeeAgent.__init__()for accepted forms (None/str/dict/ControllerParams).
- Return type:
Agent- Returns:
Agent instance
Note
mass=None (default): Uses URDF file’s mass values for physics simulation
mass=0.0: Override all links to mass=0 for kinematic control (no physics)
Example:
robot = Agent.from_urdf(urdf_path="arm_robot.urdf") robot = Agent.from_urdf(urdf_path="panda", use_fixed_base=True) robot = Agent.from_urdf(urdf_path="arm_robot.urdf", mass=0.0)
- set_goal_pose(goal, direction=None)
Set goal pose for the robot to move to.
Note: This is ignored if the robot has a fixed base.
- brake()
Come to rest along the current direction of travel at the configured deceleration.
A deceleration-limited counterpart of
stop(), which zeroes the velocity at once (an emergency stop). The agent keeps its heading and its line of motion and stops at the braking point,|v|^2 / (2 * decel)ahead, decelerating at exactly the configured rate along that direction (the same projected limits a trajectory uses). The remaining path and any queued waypoints are dropped; a velocity command (the controller’sset_velocity) is ended the same way.A differential-drive agent brakes straight along its heading (backing up, it brakes backwards). A path set while it brakes is handled like any path set while moving (see
set_path()); a pending path from an earlierbrakeorwait_completereplacement is dropped.The action queue is left alone, but does not run on while the agent brakes. A
MoveActionstill executing endsCANCELLEDon its next update – its request is gone once the braking path replaces it – and the queue waits until the agent is at rest before starting the next action; callclear_actions()first to drop the queued actions too.The agent’s controller does the braking (its
brake()); a custom controller changes how the agent brakes by overridingKinematicController.braking_request, whichgoal_replacement="brake"uses too.- Return type:
- Returns:
Truewhen a braking trajectory was set.Falseat rest, for a fixed-base robot, and for a controller that cannot brake.
- path_rejection(path, direction=None)
Why
set_path()would refusepathright now, orNone.A
PathRejection:reasonsays why,temporarywhether it lasts only until the current motion ends (a fixed-base robot and an empty path are permanent).Only
goal_replacement="reject"refuses a path that cannot continue the current motion (seeset_path()); the other modes take every path. Asking first lets a caller report a refusal before acting.directionis the oneset_path()would be given.- Return type:
Optional[PathRejection]
- set_motion_mode(mode)
Set motion mode for the robot.
Replaces the active controller with the matching default (OmniController or DifferentialController). Any custom controller previously installed via
controller.typeis lost.Note: Motion mode cannot be changed while the robot is moving.
Deprecated since version Prefer:
agent.set_controller(create_controller(name, cfg))for runtime controller swaps.set_motion_modeis kept for backward compatibility and only handles the built-in Omni / Differential defaults.
- set_path(path, auto_approach=True, final_orientation_align=True, direction=None, _preempt=False)
Set a path (list of waypoints) for the robot to follow.
A path set while the agent is moving continues the motion when it can: the straight-line trajectory to the first waypoint starts from the agent’s current velocity (signed along the line, so a goal behind is reached by slowing and reversing). It cannot for a goal inside the braking distance, where the agent is, off the line of motion, or – differential drive – one that needs a turn in place. Such a path is handled as the controller’s
goal_replacementsetting says (GoalReplacement):brake(the default) brakes at the configured deceleration and then starts it,wait_completefinishes the current path first (it holds every path set while one is in progress, reachable or not),immediatestarts it from rest at once, andrejectrefuses it – nothing changes, the current motion continues, and this returnsFalse(the reason is logged and available frompath_rejection()). At rest every path is taken.- Parameters:
path (
List[Pose]) – List of Pose waypoints to follow in sequenceauto_approach (
bool) – If True, automatically add straight-line approach from current position to first waypoint if distance > threshold (default: True)final_orientation_align (
bool) – If True, add final rotation to match last waypoint’s orientation after reaching the position (default: True)direction (
Union[MovementDirection,str,None]) – Movement direction override, orNoneto use the controller’sdefault_direction. Can be MovementDirection enum or string (“auto”, “forward”, “backward”). Only used in differential drive mode (MotionMode.DIFFERENTIAL). In omnidirectional mode, this parameter is ignored._preempt (
bool) – Internal: start without waiting for the current path underwait_complete(used bybrake()), for every kinematic controller, omnidirectional or differential, per-agent or batched.
- Return type:
- Returns:
Truewhen the path was taken (started or held to start later);Falsefor a fixed-base robot, an empty path, or a path refused undergoal_replacement="reject".
- request_path(request, _preempt=False, _internal=False)
Follow
request: the core ofset_path(), which builds one from its arguments.The same rules as
set_path(): a path set while moving continues the motion when it can, and otherwise the controller’sgoal_replacementdecides.request.auto_approachputs the current pose in front of the path when the agent is at rest and more than 0.5 m from the first waypoint; the request reaches the controller as a copy that keeps its identity, sopath_request_state()can tell what became of it.- Parameters:
- Return type:
- Returns:
Truewhen the path was taken (started or held to start later);Falsefor a fixed-base robot, an empty path, or a path refused undergoal_replacement="reject".
- path_request_state(request)
What became of
request(sent withrequest_path()): being followed, held, followed to its end, or gone – replaced by another request, dropped from the hold, stopped, braked or cancelled.UNKNOWNfor a controller that does not track requests, and for a request aset_pathoverride did not pass on (it sent one of its own instead).- Return type:
PathRequestState
- add_action(action)
Add an action to the execution queue.
Actions are executed sequentially in the order they are added.
- Parameters:
action (
Action) – Action instance to add to queue
Example:
agent.add_action(MoveAction(path=my_path)) agent.add_action(WaitAction(duration=5.0))
- add_action_sequence(actions)
Add multiple actions to the execution queue.
- Parameters:
actions (
List[Action]) – List of Action instances to add
Example:
agent.add_action_sequence([ MoveAction(path=path1), PickAction(target_object_id=obj.body_id), MoveAction(path=path2), DropAction(drop_pose=Pose(position=[10, 5, 0])) ])
- clear_actions()
Clear all actions from the queue and cancel current action.
- get_current_action()
Get the currently executing action.
- Return type:
Optional[Action]- Returns:
Current Action instance, or None if no action is executing
- get_action_queue_size()
Get the number of actions waiting in the queue.
- Return type:
- Returns:
Number of actions in queue
- is_action_queue_empty()
Check if action queue is empty and no action is currently executing.
- Return type:
- Returns:
True if no actions are queued or executing, False otherwise
- set_joint_motion_profile(joint, max_velocity=None, max_accel=None, max_decel=None)
Override how fast a kinematic joint moves, and how it gets there.
Without this, a kinematic joint runs at the URDF’s
<limit velocity="...">and reaches it instantly: the speed is a property of the model file, so changing it means editing or regenerating the URDF, andchangeDynamics(maxJointVelocity=...)does not help becausegetJointInfo()keeps reporting the original.Giving
max_accelturns the motion into a trapezoid – ramp up, cruise, ramp down – which is what a real lift, hoist or linear axis does. A 0.6 m travel at 0.4 m/s takes 1.5 s at a constant speed and 1.9 s with 1.0 m/s ramps, so the difference is not cosmetic when something downstream is timing the move.Both are optional and independent. With neither, nothing changes; with
max_velocityalone the joint still steps instantly to that speed, exactly as before.Every argument left at
Nonekeeps what the joint already has, so this can be called again to change one of them. A ramp cannot be taken off a joint once it has one.Can be called while the joint is moving. The speed it is carrying is kept and the next step re-plans from it under the new limits, so the change is continuous; if the new limits can no longer stop the joint at its target it brakes and comes back, as for any other target it cannot reach.
- Parameters:
joint (
Union[int,str]) – Joint index, or joint name as spelled in the URDF.max_velocity (
Optional[float]) – Speed cap, replacing the URDF limit.Nonekeeps whatever the joint already uses.max_accel (
Optional[float]) – Acceleration, in units/s^2.Nonekeeps the acceleration the joint already has, and means no ramp only when it has none.max_decel (
Optional[float]) – Deceleration.Nonekeeps the current one, or followsmax_accelwhen that is given. On its own it changes the braking rate of a joint that already ramps.
- Raises:
KeyError – If joint names a joint this body does not have.
IndexError – If joint is an index this body does not have.
ValueError – If any value given is not positive, or if
max_decelis given for a joint with no acceleration.
- Return type:
- is_joint_moving(joint)
Whether a ramped joint is still in motion.
An action reports complete once the joint is inside its tolerance, which a ramped joint reaches while still braking through the last fraction of a millimetre. Anything that has to know the joint has actually stopped – a lift releasing its passengers, say – needs this rather than the action’s status.
True while the joint is following a trajectory, while it is braking with none to follow, and while it is between the two: changing a motion profile voids the trajectory it was solved against but not the speed the joint is carrying, and the replacement is not planned until the next step. A joint that is only carrying speed is as much in motion as one with a plan, which is why this asks about the motion rather than about the trajectory.
- Parameters:
joint (
Union[int,str]) – Joint index, or joint name as spelled in the URDF.- Raises:
KeyError – If joint names a joint this body does not have.
IndexError – If joint is an index this body does not have.
- Return type:
- update(dt)
Update robot position towards goal with velocity/acceleration constraints.
Supports two motion modes: - MotionMode.OMNIDIRECTIONAL: Move in any direction without rotating first (smooth trajectories) - MotionMode.DIFFERENTIAL: Rotate to face target, then move forward (smooth trajectories)
Also processes action queue for high-level task execution.
Note: This does nothing if the robot has a fixed base.
- get_velocity()
Get current velocity vector.
- Return type:
- Returns:
Velocity [vx, vy, vz] in m/s
- restore_motion_state(pose, linear_velocity, angular_velocity, *, moving)
Restore Agent-owned motion fields; restore controller execution separately.
- Return type:
- set_controller(controller=None)
Set or replace the base (index-0) movement controller.
When a controller is set,
update()delegates movement tocontroller.compute(agent, dt).A controller that carries its own
ControllerParamsalso becomes this agent’scontroller_params, which is whatAgent.__init__does when the controller is passed at construction. Without that the two diverge silently: the controller moves the agent by its own limits whilecontroller_params– the single source of truth thatmax_linear_veland its siblings delegate to, and that a batch controller builds its trajectory from – still holds whatever was there before, usually the defaults.Note: A default controller is always assigned in
from_params(). SettingNonedisables all movement and leavescontroller_paramsas it is, since there are then no limits to take.
- add_controller(controller)
Append a high-level controller to the chain.
High-level controllers (patrol, random walk) are executed before the base navigation controller in
update().- Parameters:
controller – A
Controllerinstance.- Return type:
- remove_controller(controller_or_cls)
Remove a non-base controller by instance or class.
The base controller (index 0) cannot be removed via this method. Use
set_controller()to replace it.When a class is given, the first instance of that class (excluding the base controller) is removed. When an instance is given, that exact instance is removed.
- Parameters:
controller_or_cls – A Controller instance or subclass.
- Return type:
- get_controller_by_type(cls)
Return the first controller matching cls, or
None.Searches the entire chain (including the base controller).
- property controller
Return the base (index-0) controller, or
Noneif the chain is empty.
- stop()
Stop robot movement and clear goal and path.
- is_urdf_robot()
Check if this robot is URDF-based (has joints).
- Return type:
- get_num_joints()
Get number of joints (0 for mesh robots).
- Return type:
- get_joint_state(joint)
Get joint state (position and velocity).
For kinematic robots (mass=0), returns the cached position and velocity=0.0, avoiding a PyBullet C call. For physics robots the value is read from
p.getJointState().Works for a fixed joint as for any other.
- Parameters:
joint (
Union[int,str]) – Joint index (0-based), or joint name as spelled in the URDF. The old keywordjoint_index=is still accepted.- Return type:
- Returns:
(position, velocity) tuple;
(0.0, 0.0)with a warning for a non-URDF body or an unknown joint name.- Raises:
pybullet.error – If joint is an index this body does not have.
Example:
pos, vel = robot.get_joint_state(0) pos, vel = robot.get_joint_state("elbow_to_wrist")
- get_joint_state_by_name(joint_name)
Get (position, velocity) for a single joint by name. Returns (position, velocity) or (0.0, 0.0) if not found.
Deprecated, removed in 0.10.0: use
get_joint_state(), which also takes a name.- Return type:
- capture_kinematic_joint_execution()
Capture every joint’s position, command, motion limits and execution.
A solved trajectory is represented by its primitive inputs and how long the joint has followed it (as
t0_offset, its negative). Rebuilding it preserves the phase reached at this completed-step boundary without serializing the TPI instance itself.
- restore_kinematic_joint_execution(states)
Restore joint commands and execution at a completed-step boundary.
- Return type:
- get_all_joints_state()
Return a list of (position, velocity) for all joints. Example: [(pos0, vel0), (pos1, vel1), …]
- Return type:
- get_all_joints_state_by_name()
Return a dict of {joint_name: (position, velocity)} for all joints. Example: {joint_name: (pos, vel), …}
- Return type:
- get_joints_state_by_name(joint_names)
Return a dict of {joint_name: (position, velocity)} for the specified joint_names. Example: {joint_name: (pos, vel), …}
- Return type:
- set_joint_target(joint, target_position, max_force=500.0)
Set target position for a joint (for URDF robots only).
An unknown joint name or an index out of range is ignored with a warning; a fixed joint is ignored silently.
- Parameters:
Example:
robot.set_joint_target(0, 1.57) # Move first joint to 90 degrees robot.set_joint_target("base_to_shoulder", 1.57)
- set_joint_position(joint, position, max_force=500.0)
Put a joint at
positionat once, without moving it there.The joint counterpart of
set_pose(): what a simulator’s “set entity state” asks of a fixed-base mechanism such as a lift cabin, where placing the base would carry the whole mechanism away.positionalso becomes the joint’s target, so the step loop keeps it there instead of resuming a motion towards an older target, and any speed or plan from a motion profile is dropped. Objects attached to the robot’s links follow at once, and the body counts as moved for the next collision check. An action still driving this joint is not cancelled; cancel it first if it should not move the joint again.A position outside the joint’s URDF limits is applied, with a warning.
- Parameters:
- Return type:
- Returns:
True if the joint was set; False for a non-URDF body, an unknown or fixed joint.
- set_joints_positions(positions, max_force=500.0)
Put several joints at their positions at once, as
set_joint_position()does for one.Accepts what
set_joints_targets()accepts: a list with a position for every joint, in joint-index order (a fixed joint’s entry is ignored), or a dict{joint name or index: position}for some of them. Attached objects follow once, after every joint is placed.- Return type:
- Returns:
True if every given joint was set; False for a non-URDF body, a list of the wrong length (nothing is set), or a dict naming an unknown or fixed joint (the others are still set).
- set_joint_target_by_name(joint_name, target_position, max_force=500.0)
Set target position for a joint by joint name.
Deprecated, removed in 0.10.0: use
set_joint_target(), which also takes a name.
- set_all_joints_targets(target_positions, max_force=500.0)
Set target positions for all joints at once.
- Parameters:
Example:
robot.set_all_joints_targets([0.0, 1.57, -1.57, 0.0])
- set_joints_targets_by_name(joint_targets, max_force=500.0)
Set multiple joint targets by dict {joint_name: target_position} (partial update allowed).
- set_joints_targets(targets, max_force=500.0)
Set joint targets (accepts both list and dict).
- Parameters:
Example:
# Using list robot.set_joints_targets([0.0, 1.57, -1.57, 0.0]) # Using dict robot.set_joints_targets({"joint1": 1.57, "joint2": -1.57})
- is_joint_at_target(joint, target, tolerance=None)
Check if a single joint is within tolerance of the target position.
- Parameters:
joint (
Union[int,str]) – Joint index (0-based), or joint name as spelled in the URDF. The old keywordjoint_index=is still accepted.target (
float) – Target position (radians for revolute, metres for prismatic).tolerance (
Union[float,list,dict,None]) – Position tolerance —float,list,dict, orNone(→self.joint_tolerance). Resolved via_resolve_joint_tolerance()using the joint’s index.
- Return type:
- Returns:
True if the joint is within tolerance; False, with a warning, for a non-URDF body, an unknown joint name or an index out of range.
- is_joint_at_target_by_name(joint_name, target, tolerance=None)
Check if a single joint (by name) is within tolerance of the target position.
- Parameters:
joint_name (
str) – Joint name string.target (
float) – Target position (radians for revolute, metres for prismatic).tolerance (
Union[float,list,dict,None]) – Position tolerance —float,list,dict, orNone(→self.joint_tolerance). Resolved via_resolve_joint_tolerance()using the joint’s index.
- Return type:
Deprecated, removed in 0.10.0: use
is_joint_at_target(), which also takes a name.
- are_all_joints_at_targets(target_positions=None, tolerance=None)
Check if joints are at target positions.
- Parameters:
target_positions (
Optional[list]) – List of target positions for each joint. If None, uses the last commanded targets.tolerance (
Union[float,list,dict,None]) –float,list,dict, orNone. If None, usesself.joint_tolerance. Passed through to_resolve_joint_tolerance()per joint.Note
A scalar tolerance applies the same value to all joints. For mixed prismatic (metres) / revolute (radians) robots, consider a
dictkeyed by joint name or setself.joint_toleranceto a dict.
- Return type:
- Returns:
True if all joints are within tolerance of their targets.
- are_joints_at_targets_by_name(joint_targets, tolerance=None)
Check if all specified joints (by name) are within tolerance.
- Parameters:
joint_targets (
dict) –{joint_name: target}tolerance (
Union[float,list,dict,None]) –float(all),dict({joint_name: tol}), orNone(→self.joint_tolerance).A
listis also accepted but is resolved by absolute joint index (not by iteration order of joint_targets). For named-joint subsets, prefer adictto avoid unexpected index-based fallback.For mixed prismatic / revolute chains, use a
dictso prismatic joints (metres) can have a tighter tolerance than revolute joints (radians).
- Return type:
- Returns:
True if all joints are within tolerance, False otherwise.
- are_joints_at_targets(targets=None, tolerance=None)
Check if joints are at target positions.
- Parameters:
targets (
Union[list,dict,None]) – List of target positions for all joints, dict{joint_name: position}, or None to use the last commanded targets.tolerance (
Union[float,list,dict,None]) –Tolerance value(s) —
float,list,dict, or None (→self.joint_tolerance).For mixed prismatic / revolute chains, use a
dictso prismatic joints (metres) can have a tighter tolerance than revolute joints (radians):agent.are_joints_at_targets( targets, tolerance={"rail_joint": 0.005, "elbow_to_wrist": 0.05}, )
- Return type:
- Returns:
True if all joints are within tolerance, False otherwise.
Example:
# No args — check last commanded targets with agent's default tolerance if robot.are_joints_at_targets(): print("All joints settled") # Using list if robot.are_joints_at_targets([0.0, 1.57, -1.57, 0.0], tolerance=0.01): print("Reached target") # Using dict if robot.are_joints_at_targets({"joint1": 1.57, "joint2": -1.57}, tolerance=0.01): print("Reached target")
- property ik_params: IKParams
Read-only access to the IK solver configuration.
- move_end_effector(target_position, target_orientation=None, end_effector_link=None, max_force=500.0, tolerance=None)
Set end-effector target position via inverse kinematics.
Solves IK, checks reachability, and calls
set_all_joints_targets()internally. Actual movement happens inupdate()(fire-and-forget, likeset_joint_target()).When the solver returns an IK candidate, its joint targets are set even when the target is unreachable (best-effort). If no candidate is available, no new joint target is issued. The return value tells the caller whether the IK solution actually reaches the desired position.
- Parameters:
target_position (
List[float]) – Target EE position [x, y, z] in world frame.target_orientation (
Optional[Tuple[float,float,float,float]]) – Target EE orientation as quaternion [qx, qy, qz, qw].end_effector_link (
Union[int,str,None]) – End-effector link (int, str, or None for auto-detect).max_force (
float) – Maximum force for motor control (physics mode).tolerance (
Optional[float]) – Euclidean distance (m) for reachability check. If None, usesik_params.reachability_tolerance.
- Return type:
- Returns:
True if the IK solution places the EE within tolerance of the target (reachable). False otherwise. A best-effort candidate, when available, is still commanded.
Example:
reachable = arm.move_end_effector([0.3, 0.0, 0.5]) if not reachable: print("Target may not be fully reachable")
- are_ee_at_target(target_position, target_orientation=None, end_effector_link=None, tolerance=0.02, orientation_tolerance=0.15)
Check whether the end-effector is near the target pose.
Resolves the EE link and delegates to
_check_ee_pose().- Parameters:
target_position (
List[float]) – Target EE position [x, y, z] in world frame.target_orientation (
Optional[Tuple[float,float,float,float]]) – Target EE orientation as quaternion [qx, qy, qz, qw]. If None, only position is checked.end_effector_link (
Union[int,str,None]) – Link index, name, or None (auto-detect).tolerance (
float) – Maximum Euclidean distance (m) to consider reached.orientation_tolerance (
float) – Maximum1 - |dot|between actual and target quaternions (default 0.15).
- Return type:
- Returns:
True if the EE is within tolerance of the target.
- update_attached_objects_kinematics()
For URDF robots: update attached objects’ pose to follow the parent link (kinematics attach). This is called every step for kinematic (mass=0) attached objects.
pybullet_fleet.agent_manager module
core/agent_manager.py Management classes for simulation objects and agents. - SimObjectManager: Base manager for all simulation objects - AgentManager: Extended manager with movement control for agents
- class pybullet_fleet.agent_manager.GridSpawnParams(x_min, x_max, y_min, y_max, spacing, offset, z_min=0, z_max=0)
Bases:
objectGrid parameters for object spawning in 3D space.
- x_min
Minimum X grid index
- x_max
Maximum X grid index
- y_min
Minimum Y grid index
- y_max
Maximum Y grid index
- spacing
Grid spacing [spacing_x, spacing_y, spacing_z] in meters
- offset
Grid offset [offset_x, offset_y, offset_z] in meters
- z_min
Minimum Z grid index (defaults to 0)
- z_max
Maximum Z grid index (defaults to 0 for 2D grids)
Note
Objects spawn in X → Y → Z order. For 2D grids, set z_min=z_max=0 (default). For 3D grids, set z_max > z_min to enable vertical layers.
- x_min: int
- x_max: int
- y_min: int
- y_max: int
- z_min: int = 0
- z_max: int = 0
- property total_cells: int
(x range) * (y range) * (z range).
- Type:
Total number of grid cells
- classmethod from_dict(config)
Create GridSpawnParams from a configuration dictionary.
Supports two formats:
Explicit ranges (original) — requires
x_min,x_max,y_min,y_max,spacing,offset:grid: x_min: 0 x_max: 9 y_min: 0 y_max: 4 spacing: [3.0, 3.0, 0.0] offset: [0, 0, 0.05]
Count-based (convenience) — requires
countandspacing;columnsandoffsetare optional:grid: count: 50 spacing: [3.0, 3.0] offset: [0, 0, 0.05] columns: 10
When
countis present,from_count()is used to compute the grid ranges.
- classmethod from_count(count, columns=None, spacing=None, offset=None)
Create GridSpawnParams from a total entity count.
Computes
x_maxandy_maxfrom count and columns so that the grid has exactly enough cells. Useful when you know “I want 50 robots” rather than “x_max=9, y_max=4”.- Parameters:
count (
int) – Total number of entities to place.columns (
Optional[int]) – Grid width (X cells) before wrapping to the next row. Defaults toceil(sqrt(count)).spacing (
Optional[List[float]]) –[sx, sy, sz]in metres. Default[1,1,0].offset (
Optional[List[float]]) –[ox, oy, oz]origin offset. Default[0,0,0].
- Return type:
GridSpawnParams- Returns:
GridSpawnParams with
x_min=0,y_min=0,x_max=columns-1,y_max=ceil(count/columns)-1.
- class pybullet_fleet.agent_manager.SimObjectManager(sim_core=None, object_class=<class 'pybullet_fleet.sim_object.SimObject'>, enable_profiling=False)
Bases:
Generic[T]Base manager class for simulation objects (SimObject and Agent).
This class provides centralized control of multiple simulation objects.
Features: - Grid-based object spawning - Query all object poses - Get object count
- Type Parameter:
T: Type of objects managed (must be SimObject or its subclass)
- __init__(sim_core=None, object_class=<class 'pybullet_fleet.sim_object.SimObject'>, enable_profiling=False)
Initialize SimObjectManager.
- Parameters:
sim_core – Reference to simulation core (optional)
object_class (
type) – Default class to instantiate when spawning (SimObject or a subclass such as Agent).enable_profiling (
bool) – IfTrue, spawn methods log elapsed time vialogger.info. DefaultFalse. Can be overridden later:mgr.enable_profiling = True.
- enable_profiling: bool
- objects: List[T]
- add_object(obj)
Add an object to the manager.
- Parameters:
obj (
TypeVar(T, bound=SimObject)) – SimObject or Agent instance to add- Return type:
- Returns:
None. The object is silently skipped (with a warning) when its
object_idis invalid (< 0), which typically means it was created without a sim_core.
Note
Objects are automatically registered to sim_core.sim_objects via SimObject.__init__(), so we don’t register them here again.
- remove_object(obj)
Remove an object from the manager’s tracking lists.
This only removes the object from the manager’s bookkeeping (
objects,body_ids,object_ids). It does not touchsim_coreor PyBullet — that is handled byMultiRobotSimulationCore.remove_object().Called automatically by
sim_core.remove_object()when this manager is registered viasim_core.register_manager().
- clear()
Remove all objects from the manager’s tracking lists.
This is a manager-only operation — it does not remove objects from
sim_coreor PyBullet. Typically called bysim_core.reset()to keep the manager in sync after a full simulation reset.- Return type:
- spawn_objects_grid(num_objects, grid_params, spawn_params, *, name_prefix=None)
Spawn multiple objects in a grid pattern.
This is a convenience wrapper around
spawn_grid_countsfor spawning a single object type with a specified count.- Parameters:
num_objects (
int) – Number of objects to spawngrid_params (
GridSpawnParams) – GridSpawnParams instance with grid configurationspawn_params (
SimObjectSpawnParams) – SimObjectSpawnParams instance with object parametersname_prefix (
Optional[str]) – Optional prefix for stable generated names (<prefix>_0,<prefix>_1, …).
- Return type:
- Returns:
List of spawned object instances
- spawn_grid_mixed(num_objects, grid_params, spawn_params_list, *, name_prefix=None)
Spawn multiple SimObjects in a grid pattern with mixed types.
This method allows spawning different types of objects with specified probabilities. If probabilities don’t sum to 1.0, some grid positions may remain empty.
- Parameters:
num_objects (
int) – Maximum number of objects to spawngrid_params (
GridSpawnParams) – GridSpawnParams instance with grid configurationspawn_params_list (
List[Tuple[SimObjectSpawnParams,float]]) – List of (spawn_params, probability) tuples - spawn_params: SimObjectSpawnParams for this type - probability: Spawn probability (0.0 to 1.0) Note: Probabilities don’t need to sum to 1.0name_prefix (
Optional[str]) – Optional prefix for stable generated names (<prefix>_0,<prefix>_1, …).
- Return type:
- Returns:
List of spawned SimObject instances
Example:
# Spawn 100 objects: 60% typeA, 30% typeB, 10% empty spawn_params_list = [ (typeA_params, 0.6), (typeB_params, 0.3), ] manager.spawn_grid_mixed(100, grid_params, spawn_params_list)
- spawn_grid_counts(grid_params, spawn_params_count_list, *, name_prefix=None)
Spawn objects on a grid according to the specified count for each type.
Each type is spawned exactly the requested number of times. Grid positions are randomly shuffled unless
name_prefixis set; prefixed names keep deterministic grid placement so<prefix>_imaps to a stable position across runs.- Parameters:
- Return type:
- Returns:
List of spawned objects
- Raises:
ValueError – If the total count exceeds the number of grid cells.
- spawn_objects_batch(params_list)
Batch API to spawn multiple object instances at once.
When sim_core provides
batch_spawn(), rendering is disabled and the spatial grid rebuild is deferred until all objects are created.
- spawn_from_config(entities_yaml)
Spawn entities from a list of config dicts.
Dispatches to
entity_cls.from_dict()for each entity, which internally calls the appropriateSpawnParams.from_dictandfrom_params. Custom entity classes can overridefrom_dictto use their ownSpawnParams.If a dict has no
typefield,"agent"is assumed for backward compatibility. Supported types:"agent","sim_object", or any custom type registered viaregister_entity_class().
- spawn_from_yaml(yaml_path, key='entities')
Load a YAML file and spawn entities from the specified section.
Reads yaml_path, extracts the key section (default
"entities"), and delegates tospawn_from_config().- Parameters:
- Return type:
- Returns:
List of spawned objects (empty if key is missing).
- Raises:
FileNotFoundError – If yaml_path does not exist.
- get_pose(object_index)
Get current pose of a specific object.
- get_all_poses()
Get current poses of all objects.
- Return type:
List[Pose]- Returns:
List of Pose objects for all objects
- get_poses_dict()
Get current poses of all objects as a dictionary.
- set_pose_all(pose_factory)
Set pose for all objects using a factory function.
Applies pose_factory to each object and immediately calls
set_posewith the returned value. Works for both SimObject and Agent instances.- Parameters:
pose_factory (
Callable[[TypeVar(T, bound=SimObject)],Pose]) – Function that takes an object and returns a target Pose.- Return type:
Example:
# Shift every object 1 m along X manager.set_pose_all(lambda obj: Pose.from_xyz( obj.get_pose().x + 1.0, obj.get_pose().y, obj.get_pose().z, ))
- get_object_count()
Get total number of managed objects.
- Return type:
- class pybullet_fleet.agent_manager.AgentManager(sim_core=None, name=None, update_frequency=10.0, object_class=<class 'pybullet_fleet.agent.Agent'>, enable_profiling=False, fleet_controller=None)
Bases:
SimObjectManager[Agent]Extended manager class for agents with update callback system.
This class extends SimObjectManager with agent-specific features: - Grid-based agent spawning with AgentSpawnParams - Pose goal assignment to individual agents - Callback system for custom update logic (goals, state tracking, etc.) - Query moving/stopped agents - Optional batch controller for vectorized kinematic updates (
fleet_controller={"type": ...}orenable_batch())Key Features: - Auto-registers update callback to simulation loop - Callback receives (agents, manager, dt) for easy agent operations - Configurable update frequency - Direct access to manager methods within callback
Note: - Agent.update() is automatically called by MultiRobotSimulationCore every step - AgentManager callbacks are for high-level logic (goals, coordination, etc.) - Agent-specific state can be stored in each Agent.user_data dict
- __init__(sim_core=None, name=None, update_frequency=10.0, object_class=<class 'pybullet_fleet.agent.Agent'>, enable_profiling=False, fleet_controller=None)
Initialize AgentManager.
- Parameters:
sim_core – Reference to simulation core (optional)
name (
Optional[str]) – Optional name for this manager. When set, the manager can be retrieved later viaget_manager().update_frequency (
float) – Default update callback frequency in Hz (default: 10.0)object_class (
type) – Class to instantiate when spawning (default: Agent). Pass an Agent subclass to manage custom agent types.enable_profiling (
bool) – IfTrue, spawn methods log elapsed time. DefaultFalse.fleet_controller (
Optional[Dict[str,Any]]) – Manager controller configuration.typemay be"batch_omni"or"batch_differential"to enable vectorized movement for every managed agent; omit it for per-agent execution. The remaining keys are sharedControllerParamsdefaults applied only where an agent did not set that field in its owncontroller:config.
- property agents: List[Agent]
The agents this manager holds, skipping anything that is not one.
spawn_from_config()dispatches on each entry’stype, so a config may mixagentandsim_objectandobjectscan hold both. Everything on this class that commands movement, reads motion state or queues actions is agent-only, and reads this rather thanobjects.
- enable_batch(mode)
Create and attach a batch controller for mode, replacing any existing one.
Any agents already managed by this instance that are not yet batch-controlled are registered immediately. Agents spawned afterwards are registered automatically via
add_object().- Parameters:
mode (
str) – Batch controller registry name (e.g."batch_omni","batch_differential") or a dotted import path to a customBatchKinematicControllersubclass (e.g."my_pkg.MyBatchController").- Return type:
- Returns:
The newly-created
BatchKinematicController.- Raises:
ValueError – If mode is not recognised.
- disable_batch()
Unregister all managed agents from the batch controller and detach it.
- Return type:
- add_object(obj)
Add an object, wiring up the agent-only parts only for agents.
An
AgentManagercan legitimately hold a plainSimObject:spawn_from_config()dispatches on each entry’stypeand a config may mixagentandsim_object. Everything below is agent-only, though – the fleet-controller defaults readcontroller_paramsand the batch controller reads_batch_controller, neither of which aSimObjecthas – so a mixed manager used to raiseAttributeErrorfrom inside this method as soon as either controller was attached. That could be long after the object was added, and it read as a fault inenable_batch()rather than in the mix.- Return type:
- remove_object(obj)
Remove an object from the manager’s tracking lists.
This only removes the object from the manager’s bookkeeping (
objects,body_ids,object_ids). It does not touchsim_coreor PyBullet — that is handled byMultiRobotSimulationCore.remove_object().Called automatically by
sim_core.remove_object()when this manager is registered viasim_core.register_manager().- Parameters:
obj (
Agent) – The object to remove.- Return type:
- Returns:
True if the object was found and removed, False otherwise.
- spawn_agents_grid(num_agents, grid_params, spawn_params, *, name_prefix=None)
Spawn agents in a grid. Alias for
spawn_objects_grid().- Return type:
List[Agent]
- spawn_agents_grid_mixed(num_agents, grid_params, spawn_params_list, *, name_prefix=None)
Spawn mixed agent types. Alias for
spawn_grid_mixed().- Return type:
List[Agent]
- spawn_agent_grid_counts(grid_params, spawn_params_count_list, *, name_prefix=None)
Spawn exact counts per type. Alias for
spawn_grid_counts().- Return type:
List[Agent]
- set_goal_pose(agent_index, goal)
Set goal pose for a specific agent.
- set_goal_pose_by_body_id(body_id, goal)
Set goal pose for an agent by its PyBullet body ID.
Note
This method uses PyBullet’s internal body_id for compatibility with direct PyBullet API usage. For manager-level operations, prefer using set_goal_pose_by_object_id() instead.
- set_goal_pose_by_object_id(object_id, goal)
Set goal pose for an agent by its simulation object ID.
This is the preferred method for manager-level operations, as it uses the simulation’s unique object_id rather than PyBullet’s internal body_id.
- stop_all()
Stop all agents and clear their goals.
- set_goal_pose_all(goal_factory)
Set goal pose for all agents using a factory function.
This helper method simplifies bulk goal assignment by applying a factory function to each agent. The factory can use agent-specific data (current pose, user_data, etc.) to create customized goals.
- Parameters:
goal_factory (
Callable[[Agent],Pose]) – Function that takes an Agent and returns a Pose- Return type:
Example:
# Set all agents to move to their designated home positions def get_home_goal(robot): return robot.user_data['home_position'] manager.set_goal_pose_all(get_home_goal) # Move all agents 5 meters forward from their current position def move_forward(robot): current_pos = robot.get_pose().position return Pose.from_xyz(current_pos[0] + 5, current_pos[1], current_pos[2]) manager.set_goal_pose_all(move_forward)
Note
This is a convenience wrapper around individual set_goal_pose calls. No performance benefit over explicit loops, but improves code clarity.
- set_joints_targets_all(targets_factory, max_force=500.0)
Set joint targets for all agents using a factory function.
This helper method simplifies bulk joint control by applying a factory function to each agent. Useful for coordinated multi-robot arm movements.
- Parameters:
- Return type:
Example:
# Set all robot arms to neutral position def get_neutral_joints(robot): return [0.0, 0.0, 0.0, 0.0] manager.set_joints_targets_all(get_neutral_joints) # Set custom positions based on robot index def get_custom_joints(robot): idx = robot.user_data.get('index', 0) return [idx * 0.1, 0.0, 0.0, 0.0] manager.set_joints_targets_all(get_custom_joints, max_force=1000.0)
Note
Only applicable to agents with controllable joints (robot arms, etc.). Mobile robots without arm joints will ignore this command.
- get_moving_count()
Get number of agents currently moving.
- Return type:
- add_action_sequence_all(action_factory)
Apply action sequence to all agents using a factory function.
This helper method simplifies bulk action assignment by applying a factory function to each agent. The factory can use agent-specific data (pose, user_data, etc.) to create customized action sequences.
- Parameters:
action_factory (
Callable[[Agent],List[Any]]) – Function that takes an Agent and returns a list of Actions- Return type:
Example:
def create_pick_drop_sequence(robot): target = robot.user_data['target_object'] return [ PickAction(target_object_id=target.body_id), MoveAction(path=Path.from_positions([[10, 10, 0]])), DropAction(drop_pose=Pose(position=[10, 10, 0])) ] # Apply to all agents at once manager.add_action_sequence_all(create_pick_drop_sequence)
Note
This is a convenience wrapper. Internally it still loops through agents, so there’s no performance benefit over explicit loops. The main advantage is code clarity and reduced boilerplate.
- add_action_all(action_factory)
Add a single action to all agents using a factory function.
Similar to add_action_sequence_all, but adds a single action instead of a sequence.
- Parameters:
action_factory (
Callable[[Agent],Any]) – Function that takes an Agent and returns a single Action- Return type:
Example:
def create_move_action(robot): goal_pos = robot.user_data['next_position'] return MoveAction(path=Path.from_positions([goal_pos])) manager.add_action_all(create_move_action)
- register_callback(callback, frequency=None)
Register a callback for custom agent update logic.
Multiple callbacks can be registered, each with their own frequency. This method automatically registers with sim_core if available.
The callback provides access to the AgentManager instance, making it easy to: - Access all agents via manager.objects - Use manager methods (set_goal_pose, query states, etc.) - Store manager-level state in agent.user_data
- The callback should have signature:
callback(manager: AgentManager, dt: float) -> None
- Parameters:
Example (Goal management):
def goal_update_logic(manager, dt): for agent in manager.objects: if not agent.is_moving: # Set new goal for stopped agents new_goal = calculate_next_goal(agent) agent.set_goal_pose(new_goal) manager.register_callback(goal_update_logic, frequency=4.0)
Example (State tracking):
def state_tracker(manager, dt): for agent in manager.objects: # Track agent statistics if 'total_distance' not in agent.user_data: agent.user_data['total_distance'] = 0.0 agent.user_data['total_distance'] += np.linalg.norm(agent.velocity) * dt manager.register_callback(state_tracker, frequency=10.0)
Comparison with sim_core.register_callback():
AgentManager callback: Provides manager reference and filtered agent list
sim_core callback: Provides sim_core reference for all objects
Use AgentManager for agent-specific operations
Use sim_core for general simulation-wide operations
- setup_camera(camera_config=None)
Setup camera to view all managed objects in the simulation.
This method automatically extracts positions from all managed objects and configures the camera to fit them in the view.
- Parameters:
camera_config (
Optional[Dict]) – Dictionary with camera settings (from yaml config). If None, uses default settings.- Return type:
Example:
# Basic usage with default settings agent_manager.setup_camera() # With custom camera config camera_config = { 'camera_mode': 'auto', 'camera_view_type': 'top_down', 'camera_auto_scale': 0.8 } agent_manager.setup_camera(camera_config)
Note
Requires sim_core to be set during AgentManager initialization. Only works when GUI is enabled.
pybullet_fleet.agent_plugin module
AgentPlugin — per-agent lifecycle-managed plugins.
Provides a lightweight plugin system for attaching reusable behaviours
to individual Agent instances.
Each plugin receives lifecycle callbacks and has access to its owning
agent via self.agent.
Lifecycle:
__init__(agent, config) # construction
on_init() # after agent is fully constructed
on_update(dt) # each Agent.update() step
on_reset() # when agent state is reset
on_destroy() # when agent is removed / sim shuts down
All hooks are optional no-ops by default — override only what your plugin needs.
Registry
from pybullet_fleet.agent_plugin import create_agent_plugin
plugin = create_agent_plugin("battery", agent)
plugin = create_agent_plugin("battery", agent, {"charge_rate": 0.01})
Subclasses with a _registry_name class attribute are auto-registered:
class BatteryPlugin(AgentPlugin):
_registry_name = "battery"
...
YAML usage:
plugins:
- type: "battery"
config: {}
- class: "my_project.sensors.LidarPlugin"
config:
range: 10.0
- pybullet_fleet.agent_plugin.register_agent_plugin(name, cls)
Register a plugin class under name.
- Return type:
- pybullet_fleet.agent_plugin.create_agent_plugin(name, agent, config=None)
Create a plugin by registered name.
Convenience wrapper around
create_agent_plugin_from_entry()for use in Python code where building an entry dict is verbose.
- pybullet_fleet.agent_plugin.list_agent_plugins()
Return a copy of the agent plugin registry for inspection.
- pybullet_fleet.agent_plugin.create_agent_plugin_from_entry(entry, agent)
Create a plugin from a YAML-style config entry.
Supports two formats:
Registry shorthand:
{"type": "battery", "config": {...}}Dotted path:
{"class": "my_pkg.MyPlugin", "config": {...}}
- Parameters:
- Return type:
AgentPlugin- Returns:
Instantiated
AgentPlugin.- Raises:
KeyError – If
typeis not in the registry.TypeError – If
classdoes not resolve to an AgentPlugin subclass.ValueError – If neither
typenorclassis present.
- class pybullet_fleet.agent_plugin.AgentPlugin(agent)
Bases:
objectBase class for per-agent plugins.
Lifecycle:
__init__(agent) # construction (typed kwargs in subclasses) on_init() # after agent is fully constructed on_update(dt) # each simulation step on_reset() # when agent state is reset on_destroy() # when agent is removed / sim shuts down
Subclasses override the hooks they need. All hooks are no-ops by default.
Subclasses with a
_registry_nameclass attribute are auto-registered inAGENT_PLUGIN_REGISTRY(e.g._registry_name = "battery").- agent
The owning
Agentinstance.
- config
Raw configuration dict (populated by
from_config()).
- classmethod from_config(agent, config=None)
Create from config dict, matching keys to
__init__parameters.Works like
Controller.from_config(): inspects the subclass__init__signature and passes matching keys as kwargs. The raw config dict is stored asconfig.
- on_init()
Called after the agent is fully constructed.
Override to perform one-time setup that depends on the agent being registered with sim_core. No-op by default.
- Return type:
- on_update(dt)
Called each simulation step from
Agent.update().Override in subclasses. Default is a no-op.
- on_reset()
Called when the agent’s state is reset.
Override to reinitialise plugin state. No-op by default.
- Return type:
- on_destroy()
Called when the agent is removed or the simulation shuts down.
Override to release resources. No-op by default.
- Return type:
pybullet_fleet.camera_controller module
Interactive camera control for PyBullet GUI.
Provides right-drag and arrow-key camera panning, keyboard zooming, and view presets.
Integrated via _handle_keyboard_events() in MultiRobotSimulationCore.
- class pybullet_fleet.camera_controller.CameraController(client_id, drag_sensitivity=0.01, zoom_speed=1.0)
Bases:
objectInteractive camera control for PyBullet GUI.
Call
update()each simulation step with the result ofp.getKeyboardEvents()andp.getMouseEvents()to process camera movement.Controls: - Right-drag — pan camera target (no conflict with native left-drag rotation) - Arrow keys — pan the camera target in the horizontal camera-local plane -
=/-— zoom in / out -o— top-down view- update(keys, mouse_events=None)
Process keyboard + mouse events and update camera.
Only calls
resetDebugVisualizerCamerawhen our controls actually changed something. This avoids interfering with PyBullet’s native camera manipulation (left-drag rotation, scroll zoom) when idle.
- follow_target(target)
Move only the camera target, preserving the user’s view angles.
- Return type:
pybullet_fleet.cli module
Command-line interface for pybullet_fleet.
Exposes pybullet-fleet examples and pybullet-fleet config so a
pip-installed user can locate, list, copy, or run bundled assets without
cloning the repository. The assets ship inside the wheel (see
[tool.setuptools.package-data]), so they live next to the installed package.
- pybullet_fleet.cli.main(argv=None)
- Return type:
pybullet_fleet.collision_visualizer module
collision_visualizer.py Utilities for visualizing collision shapes in PyBullet.
Deprecated since version This: module is not actively used. Collision visualization is handled
directly by core_simulation.py. This file will be removed in a
future release.
- class pybullet_fleet.collision_visualizer.CollisionVisualizer
Bases:
objectHandles visualization of collision shapes as debug wireframes. Independent from visual shape rendering. Optimized for fast toggle by caching debug items.
- set_visible(visible)
Show or hide collision shapes (optimized toggle).
- clear()
Remove all collision shape debug items.
- Return type:
- draw_all_collision_shapes(simplified=True, max_objects=1000)
Draw collision shapes for all bodies as debug wireframes.
- draw_body_aabb(body_id, color=[0, 1, 0], base_only=True)
Draw only AABB for a body (fast, simplified visualization).
pybullet_fleet.commands module
Transport-neutral fleet command and acknowledgement types.
- class pybullet_fleet.commands.RobotGoalCommand2D(name, position, yaw=0.0, z=None, command_id=None)
Bases:
objectPlanar navigation command for one robot.
zis the goal’s height.None(the default) keeps the robot’s present height, so a planar goal never moves it up or down; a goal at another height is a 3D move, which a moving robot can only continue into along its line of motion (seeAgent.set_path()).- name: str
- yaw: float = 0.0
- to_pose(current_z=0.0)
Convert this command to a simulation
Pose.current_zis the robot’s present height, used whenzisNone.- Return type:
Pose
- class pybullet_fleet.commands.RobotGoalCommand3D(name, position, orientation=(0.0, 0.0, 0.0, 1.0), command_id=None)
Bases:
object3D navigation command for one robot.
- name: str
- to_pose(current_z=0.0)
Convert this command to a simulation
Pose.current_zis accepted for symmetry withRobotGoalCommand2D.to_pose()and unused: a 3D goal names its height.- Return type:
Pose
- class pybullet_fleet.commands.RobotJointPositionsCommand(name, positions)
Bases:
objectOrdered joint target command for one robot.
- name: str
- class pybullet_fleet.commands.RobotNamedJointPositionsCommand(name, positions)
Bases:
objectNamed joint target command for one robot.
- name: str
- class pybullet_fleet.commands.RobotAttachCommand(name, attach, object_name='', parent_link='base_link', offset=<factory>, search_radius=0.5)
Bases:
objectAttach or detach a simulation object for one robot.
- name: str
- attach: bool
- object_name: str = ''
- parent_link: str = 'base_link'
- offset: Pose
- search_radius: float = 0.5
- class pybullet_fleet.commands.RobotActionCommand(name, action_type, action_params_json='', command_id=None)
Bases:
objectGeneric PyBulletFleet action command for one robot.
- name: str
- action_type: str
- action_params_json: str = ''
- class pybullet_fleet.commands.CommandAck(command_id, source, sim_time, accepted_names=<factory>, rejected=<factory>)
Bases:
objectResult of accepting or rejecting a fleet command.
- command_id: str
- source: str
- sim_time: float
- property ok: bool
Whether at least one target was accepted and none were rejected.
pybullet_fleet.config_utils module
config_utils.py Utility functions for loading and merging configuration files.
- pybullet_fleet.config_utils.load_yaml_config(config_path)
Load a YAML config file and return parsed contents.
General-purpose YAML loader. Works for any YAML config file (simulation, bridge, spawn definitions, etc.).
- Parameters:
config_path (
str) – Path to YAML config file.- Return type:
- Returns:
Parsed config dict.
- Raises:
FileNotFoundError – If config_path does not exist.
- pybullet_fleet.config_utils.merge_configs(base_config, override_config)
Recursively merge two configuration dictionaries.
Values in override_config take precedence over base_config.
- pybullet_fleet.config_utils.config_get_bool(config, key, default)
Read a bool-like value from a config mapping.
Accepts YAML-native booleans and common string forms such as
"true","false","yes","no","1", and"0". YAML integer values0and1are also accepted. Unknown values raiseValueErrorso typos do not silently enable a feature.- Return type:
- pybullet_fleet.config_utils.config_get_str_list(config, key, default=None)
Read a string list from a config mapping.
A single string becomes a one-element list.
Noneand missing keys returndefaultwhen provided, otherwise an empty list.
- pybullet_fleet.config_utils.load_config(config_paths)
Load and merge configuration from one or more YAML files.
If multiple paths are provided, later configs override earlier ones. Delegates to
load_yaml_config()for each file.- Parameters:
config_paths (
Union[str,List[str]]) – Single path string or list of paths to configuration files. Later configs in the list override earlier ones.- Return type:
- Returns:
Merged configuration dictionary
Examples
# Single config config = load_config(‘config.yaml’)
# Multiple configs (100robots_config overrides config.yaml) config = load_config([‘config.yaml’, ‘100robots_config.yaml’])
- pybullet_fleet.config_utils.resolve_class(dotted_path)
Import and return a class from a dotted Python path.
- Parameters:
dotted_path (
str) – Fully-qualified class path, e.g."pybullet_fleet.plugins.workcell_plugin.WorkcellPlugin".- Return type:
- Returns:
The resolved class object.
- Raises:
ValueError – If dotted_path is not a valid
module.ClassNamestring.ModuleNotFoundError – If the module cannot be imported.
AttributeError – If the class is not found in the module.
- pybullet_fleet.config_utils.dataclass_from_dict(cls, config, *, aliases=None, converters=None, strict_keys=None)
Construct a dataclass instance from a config dict via field introspection.
For each
init=Truefield in cls, look up the corresponding config key (or its alias) and apply an optional converter. Fields with defaults are optional; fields without defaults are required.Enum fields are auto-wrapped: if the config value is a
strand the field type is anEnumsubclass, the value is converted viaEnumCls(value).- Parameters:
config (
Dict[str,Any]) – Dict of config values (typically from YAML).aliases (
Optional[Dict[str,str]]) –{field_name: config_key}— alternative config keys. For example{"camera_config": "camera"}reads the"camera"key from config into thecamera_configfield.converters (
Optional[Dict[str,Callable]]) –{field_name: callable}— per-field converters. Called asconverter(raw_value)before assignment. A converter returningNoneskips the field (useful for conditionalNone-passthrough, e.g.collision_detection_method).strict_keys (
Optional[List[str]]) – If provided, only these fields are read from config. All other fields use their dataclass defaults.
- Return type:
TypeVar(T)- Returns:
An instance of cls.
- Raises:
ValueError – If a required field (no default) is missing from config.
Example:
@dataclass class MyParams: x: float = 0.0 mode: MyEnum = MyEnum.A params = dataclass_from_dict(MyParams, {"x": 1.5, "mode": "b"}) assert params.x == 1.5 assert params.mode == MyEnum.B
- pybullet_fleet.config_utils.forward_spawn_params(factory_method, spawn_params, *, aliases=None, extra_kwargs=None)
Build kwargs for a factory method from a dataclass spawn_params.
Introspects the factory_method’s signature and forwards matching fields from spawn_params. Fields named differently can be mapped via aliases (e.g.
{"initial_pose": "pose"}).- Parameters:
factory_method (
Callable) – Target class method (e.g.Agent.from_urdf).spawn_params – Dataclass instance with spawn parameters.
aliases (
Optional[Dict[str,str]]) –{spawn_field: factory_param}— field name remapping.extra_kwargs (
Optional[Dict[str,Any]]) – Additional kwargs to merge (e.g.{"sim_core": sc}).
- Return type:
- Returns:
Dict of keyword arguments ready for
factory_method(**result).
Example:
kwargs = forward_spawn_params( Agent.from_urdf, spawn_params, aliases={"initial_pose": "pose"}, extra_kwargs={"sim_core": sim}, ) agent = Agent.from_urdf(**kwargs)
pybullet_fleet.controller module
Unified controller hierarchy + built-in controllers + registry.
Each kinematic model (omni, differential) gets one controller class that handles
both velocity commands (set_velocity) and pose commands (set_goal_pose /
set_path) via an internal mode state machine.
Hierarchy
Controller (ABC) — pure compute + hooks
└── KinematicController — mode state machine + velocity & pose dispatch
├── OmniController — 6-DoF velocity + omnidirectional TPI pose
└── DifferentialController — unicycle velocity + rotate-then-forward TPI pose
Mode state machine (B3 — input-based + interruption)
IDLE ──set_velocity()──→ VELOCITY
IDLE ──set_goal_pose()──→ POSE
VELOCITY ──set_goal_pose()──→ POSE (cancel velocity)
VELOCITY ──watchdog timeout──→ IDLE
POSE ──set_velocity()──→ VELOCITY (cancel pose/TPI)
POSE ──trajectory complete──→ IDLE
Registry
from pybullet_fleet.controller import create_controller
ctrl = create_controller("omni")
ctrl = create_controller("differential", {"max_linear_vel": 1.5})
- pybullet_fleet.controller.register_controller(name, cls)
Register a controller class under name.
- Return type:
- pybullet_fleet.controller.create_controller(name, config=None)
Create a controller by registered name, optionally passing config.
Convenience wrapper around
create_controller_from_entry().- Raises:
KeyError – If name is not registered.
- Return type:
Controller
- pybullet_fleet.controller.create_controller_from_entry(entry)
Create a controller from a YAML-style entry dict.
Supports two formats:
{"type": "omni", "config": {"max_linear_vel": 2.0}}— registry lookup.{"class": "my_pkg.MyController", "config": {...}}— dotted path.
Both formats use a nested
configsub-dict for parameters.- Return type:
Controller- Returns:
Instantiated
Controller.- Raises:
KeyError – If
typeis not in the registry.TypeError – If
classdoes not resolve to a Controller subclass.ValueError – If neither
typenorclassis present.
- pybullet_fleet.controller.list_controllers()
Return a copy of the controller registry for inspection.
- pybullet_fleet.controller.SET_PATH_OVERRIDE_DEPRECATION = '{}.{} overrides set_path(), which is deprecated: override request_path() instead. From 0.10.0 an overridden set_path() is no longer called for requests sent with Agent.request_path() or by actions.'
Given once per class that overrides
Controller.set_path(); formatted with the class’s module and qualified name.
- pybullet_fleet.controller.overrides_set_path(controller)
Whether
controller’s class overridesController.set_path().An override marked
_only_reorders_arguments(a built-in controller keeping its historical positional order, seeBatchDifferentialController) does nothing but pass its arguments on, so it does not count: requests go straight toController.request_path(). A subclass that overrides it again counts as usual.- Return type:
- pybullet_fleet.controller.send_request(controller, agent, request, preempt=False, internal=False)
Give
requesttocontrollerthe wayAgent.request_pathdoes.A controller whose class overrides
Controller.set_path()– to edit the path, say – gets the request through that override, with the request’s fields as arguments. The override’s call tosuper().set_path()passes on a request that keeps the identity of the one sent, soAgent.path_request_statestill follows it. Any other controller gets it throughrequest_path.internalmarks a request the controller made itself – a braking path – rather than one a user sent. It goes straight torequest_path: an override that edits the user’s paths must not edit the controller’s own, or braking would leave the line of motion.- Return type:
- class pybullet_fleet.controller.Controller(params=None)
Bases:
ABCAgent movement control interface (Strategy pattern).
Pure base class: only
compute()+ lifecycle hooks. All built-in controllers are kinematic: they update agent pose directly viaagent.set_pose(). No physics forces or torques are applied.Subclasses with a
_registry_nameclass attribute are auto-registered via_registry_nameclass attribute (e.g._registry_name = "omni").- abstractmethod compute(agent, dt)
Compute one step of control.
- Return type:
- Returns:
Trueif the agent moved,Falseotherwise.
- params: ControllerParams
- path_rejection(agent, path, direction=None)
Why
pathwould be refused now, orNoneif it would be taken.The default takes every path. The kinematic controllers refuse one only under
goal_replacement="reject".
- brake(agent)
Bring
agentto rest within the deceleration limits; seeAgent.brake, which delegates here.- Return type:
- Returns:
Truewhen a braking motion was started. The default cannot brake and returnsFalse;Agent.stopis then the way to stop.
- request_path(agent, request, preempt=False)
Follow
request;Falseif refused. The core ofset_path().The kinematic controllers implement it. A controller written against
set_path()alone keeps working: itsset_pathis called with the request’s fields.Agent.request_pathgoes through an overriddenset_pathtoo, on any controller (seesend_request()).- Return type:
- set_path(agent, path, final_orientation_align=True, direction=None, preempt=False)
Follow
path:request_path()with aPathRequestof these fields.- Parameters:
agent (
Agent) – Agent to navigate.path (
List[Pose]) – Non-empty list of waypoint Poses.final_orientation_align (
bool) – Rotate to match the last waypoint’s orientation after reaching its position.direction (
Optional[MovementDirection]) –None(usedefault_direction),FORWARD,AUTO, orBACKWARD(differential only).preempt (
bool) – Do not hold the path for the current one underwait_complete(Agent.brakeuses it).
- Return type:
- request_state(agent, request)
What became of
request(seePathRequestState).UNKNOWNby default: a controller that does not track requests.- Return type:
PathRequestState
- classmethod from_config(config)
Create from a config dict.
The dict may contain:
Any field of
ControllerParams(e.g.max_linear_vel,navigation_2d, …). Unknown keys are dropped silently byControllerParams.from_dict.Subclass-specific keys that match the subclass
__init__signature (e.g.wheel_separationforDifferentialController).A
typekey naming the controller; ignored here (consumed bycreate_controller()).
- Return type:
TypeVar(_ControllerT, bound= Controller)
- on_stop(agent)
Called when
stop()is invoked on the agent.- Return type:
- reset()
Reset internal controller state.
- Return type:
- class pybullet_fleet.controller.KinematicController(params=None)
Bases:
GoalReplacementPolicy,ControllerUnified base for kinematic controllers handling both velocity and pose.
- Internal mode state machine:
IDLE — no active command VELOCITY — processing velocity input (body-frame) POSE — processing goal pose via TPI trajectory
- Input-based mode switching with interruption (B3):
set_velocity()→ switch to VELOCITY (cancels POSE if active)set_goal_pose()/set_path()→ switch to POSE (cancels VELOCITY)Watchdog timeout → IDLE
Trajectory complete → IDLE
- property default_direction: MovementDirection
Default movement direction used when
set_pathis called without explicit direction.
- property mode: ControllerMode
Current controller mode.
- property goal_pose: Pose | None
Current goal pose (active waypoint).
- property current_waypoint_index: int
Current waypoint index in the path (0-based).
- property path: List[Pose]
Current path (list of waypoints). Empty when idle.
- compute(agent, dt)
Template: dispatch to velocity or pose handler based on mode.
- Return type:
- on_stop(agent)
Zero all velocity commands, cancel pose, and clear path state.
- Return type:
- reset()
Reset all internal state.
- Return type:
- set_velocity(vx=0.0, vy=0.0, vz=0.0, wx=0.0, wy=0.0, wz=0.0)
Set velocity command (body frame, 6-DoF). Override in subclasses for clamping.
- Return type:
- cancel_pose()
Cancel active pose navigation and switch to IDLE.
- Return type:
- continuation_velocity(agent)
World-frame velocity a new path would continue from, or
None.The agent’s velocity while it is under way (a translation or a velocity command), else
None. A controller that does not continue motion into a new path returnsNone. Used byAgent.brake()and byGoalReplacement.BRAKE.
- pending_path()
The accepted path waiting for the agent to stop, or
None.- Return type:
Optional[PathRequest]
- request_path(agent, request, preempt=False)
Follow
request’s waypoints (set_path()builds one from its arguments).What happens depends on
goal_replacement(seeGoalReplacement).wait_completeholds the path while the current one is in progress and starts it once that one is finished. In the other modes a path that can continue the current motion (or any path at rest) starts at once, from the current velocity; otherwisebrakebrakes along the current motion and starts the path once stopped,immediatestarts it from rest at once, andrejectrefuses it, leaving the current motion and path untouched. Only the latest held path is kept: a newer request, a stop or a cancel drops it, with a log line.The controller owns all path-navigation state: waypoint index, movement direction, final-orientation alignment.
Agent.set_path()handles validation, auto-approach, and visualisation, then delegates here.- Parameters:
agent (
Agent) – Agent to navigate.request (
PathRequest) – The waypoints (non-empty), whether to align to the last one’s orientation, and the direction (None:default_direction; differential only).preempt (
bool) – Do not hold the path for the current one underwait_complete(Agent.brakeuses it); the other rules still apply.
- Return type:
- Returns:
Falsewhen the path is refused (rejectonly);Trueonce it is set or held to start later.
- braking_request(agent)
The path request that brings the moving
agentto rest, orNoneat rest.The one place that decides how this controller brakes:
brake()(and soAgent.brake) sets it, andgoal_replacement="brake"runs it before a path the agent cannot continue into. The default stops at the braking point,|v|^2 / (2 * decel)ahead along the motion, at the configured deceleration (seebraking_request()). A subclass overrides it to brake differently. The request must continue the current motion (the controller’s_replacement_obstaclerule); one that does not is not started – a warning, and the default braking point instead.- Return type:
Optional[PathRequest]
- brake(agent)
Set
braking_request()throughAgent.set_path, never held for the current path.A pending path from an earlier
brakeorwait_completereplacement is dropped. ReturnsFalseat rest.- Return type:
- request_state(agent, request)
What became of
request: being followed, held, followed to its end, or gone (replaced, dropped, stopped, braked or cancelled).- Return type:
PathRequestState
- capture_navigation_state()
Capture the active kinematic pose path, including waypoint and turn phases.
- Return type:
- restore_navigation_state(state, orientation, owner='')
Restore a kinematic pose path without reissuing its navigation command.
ownernames the agent in the log line if the restored pending path is later dropped.- Return type:
- class pybullet_fleet.controller.OmniController(params=None)
Bases:
KinematicControllerUnified omnidirectional controller: velocity commands + TPI pose navigation.
- Velocity mode (VELOCITY):
6-DoF body-frame velocity (vx, vy, vz, wx, wy, wz) → quaternion-based world-frame integration. Linear and angular magnitudes are clamped.
- Pose mode (POSE):
Per-axis TPI with distance-ratio velocity scaling for straight-line motion from start to goal.
- set_velocity(vx=0.0, vy=0.0, vz=0.0, wx=0.0, wy=0.0, wz=0.0)
Set velocity in body frame (6-DoF) with kinematic clamping.
Scalar limits ⇒ magnitude clamp (preserves direction). Per-axis limits ⇒ per-component clamp.
- Return type:
- class pybullet_fleet.controller.DifferentialController(params=None, wheel_separation=0.0)
Bases:
KinematicControllerUnified differential-drive controller: velocity commands + TPI pose.
- Velocity mode (VELOCITY):
Unicycle model — only forward (
vx) and yaw rate (wz). Lateral velocity and other DoF are ignored.- Pose mode (POSE):
Two-phase TPI: ROTATE to face target, then FORWARD to reach it. Uses TPI + quaternion slerp for smooth rotation.
- capture_navigation_state()
Capture the common pose path plus differential heading and direction.
- Return type:
- restore_navigation_state(state, orientation, owner='')
Restore a turn or straight segment without issuing another command.
- Return type:
- set_velocity(vx=0.0, vy=0.0, vz=0.0, wx=0.0, wy=0.0, wz=0.0)
Set velocity (body frame). Only
vxandwzare used.Per-axis limits are reduced to scalars via X (forward) / yaw axes.
- Return type:
pybullet_fleet.controller_params module
Shared parameter dataclass for kinematic controllers.
ControllerParams carries all kinematic limits and behaviour flags that are
common to every KinematicController subclass (omni, differential, …).
It is stored on the per-agent controller as controller.params and is the
single authoritative source consulted by both per-agent control loops and the
batched controllers (BatchOmniController / BatchDifferentialController).
Design rationale
Single source of truth — eliminates duplication of
max_linear_vel,navigation_2d, etc. acrossAgentSpawnParams,Agent, and the controllers themselves.Per-axis kinematic limits —
max_*_vel/accelaccept either a scalar (uniform limit, magnitude clamp semantics) or a 3-element sequence (per-axis limit, per-axis clamp / direction-projected TPI). Velocity-mode clamping and pose-mode TPI both branch on the runtime form.Symmetry with batched controllers — batch controllers read
agent.controller.paramsduringregister_agentand pack the fields into(N,)arrays. Per-agent and batch share the exact same dataclass.Pure data, no logic — kept separate from
controller.py(which holds the control-loop logic) to avoid bloating that module and to keep imports cycle-free betweenagent.py,controller.pyandcontrollers/*.
- class pybullet_fleet.controller_params.ControllerParams(max_linear_vel=None, max_angular_vel=None, max_linear_accel=None, max_linear_decel=None, max_angular_accel=None, max_angular_decel=None, cmd_vel_timeout=None, navigation_2d=None, default_direction=MovementDirection.FORWARD, goal_replacement=None, stop_on_collision=None)
Bases:
objectKinematic limits and behaviour flags shared by all
KinematicControllersubclasses.All numeric fields default to
None(“not explicitly set”). Controllers resolveNoneto the framework default frompybullet_fleet._defaults.CONTROLLERat the point of use, so aControllerParams()with all-Nonefields behaves identically to the old all-default instance. TheNonesentinel enables fleet-level defaults inAgentManager: only fields that are stillNoneon an agent are filled in from the fleet config; explicitly set values are never overwritten.- max_linear_vel
Maximum linear velocity in m/s. Scalar = magnitude clamp (Euclidean norm). 3-element sequence
[vx, vy, vz]= per-axis limit in body frame.None→ framework default.
- max_angular_vel
Maximum angular velocity in rad/s. Same semantics as
max_linear_vel.None→ framework default.
- max_linear_accel
Maximum linear acceleration in m/s² (used by TPI).
None→ framework default.
- max_linear_decel
Maximum linear deceleration in m/s² (used by TPI). Same scalar/per-axis semantics as
max_linear_accel.None→ mirrormax_linear_accel(symmetric trapezoid), which is the behaviour of every release before this field existed. Set it for vehicles that brake harder than they accelerate.
- max_angular_accel
Maximum angular acceleration in rad/s² (used by TPI).
None→ framework default.
- max_angular_decel
Maximum angular deceleration in rad/s² (used by TPI). Same scalar/per-axis semantics as
max_angular_accel.None→ mirrormax_angular_accel(symmetric trapezoid), which is the behaviour of every release before this field existed. Set it for vehicles whose turns brake at a different rate than they start. A scalar must be a finite number above zero; a per-axis value needs finite components of zero or more and a yaw (z) component above zero, since every turn brakes at it. Anything else raisesValueErrorwhen it is set.
- cmd_vel_timeout
Watchdog timeout in seconds;
0.0orNonedisables the watchdog.None→ framework default (0.0).
- navigation_2d
When
True, pose-control trajectories preserve the currentzcoordinate (XY-plane navigation).None= not explicitly set (treated asFalseby all controllers).
- default_direction
Default movement direction for
set_path, aMovementDirectionor its string value. Only meaningful for differential-drive controllers.
- goal_replacement
What a moving agent does with a new path it cannot reach from its current motion within these limits – a
GoalReplacementor its string value ("brake","reject","wait_complete","immediate").None→ framework default,"brake"unless changed (seepybullet_fleet._defaults.CONTROLLER, overridable with thePBF_CONTROLLER_GOAL_REPLACEMENTenvironment variable).
- stop_on_collision
When
True, the agent stops dead (Agent.stop: no deceleration, path dropped) on the step a collision starts that involves it or an object attached to it, as a vehicle that has run into something stays where it hit. A contact between an agent and its own attached object does not count.None→ framework default,Falseunless changed (PBF_CONTROLLER_STOP_ON_COLLISION).
- default_direction: MovementDirection = 'forward'
- goal_replacement: GoalReplacement | None = None
- as_config()
The fields as plain data – enums as their string values – for YAML, checkpoints and
from_dict().
- classmethod from_dict(config)
Create from a dict, ignoring unknown keys.
Unknown keys are silently dropped so that subclass-specific extras (e.g.
wheel_separation) can coexist with shared params inside a single YAML block. Enum fields take their string values.- Return type:
ControllerParams
- linear_vel_along_direction(direction_unit)
Maximum scalar speed along direction_unit respecting per-axis limits.
- Return type:
- linear_accel_along_direction(direction_unit)
Maximum scalar acceleration along direction_unit respecting per-axis limits.
- Return type:
- linear_decel_along_direction(direction_unit)
Maximum scalar deceleration along direction_unit respecting per-axis limits.
- Return type:
- clamp_linear_vec(vec)
Clamp a body-frame linear velocity vector
(3,).- Return type:
- clamp_angular_vec(vec)
Clamp a body-frame angular velocity vector
(3,).- Return type:
- scalar_max_linear_vel()
Forward-axis scalar
max_linear_vel(for differential drive).- Return type:
- scalar_max_linear_accel()
Forward-axis scalar
max_linear_accel(for differential drive).- Return type:
- scalar_max_linear_decel()
Forward-axis scalar
max_linear_decel(for differential drive).- Return type:
- scalar_max_angular_vel()
Yaw-axis scalar
max_angular_vel(for differential drive).- Return type:
- scalar_max_angular_accel()
Yaw-axis scalar
max_angular_accel(for differential drive).- Return type:
- scalar_max_angular_decel()
Yaw-axis scalar
max_angular_decel(for differential drive).- Return type:
- pybullet_fleet.controller_params.parse_goal_replacement(value)
A
GoalReplacementfrom itself or its string value.- Raises:
ValueError – for any other value, naming the accepted ones.
- Return type:
GoalReplacement
pybullet_fleet.core_simulation module
core_simulation.py Reusable core simulation logic for multi-robot PyBullet environments. Integrates generation, management, transport, attach/detach, collision detection, coordinate conversion, occupied judgment, transport path generation, debugging, monitoring, and log control for various robots, pallets, and meshes.
- pybullet_fleet.core_simulation.CollisionIgnoreFilter
fn(obj_a, obj_b) -> bool for :meth:`MultiRobotSimulationCore.set_collision_ignore_filter`: ``Truewhen the two touching objects are meant to touch and should not count as a collision.alias of
Callable[[SimObject,SimObject],bool]
- pybullet_fleet.core_simulation.CollisionMargin
one distance for every axis, or one per world axis (x, y, z).
- Type:
A collision clearance
- class pybullet_fleet.core_simulation.CollisionPairObservation(object_ids, detection_method, signed_distance, sample_step, sample_time)
Bases:
objectLast narrow-phase measurement for an active object pair.
- detection_method: CollisionDetectionMethod
- sample_step: int
- sample_time: float
- class pybullet_fleet.core_simulation.CollisionObservation(step, sim_time, configured_method, margin, pairs)
Bases:
objectActive pairs as of a completed collision check, not an event history.
- step: int
- sim_time: float
- configured_method: CollisionDetectionMethod
- pairs: Tuple[CollisionPairObservation, ...]
- class pybullet_fleet.core_simulation.SimulationParams(target_rtf=1.0, timestep=0.1, duration=0, gui=True, physics=False, monitor=True, enable_monitor_gui=None, monitor_update_interval=None, monitor_log_interval=1.0, collision_check_frequency=None, log_level='warn', max_steps_per_frame=10, max_sleep_frames=4.0, gui_min_fps=30, enable_collision_shapes=False, enable_structure_transparency=False, enable_shadows=True, enable_gui_panel=False, ignore_static_collision=True, ignore_attached_collision=True, enable_time_profiling=False, profiling_interval=100, enable_memory_profiling=False, enable_collision_color_change=False, spatial_hash_cell_size_mode=SpatialHashCellSizeMode.AUTO_INITIAL, spatial_hash_cell_size=None, collision_detection_method=None, collision_margin=0.02, multi_cell_threshold=1.5, enable_floor=True, camera_config=None, lighting_config=None, model_paths=None, window_width=1024, window_height=768, monitor_width=680, monitor_height=480, monitor_x=-1, monitor_y=-1)
Bases:
objectSimulation configuration parameters.
All fields have sensible defaults for headless kinematics-based simulation. Use
from_config/from_dictto load from YAML files.- target_rtf: float = 1.0
- timestep: float = 0.1
- duration: float = 0
- gui: bool = True
- physics: bool = False
- monitor: bool = True
- enable_monitor_gui: bool | None = None
Whether the DataMonitor opens a window.
None(the default) followsgui: a headless simulation collects monitor data without putting a Tk window on screen.TrueorFalseis honoured as given, so a monitor window without the PyBullet viewer is still available.
- monitor_update_interval: float | None = None
Simulated seconds between DataMonitor refreshes while
monitoris on. A refresh buildslast_monitor_frameand writes the file the monitor window reads (every 0.5 wall seconds).None(the default) is 0.25 s while the monitor window is open (enable_monitor_gui, orguiwhen that isNone) and 1 s otherwise;0is every step. Simulated time: at a real-time factor above 1 a short interval means more writes per wall second. While paused, a selection, follow or pause change, and a single step, refresh at once. Read once, when the simulation is created.
- monitor_log_interval: float = 1.0
Wall-clock seconds between
[MONITOR]lines logged at INFO – RTF, collision totals, step count – independent ofmonitor,guiandmonitor_update_interval.monitordrives the DataMonitor, whose line is logged at DEBUG; this keeps those figures in the log whether or not anything is on screen. Default 1 s;0logs none. Wall clock rather than simulated time, so the log’s volume does not scale with the real-time factor.
- log_level: str = 'warn'
- max_steps_per_frame: int = 10
- max_sleep_frames: float = 4.0
- gui_min_fps: int = 30
- enable_collision_shapes: bool = False
- enable_structure_transparency: bool = False
- enable_shadows: bool = True
- enable_gui_panel: bool = False
- ignore_static_collision: bool = True
- ignore_attached_collision: bool = True
Do not count contact between objects on one attachment tree (
attach_object): a carrier, its loads and their loads touch one another by design. Contact with anything outside the tree is reported.
- enable_time_profiling: bool = False
- profiling_interval: int = 100
- enable_memory_profiling: bool = False
- enable_collision_color_change: bool = False
- spatial_hash_cell_size_mode: SpatialHashCellSizeMode = 'auto_initial'
- collision_detection_method: CollisionDetectionMethod | None = None
- collision_margin: float | Tuple[float, float, float] = 0.02
Clearance, in metres, within which CLOSEST_POINTS (and the kinematic pairs of HYBRID) report a pair that does not touch; CONTACT_POINTS ignores it. A number applies to every direction; an
(x, y, z)triple (a list in YAML) gives one clearance per world axis, for example(0.05, 0.05, 0.0)to report bodies side by side but not one passing close above or below another. A triple acts in the broad phase: each AABB axis is enlarged by that axis’s clearance, so two bodies whose AABBs are farther apart than that on any axis are never reported. The narrow phase judges the straight-line gap against the largest component, so(m, m, m)is the same asm, and(m, m, 0)reports whatCollisionMode.NORMAL_2Dwithmdid, for every pair.
- multi_cell_threshold: float = 1.5
- enable_floor: bool = True
- window_width: int = 1024
- window_height: int = 768
- monitor_width: int = 680
- monitor_height: int = 480
- monitor_x: int = -1
- monitor_y: int = -1
- classmethod from_config(config_path='config.yaml')
- Return type:
SimulationParams
- class pybullet_fleet.core_simulation.MultiRobotSimulationCore(params, collision_color=None)
Bases:
object- classmethod from_yaml(yaml_path='config.yaml')
Create and initialise a simulation from a YAML config file.
Supports two YAML layouts:
Nested (recommended) —
simulation,world, andentitiessections:simulation: gui: true physics: false world: world_file: "/path/to/office.world" entities: - name: robot0 urdf_path: "robots/mobile_robot.urdf" pose: [0, 0, 0.05] - type: sim_object name: box0 visual_shape: shape_type: box half_extents: [0.3, 0.3, 0.1] pose: [3, 0, 0.1]
Flat (legacy) — all keys at the top level:
gui: true physics: false timestep: 0.1
Custom entity types — register classes via dotted Python paths so
type:dispatch works without any Python code:entity_classes: forklift: "my_ros_pkg.entities.ForkliftAgent" conveyor: "warehouse_sim.conveyor.ConveyorObject" entities: - type: forklift urdf_path: robots/forklift.urdf pose: [0, 0, 0.05]
When a
worldsection is present andenable_flooris not explicitly set in the simulation config, the floor plane is automatically disabled (the world geometry replaces it).- Parameters:
yaml_path (
str) – Path to YAML config file.- Return type:
MultiRobotSimulationCore- Returns:
Fully initialised
MultiRobotSimulationCorewith world loaded and robots spawned (if configured).
- classmethod from_dict(config)
Create MultiRobotSimulationCore from a configuration dictionary.
Supports both flat simulation-params dicts and nested dicts with
simulation,world, andentitiessections. When nested keys are present they are processed the same way asfrom_yaml().An optional
entity_classessection maps names to dotted Python paths for dynamic class registration (seefrom_yaml()for details).
- events: EventBus
- setup_monitor()
- Return type:
- property sim_objects: List[SimObject]
List of all simulation objects (Agent, SimObject, etc.).
- property last_monitor_frame: MonitorFrame | None
Return the most recently published toolkit-neutral monitor frame.
- property gui_follow_enabled: bool
Return whether the viewport follows the selected entity.
- enqueue_gui_command(command)
Queue a monitor request for the next simulation-step boundary.
This method is safe to call from a tkinter callback. It deliberately does not mutate simulation state or make PyBullet calls on the caller’s thread. Returns
Falseonly when the bounded queue is full.- Return type:
- request_single_step(source='api')
Request one step while paused, without re-entering
step_once().The request is consumed by the outer
step_onceinvocation. A request made while running is ignored because normal stepping already advances the simulation.- Return type:
- property agents: List[Agent]
List of Agent instances.
- find_objects_by_name(name)
Return all registered simulation objects whose name matches.
Names are not required to be unique. The result follows registration order and includes Agents, which are also SimObjects.
- Return type:
List[SimObject]
- find_agents_by_name(name)
Return matching Agents in registration order.
- Return type:
List[Agent]
- get_unique_object_by_name(name)
Return one named object, or raise if absent or ambiguous.
- Return type:
SimObject
- get_unique_agent_by_name(name)
Return one named Agent, or raise if absent or ambiguous.
- Return type:
Agent
- property params: SimulationParams
Simulation parameters.
- property step_count: int
Current simulation step count.
- property sim_time: float
Simulated time of the state you see (read-only).
Outside a step it is the completed step’s time, the same as
get_completed_step_boundary(). Insidestep_once()the clock advances right after thepre_stepevent, so from the object update on – callbacks, plugins, the collision check,post_step– it is the time of the state that step computes. Apre_stepsubscriber sees the previous step’s time. To move the clock (resuming from a checkpoint), userestore_completed_step_boundary().
- get_completed_step_boundary()
Return the completed step and canonical elapsed time outside a step.
- configure_state_recording(*, profile, output=None, checkpoint_every_steps=1, records=())
Record a supported execution profile during ordinary simulation runs.
State recording is distinct from camera/video recording. The profile declares what can be restored; named records capture caller-owned data at the same completed boundary. Unsupported live state fails at capture.
- Return type:
- restore_completed_step_boundary(step, elapsed_time)
Restore the clock of a fresh, initialized fixed-step simulation.
- Return type:
- property collision_count: int
Total number of collisions detected.
- property enable_memory_profiling: bool
Whether memory profiling is enabled.
- property last_profiling: Mapping[str, Any] | None
Timing values from the most recently completed profiled step.
The mapping has the same timing fields (in milliseconds) as
step_once()withreturn_profiling=True, including custom fields added byrecord_profiling(). It is updated only when timing is measured: either time profiling is enabled or that step was called withreturn_profiling=True. Otherwise it isNone.Simulation plugins and callbacks execute before the current step’s later phases have completed, so they observe the previous completed step through this property. The returned mapping is read-only.
- register_plugin(plugin_or_cls, config=None, frequency=None, phase=None)
Register a simulation plugin.
- Parameters:
plugin_or_cls (
Union[TypeVar(_SimPluginT, bound= SimPlugin),Type[TypeVar(_SimPluginT, bound= SimPlugin)]]) – Either aSimPlugininstance or aSimPluginsubclass (will be instantiated).config (
Optional[Dict[str,Any]]) – Config dict (only used when plugin_or_cls is a class).frequency (
Optional[float]) – Step frequency in Hz (None= every step).phase (
Union[CallbackPhase,str,None]) – When in the stepSimPlugin.on_step()runs, aCallbackPhaseor its value ("pre_step","step","post_step"), as forregister_callback().Nonekeeps the plugin’s ownSimPlugin.step_phase("step"unless the class sets another).
- Return type:
TypeVar(_SimPluginT, bound= SimPlugin)- Returns:
The registered
SimPlugininstance.- Raises:
TypeError – If plugin_or_cls is not a SimPlugin.
ValueError – If
frequencyorphaseis not valid.
- property plugins: List[SimPlugin]
Read-only list of active plugins.
- register_callback(callback, frequency=None, phase=CallbackPhase.STEP)
Register a callback function to be called during simulation.
- Parameters:
callback (
Callable) – Function with signature callback(sim_core, dt) -> None - sim_core: Reference to MultiRobotSimulationCore instance - dt: Simulated time since this callback last ran (seconds)frequency (
Optional[float]) – Callback frequency in Hz. If None (or 0), called every simulation step. Due times are a fixed grid ofk / frequencyseconds of simulated time, so a callback neither skips beats nor drifts; it runs at most once per step, and the first time one interval into the run.phase (
Union[CallbackPhase,str]) –When in the step the callback runs, a
CallbackPhaseor its value as a string.CallbackPhase.PRE_STEP/"pre_step": at the start of the step, right after thepre_stepevent’s handlers, before the clock advances and before anything moves.sim_core.sim_timeis still the previous state’s time. Use it to apply commands this step should act on.CallbackPhase.STEP/"step"(default): after the objects have been updated, before their new poses are written to PyBullet and before the collision check.CallbackPhase.POST_STEP/"post_step": at the end of the step, right after thepost_stepevent: poses are written, and when the step ran a collision check (seecollision_check_frequency) the active pairs are those of the new poses. Use it to publish or record the step’s outcome.
In every phase
sim_core.sim_timeis the time of the state the callback sees: the previous state’s inPRE_STEP, the end of the step inSTEPandPOST_STEP; stamp anything read from the bodies with it. All three schedule theirfrequencyon it.
- Raises:
ValueError –
frequencyis negative or not finite, orphaseis not aCallbackPhase.- Return type:
A callback’s exception is not caught (unlike a plugin’s): it propagates out of
step_once(), and the rest of the step is skipped. What has happened by then depends on the phase:PRE_STEP: the clock has not advanced (sim_timeandstep_countstay at the previous state) and nothing has moved; the laterpre_stepcallbacks and plugins and the whole update are skipped.STEP: the clock has advanced and the objects have moved; later callbacks, the step’s plugins, the pose flush, the collision check, thepost_stepevent and thePOST_STEPcallbacks are skipped.POST_STEP: the step is complete except for later callbacks, thepost_stepplugins and what follows them.
In every phase the state recorder’s completed step and the DataMonitor refresh are skipped.
A callback is a subscription to the
phaseevent onevents(the event of the same name,SimEvents.PRE_STEP,SimEvents.STEPorSimEvents.POST_STEP) in a tier of its own: it runs after that event’s handlers, whatever their priority, and callbacks run in registration order.events.on(phase, handler, frequency=...)is the keyword-argument form of the same hook, with the same schedule; its exceptions are logged instead of raised.Example:
def my_callback(sim_core, dt): for obj in sim_core.sim_objects: if isinstance(obj, Agent): # Update agent logic pass sim_core.register_callback(my_callback, frequency=10.0) # 10 Hz def publish(sim_core, dt): stamp = sim_core.sim_time ... sim_core.register_callback(publish, frequency=10.0, phase=CallbackPhase.POST_STEP)
- register_behavior_tree(tree)
Register a behavior tree to tick once per simulation step.
treemust providetick(sim_core, dt). Registration is idempotent by object identity, and the returned tree makes inline use convenient. The tree’stickmethod remains public for deterministic unit tests and custom stepping loops.- Return type:
BehaviorTree
- unregister_behavior_tree(tree)
Stop automatically ticking a tree previously registered with this simulation.
- Return type:
- property behavior_trees: Tuple[BehaviorTree, ...]
Behavior trees automatically ticked by this simulation.
- register_manager(manager)
Register a
SimObjectManager(or subclass) with this simulation.Registered managers are automatically synchronised when objects are removed via
remove_object()or the simulation isreset(). The manager’ssim_coreattribute is set to self.A manager can only be registered once; duplicate calls are ignored.
- Parameters:
manager (
SimObjectManager) – The manager instance to register.- Return type:
Example:
from pybullet_fleet.agent_manager import AgentManager mgr = AgentManager() sim.register_manager(mgr) mgr.spawn_agents_grid(10, grid_params, spawn_params) # When sim.remove_object(agent) is called later, # mgr.objects is kept in sync automatically.
- unregister_manager(manager)
Remove a manager from the registry.
- Return type:
- Returns:
True if the manager was found and removed, False otherwise.
- get_manager(name)
Return the registered
AgentManagerwith the given name, orNone.- Parameters:
name (
str) – The name assigned to the manager (name:field in YAML, or thename=argument passed toAgentManager).- Return type:
Example:
sim = MultiRobotSimulationCore.from_yaml("config.yaml") fleet = sim.get_manager("delivery_fleet") for agent in fleet.objects: agent.set_path([goal])
- unregister_callback(callback_func)
Remove a registered callback by function reference.
- start_recording(output='recording.gif', width=800, height=600, fps=15, duration=None, camera_mode='auto', time_base='sim', **kwargs)
Start recording the simulation as an animated GIF or MP4.
Frames are captured via
getCameraImage(ER_TINY_RENDERER)at the specified fps frequency. Works in bothp.DIRECTandp.GUI.Output format is auto-detected from the file extension:
.gif— Animated GIF via Pillow (always available).mp4— H.264 MP4 via imageio + pyav (requirespip install imageio[pyav])
Time bases:
"sim"(default) — Capture at fixed sim-time intervals. Playback always looks like 1× speed."real"— Capture at wall-clock intervals. Playback reflects actual execution speed (e.g. 10× sim → 10× video).
- Parameters:
output (
str) – Output file path (.gifor.mp4). Parent directories created automatically.width (
int) – Frame width in pixels.height (
int) – Frame height in pixels.fps (
int) – Capture frequency and playback FPS.duration (
Optional[float]) – Recording duration in sim-seconds (time_base="sim") or wall-clock seconds (time_base="real").Nonefor manual stop.camera_mode (
str) –"auto"|"gui"|"orbit"|"manual"."auto"is promoted to"gui"when running in GUI mode.time_base (
str) –"sim"or"real". Controls capture timing.**kwargs (
Any) – Passed toSimulationRecorder(e.g.orbit_degrees,camera_params).
- Return type:
- Returns:
SimulationRecorderinstance.
Example:
sim.start_recording("output.gif", duration=4.0) sim.start_recording("output.mp4", duration=4.0, fps=30) sim.start_recording("perf.mp4", duration=4.0, time_base="real") sim.run_simulation(duration=5.0) # File is auto-saved when run_simulation ends
- stop_recording()
Stop recording and save the output file.
- set_collision_check_frequency(frequency=None)
Set the frequency (Hz, number of times per second) for collision detection.
- Parameters:
frequency (
Optional[float]) – Collision check frequency in Hz (times per second) - None: Check every step (highest accuracy, highest cost) - 0: Disable collision checking (no collision detection) - > 0: Check at specified frequency (e.g., 1.0 = once per second)- Return type:
Example:
sim.set_collision_check_frequency(None) # Every step sim.set_collision_check_frequency(1.0) # 1 Hz (once per second) sim.set_collision_check_frequency(10.0) # 10 Hz sim.set_collision_check_frequency(0) # Disable
Note: Higher frequency increases computational cost but improves collision detection accuracy.
- setup_pybullet()
Initialize PyBullet with GUI panels hidden.
- Return type:
- disable_rendering()
Disable rendering during object spawning for better performance.
- Return type:
- enable_rendering()
Enable rendering before starting simulation.
- Return type:
- batch_spawn()
Context manager for optimised batch spawning.
Disables rendering and defers spatial-grid rebuild until the context exits. Use when spawning many objects at once.
Rendering state is saved on entry and restored on exit. If rendering was already disabled (e.g. during the initial setup phase before
run_simulation()), it stays disabled afterbatch_spawn()exits.Example:
with sim_core.batch_spawn(): for params in params_list: Agent.from_params(params, sim_core) # rendering restored to previous state, spatial grid rebuilt once
- set_poses(object_ids, positions, orientations, *, preserve_velocity=True)
Set poses for N objects in one call (batch / high-throughput path).
Use this when poses are already in array form (ROS
PoseArray, vectorized controllers, NumPy pipelines). For single-object writes preferSimObject.set_pose()with aPoseobject — this method intentionally takes raw ndarrays to avoid per-objectPoseallocations on the hot path.Internally honours the same two-phase semantics as
SimObject.set_pose: insidestep_once()the writes are buffered to be flushed in Phase 2, outside they propagate to PyBullet immediately.get_pose/get_posesalways reflect the new values regardless of phase.- Parameters:
object_ids (
Sequence[int]) – N object ids to write to (in matching order).positions (
ndarray) –(N, 3)float array of XYZ positions.orientations (
ndarray) –(N, 4)float array of XYZW quaternions.preserve_velocity (
bool) – If True, preserve current velocities (dynamic objects only; ignored for kinematic objects).
- Raises:
ValueError – if shapes don’t match
(N, 3)/(N, 4)forN = len(object_ids).KeyError – if any
object_idis not registered in this sim.
- Return type:
- get_poses(object_ids)
Return
(positions, orientations)arrays for N objects (batch read).Counterpart of
set_poses(). Returns raw ndarrays for direct use in vectorized math, ROS message construction, or controller state. For single-object reads preferSimObject.get_pose()which returns aPoseobject.Reads each object’s cached pose (no PyBullet API call), so values are always consistent with the two-phase semantics — buffered writes made during the current step are visible immediately.
- notify_geometry_changed(obj)
Tell the simulation that
obj’s links moved without its base pose being set.A joint moved by
Agent.set_joint_position(), by the joint interpolation of a kinematic agent or by restoring a checkpoint calls this already. Call it after moving a body’s joints directly through PyBullet (p.resetJointState).The body counts as moved for the next collision check, and its broadphase AABB (the union of its link boxes) and spatial-hash cells follow the links. Outside a step that happens at once. Inside a step a kinematic or
STATICbody is refreshed with the flushed poses before the collision check; a physics body is re-read afterstepSimulation()anyway.- Parameters:
obj (
SimObject) – The object whose links moved.- Return type:
- set_collision_ignore_filter(ignore)
Exclude the touching pairs
ignore(obj_a, obj_b)returnsTruefor from collision results.An ignored pair is treated as not touching everywhere a collision shows up: it is not an active pair, not counted, not recoloured, not in the collision observation and raises no
COLLISION_STARTED. A pair that becomes ignored while active is resolved (COLLISION_ENDED) on the next collision check, and an ignored pair that stops being ignored is checked again on the next one, whether or not either body moved. So the filter may depend on state that changes at run time – which object carries which, say. It is applied on top ofignore_attached_collision.Noneremoves it.Ignored pairs skip the narrow phase, so the filter is called, on each collision check, for every broad-phase candidate pair involving a moved object, every active pair and every pair it ignored last time until they move apart; keep it cheap.
- Return type:
- set_collision_margin(margin)
Change the clearance and recheck stationary pairs on the next collision check.
- Parameters:
margin (
Union[float,Sequence[float]]) – Metres, for every direction, or an(x, y, z)sequence with one clearance per world axis (seeSimulationParams.collision_margin).- Raises:
ValueError – If the margin, or any component, is negative or not finite, or a sequence does not have three components.
- Return type:
- set_collision_spatial_hash_cell_size_mode(mode=None, cell_size=None)
Set collision detection spatial hash cell size mode and recalculate/rebuild grid.
This method allows dynamic mode switching and always recalculates the cell_size based on the spatial_hash_cell_size_mode setting (or override via parameters).
- Parameters:
- Return type:
- Returns:
The calculated cell_size (always > 0, falls back to 1.0 if no AABBs available)
Example:
# Recalculate with current mode sim_core.set_collision_spatial_hash_cell_size_mode() # Switch to constant mode with specific size sim_core.set_collision_spatial_hash_cell_size_mode( mode=SpatialHashCellSizeMode.CONSTANT, cell_size=3.0 ) # Switch to auto_adaptive mode sim_core.set_collision_spatial_hash_cell_size_mode( mode=SpatialHashCellSizeMode.AUTO_ADAPTIVE )
- add_object(obj)
Add an object to simulation and register it with all necessary caches.
This method centralizes object registration logic for consistency and maintainability. Called automatically by SimObject.__init__() when sim_core is provided.
- Parameters:
obj (
SimObject) – The SimObject instance to add- Return type:
Example:
# Manual addition (not recommended - SimObject does this automatically) obj = SimObject(body_id=body_id, sim_core=None) sim_core.add_object(obj) # Automatic addition (recommended) obj = SimObject(body_id=body_id, sim_core=sim_core) # Calls add_object() internally
- remove_object(obj)
Remove an object from simulation and clean up all caches.
- Parameters:
obj (
SimObject) – The SimObject instance to remove- Return type:
Example:
obj = sim_core.spawn_robot(...) # ... later ... sim_core.remove_object(obj)
- configure_visualizer(enable_structure_transparency=None, enable_shadows=None)
Configure PyBullet visualizer settings with keyboard control.
- Parameters:
- Return type:
Custom keyboard shortcuts (active during simulation): - Press SPACE to pause/play simulation - Press ‘t’ to toggle structure transparency ON/OFF
Camera controls (always active in GUI mode): - Right-drag to pan camera - Press arrow keys to pan camera horizontally - Press ‘=’ to zoom in, ‘-’ to zoom out - Press ‘o’ for top-down view
PyBullet built-in keyboard shortcuts (always available): - Press ‘w’ to toggle wireframe / collision shape display - Press ‘g’ to toggle grid display - Press ‘j’ to toggle joint axes display
- configure_gui_lighting(lighting_config=None)
Apply optional PyBullet GUI main-light and shadow-map settings.
lighting_configacceptslight_position(three coordinates),shadow_map_world_sizeandshadow_map_resolution. The normal PyBullet GUI has one main light; this does not model USD light prims.- Return type:
- compute_scene_bounds()
Compute scene bounding box from all sim_object positions.
Returns a
(center, extent)tuple where center is the mean position[cx, cy, cz]and extent is the axis-aligned size[ex, ey, ez](i.e.max - minper axis).When the scene is empty both lists are
[0.0, 0.0, 0.0].This is used by
setup_camera()(GUI) andSimulationRecorder(offscreen) so that both share the same scene-framing logic.
- setup_camera(camera_config=None, entity_positions=None)
Set up camera view based on configuration.
Valid
camera_modevalues:"auto"(default) — Auto-calculates camera distance and target from entity positions orsim_objects."manual"— Uses explicitcamera_distance,camera_yaw,camera_pitch, andcamera_targetfrom the config.
Interactive controls (right-drag/arrow-key pan, +/- zoom, o=top-down) are always enabled in GUI mode regardless of camera_mode.
- query_aabb(aabb_min, aabb_max)
Objects whose AABB overlaps the box
[aabb_min, aabb_max].Looks only at the objects registered in the collision spatial hash cells the box reaches, so the cost depends on how crowded the box is, not on how many objects the simulation holds. Every object is registered in each cell its AABB reaches, and kinematic and physics objects are re-registered on every step whatever the collision check frequency, so the hash answers for the current step. Before the hash exists, or when the box spans more cells than there are objects, every object is tested instead.
Objects with collision
DISABLEDare not in the hash; they are tested directly against their PyBullet AABB. A pose written outside a step is applied at once and answered for. Inside a step (from a callback or a controller), a written pose is buffered and reaches PyBullet only when the step flushes it: until then such an object is tested against the AABB of the pose it had when the step began. Joints are not buffered: an object whose links moved in the step (notify_geometry_changed) is tested against its links as they are now, at the base pose PyBullet holds.- Parameters:
- Return type:
List[SimObject]- Returns:
The overlapping objects, in no particular order.
Example:
# Everything within 0.5 m of a point, as a box nearby = sim.query_aabb((x - 0.5, y - 0.5, z - 0.5), (x + 0.5, y + 0.5, z + 0.5))
- pickable_candidates_near(position, radius)
Every pickable object whose base origin may be within
radiusofposition.A superset, for a search by base origin such as
SimObject.find_nearest_pickable(): it may also hold objects farther away or not pickable, so the caller measures the distance and checkspickableitself. The objects come through the spatial hash, as forquery_aabb(), plus those the hash cannot place by their origin: a pickable shape set more than a cell off its origin, objects with collisionDISABLED, and objects with a pose written in the current step and not yet flushed (their cached pose is already the new one). Before the hash exists, every object.
- get_aabbs()
Get the AABB of every simulation object, each covering all of the body’s links.
- filter_aabb_pairs(ignore_static=None, moved_objects=None, return_profiling=False)
Filter AABB pairs for collision detection with moved-based optimization. Only checks pairs involving moved objects.
- Parameters:
ignore_static (
Optional[bool]) – If True, skip collision checks with static objectsmoved_objects (
Optional[Set[int]]) – Set of object IDs that moved since last check. If None, uses self._moved_this_step (default behavior)return_profiling (
bool) – If True, include timing information in return value
- Returns:
pairs: List of (obj_id_i, obj_id_j) tuples for candidate collision pairs
timings: dict with get_aabbs, spatial_hashing, aabb_filtering (in ms) if return_profiling=True, else None
- Return type:
Tuple of (pairs, timings)
Example:
# Without profiling pairs, _ = sim.filter_aabb_pairs() # With profiling pairs, timings = sim.filter_aabb_pairs(return_profiling=True) print(f"AABB filtering took {timings['total']:.2f}ms")
- check_collisions(collision_color=None, ignore_static=None, return_profiling=False)
Check for collisions between robots using incremental updates.
Only re-checks collision pairs involving moved objects for efficiency. Maintains _active_collision_pairs as persistent state.
- Parameters:
- Returns:
pairs: List of currently active collision pairs (obj_id_i, obj_id_j)
timings: dict with get_aabbs, spatial_hashing, aabb_filtering, contact_points, total (in ms) if return_profiling=True, else None
- Return type:
Tuple of (pairs, timings)
Example:
# Without profiling active_pairs, _ = sim.check_collisions() # With profiling active_pairs, timings = sim.check_collisions(return_profiling=True) print(f"Collision check took {timings['total']:.2f}ms")
- get_active_collision_pairs()
Get currently active collision pairs.
- Return type:
- Returns:
List of (object_id_i, object_id_j) tuples for all active collisions. Pairs are sorted such that object_id_i < object_id_j.
Example:
# Check if any collisions are active if sim_core.get_active_collision_pairs(): print("Collisions detected!") # Get detailed collision info for obj_id_i, obj_id_j in sim_core.get_active_collision_pairs(): obj_i = sim_core._sim_objects_dict[obj_id_i] obj_j = sim_core._sim_objects_dict[obj_id_j] print(f"Collision: {obj_i} <-> {obj_j}")
- get_collision_observation()
Return the latest completed collision check, or
Nonebefore one runs.A skipped step does not update the check timestamp. Each pair also has its own sample timestamp because incremental checks may leave an active pair unmeasured during a later completed check.
- Return type:
Optional[CollisionObservation]
- update_monitor()
Update simulation monitor with current statistics.
Calculates actual simulation speed from a 10-second sliding window, logs monitor data via logger, and writes to DataMonitor if enabled.
- Return type:
- flush_monitor()
Build and write a monitor frame now if the window is behind; return whether it did.
Running, the next refresh (
monitor_update_interval) shows any change, andclose()flushes, so only a program that stops callingstep_once()and keeps the simulation open needs this.- Return type:
- initialize_simulation()
Initialize simulation state before running.
This method prepares the simulation for execution by: - Resetting simulation counters (step_count, collision_count, sim_time) - Clearing movement tracking state - Configuring visualizer settings (transparency, collision shapes) - Enabling rendering for GUI mode
Called automatically by run_simulation(), but can also be called manually for custom simulation loops or when restarting simulation.
Example:
# Automatic (recommended) sim.run_simulation(duration=10.0) # Manual initialization for custom loop sim.initialize_simulation() while custom_condition: sim.step_once()
- Return type:
- reset()
Reset simulation to a clean state (no objects, fresh PyBullet world).
Removes all objects from the simulation, resets PyBullet, re-applies physics-engine parameters, optionally reloads the ground plane (only when
enable_flooris True), and re-initialises counters viainitialize_simulation().After calling
reset()the simulation is ready for new objects to be spawned. Callbacks registered viaregister_callback()are preserved (their schedules restart ininitialize_simulation).Example:
sim.reset() # All objects removed, PyBullet world cleared agent = Agent.from_params(params, sim) sim.step_once()
- Return type:
- load_world(world_config, skip_models=None)
Load world environment from a configuration dictionary.
Supports three sources (checked in priority order):
world_file— a Gazebo.worldfile with<include>elements (buildings, furniture, props).sdf— a single SDF model file (building geometry).mesh_dir— a directory of OBJ/STL mesh files.
- Parameters:
world_config (
Dict[str,Any]) –Dictionary with world loading options:
{ "world_file": "/path/to/office.world", "skip_models": ["TinyRobot", "TeleportDispenser"], } or:: {"sdf": "/path/to/model.sdf"} or:: {"mesh_dir": "/path/to/meshes/"}
skip_models (
Optional[List[str]]) – Model names to skip when loading a.worldfile (e.g. robot names that are spawned separately).
- Return type:
List[SimObject]- Returns:
List of
SimObjectinstances created from the world.
Example:
sim = MultiRobotSimulationCore(SimulationParams(enable_floor=False)) sim.initialize_simulation() objs = sim.load_world({"world_file": "/maps/office.world"})
- spawn_robots_from_config(robots_config)
Spawn robots/entities from a YAML-style configuration list.
Each entry in robots_config is a dict understood by
AgentSpawnParams.from_dict()(or the appropriateSpawnParamsfor the entitytype). SDF models are automatically converted to temporary URDF files viaresolve_sdf_to_urdf(), and model names are resolved throughresolve_model().Grid spawning: If an entry contains a
gridkey, the entry is expanded into multiple entities placed on a grid. Thegriddict is parsed byfrom_dict()and supports two formats:Count-based (convenience):
{ "urdf_path": "robots/mobile_robot.urdf", "controller": {"type": "omni"}, "grid": { "count": 50, "spacing": [3.0, 3.0], "offset": [0, 0, 0.05], "columns": 10, # optional }, }
Range-based (explicit grid extents):
{ "urdf_path": "robots/mobile_robot.urdf", "grid": { "x_min": 0, "x_max": 9, "y_min": 0, "y_max": 4, "spacing": [3.0, 3.0, 0.0], "offset": [0, 0, 0.05], }, }
Grid entries create a manager internally and register it with this simulation, so objects are automatically synchronised on
remove_object()andreset().Batch processing: Declare a named manager with
fleet_controller.typeand route the entity group to it. All entities in the group are added to that manager:"managers": [{ "name": "delivery_fleet", "fleet_controller": {"type": "batch_differential"}, }] "entities": [{ "urdf_path": "robots/simple_cube.urdf", "controller": {"type": "differential"}, "manager": "delivery_fleet", "grid": {"count": 100, "spacing": [2, 2]}, }]
Entity type dispatch: If an entry contains a
typekey (e.g."agent","sim_object", or a custom registered type), the corresponding class from the entity registry is used. Default is"agent".- Parameters:
robots_config (
List[Dict[str,Any]]) – List of robot/entity parameter dicts.- Return type:
List[SimObject]- Returns:
List of spawned
SimObject(or subclass) instances.
Example:
sim.spawn_robots_from_config([ # Individual robot {"urdf_path": "robots/mobile_robot.urdf", "pose": [0, 0, 0.05]}, # Grid routed to a named batch manager { "urdf_path": "robots/mobile_robot.urdf", "controller": {"type": "omni"}, "manager": "delivery_fleet", "grid": {"count": 20, "spacing": [3, 3]}, }, # Grid assigned to a named manager { "urdf_path": "robots/mobile_robot.urdf", "manager": "delivery_fleet", "grid": {"count": 50, "spacing": [2, 2]}, }, # Custom entity type {"type": "forklift", "urdf_path": "robots/forklift.urdf", "pose": [10, 0, 0]}, ])
- run_simulation(duration=None, *, resume=False)
Run the simulation for a specified duration.
- Parameters:
duration (
Optional[float]) – Absolute simulation-time cutoff in seconds (not wall time). If None, uses self._params.duration. If duration <= 0, runs indefinitely.resume (
bool) – Continue an explicitly restored completed-step state without resetting its clock. A core returned by the supported recording loader resumes on its first plain call too.
- Return type:
Example:
# Run for 10 seconds (simulation time) sim.run_simulation(duration=10.0) # Run indefinitely (until Ctrl+C or GUI closed) sim.run_simulation(duration=0)
- close()
Release everything this simulation owns, including its client.
run_simulation()has always done this on the way out, but a program that drivesstep_once()itself, or a test that only builds a scene, never reached that code – and nothing else disconnected. An undisconnected client leaks for the life of the process, and because PyBullet’s module-level calls resolve against a default client, the next simulation in the same process then finds bodies and joints “not found” rather than failing where the leak happened.Safe to call more than once, and safe on a simulation that was never run. A second call does nothing at all: shutdown callbacks run once, so a plugin that closes a file or a socket in
on_shutdown()is not asked to do it twice bywith sim:around arun_simulation()that already closed.Releasing the client is unconditional. Finalising a recording can raise – saving an MP4 without
imageio, for one – and letting that escape before the disconnect would leak the very client this exists to release.- Return type:
- record_profiling(name, value_ms)
Record a custom profiling measurement (in milliseconds).
Call this from within Agent.update() or callback code to accumulate timing data. Multiple calls per step are summed (e.g., 100 agents each recording their custom_logic time). Auto-registers the field on first use.
The recorded field appears in both _print_profiling_summary() output and step_once(return_profiling=True) results alongside built-in fields.
- Parameters:
- Return type:
Example:
# Inside your custom Agent.update(): t0 = time.perf_counter() self._do_custom_logic(dt) self.sim_core.record_profiling('custom_logic', (time.perf_counter() - t0) * 1000)
- pause()
Pause the simulation. step_once will be skipped while paused.
- Return type:
- resume()
Resume the simulation after a pause.
- Return type:
- property is_paused: bool
Return True if the simulation is currently paused.
- step_once(return_profiling=False)
Execute one simulation step.
Performs agent updates, callbacks, physics step, collision detection, and monitoring. If enable_time_profiling is True, detailed timing information is logged.
- Parameters:
return_profiling (
bool) – If True, return timing breakdown dictionary instead of logging. Useful for external profiling tools.- Return type:
- Returns:
If return_profiling=True, returns dict with timing breakdown in milliseconds:
{ 'phase1_update': float, # agent.update + callbacks + plugin on_step 'phase2_pose_flush': float, # flush buffered poses to PyBullet 'phase3_aabb_grid_flush': float, # kinematic AABB + spatial-grid refresh 'agent_update': float, # per-object update loop (subset of phase1; compat) 'callbacks': float, # CallbackPhase.STEP callbacks (not plugins) 'step_simulation': float, # p.stepSimulation(); non-zero only if physics=True 'collision_check': float, 'collision_breakdown': { # present only when collision ran 'get_aabbs': float, 'spatial_hashing': float, 'aabb_filtering': float, 'contact_points': float, # narrow phase; non-zero only if physics=True 'total': float, }, 'events_pre_step': float, # handlers of the pre_step event 'callbacks_pre_step': float, # CallbackPhase.PRE_STEP callbacks 'events_step': float, # handlers of the step event (before callbacks) 'events_post_step': float, 'callbacks_post_step': float, # CallbackPhase.POST_STEP callbacks 'events_collision': float, 'monitor_update': float, 'total': float, }
Otherwise returns None.
Performance note: time.perf_counter() calls have negligible overhead (<0.1% for 10k objects). The profiling measurements themselves do not significantly impact simulation performance.
- get_memory_usage()
Get current memory usage (requires enable_memory_profiling=True).
- Return type:
- Returns:
Dictionary with current and peak memory usage in MB, or None if not enabled. Keys: ‘current_mb’, ‘peak_mb’
Note
Returns Python heap memory tracked by tracemalloc, NOT RSS (process memory).
tracemalloc tracks Python object allocations, not C extensions or OS-level memory.
For total process memory (RSS), use: psutil.Process().memory_info().rss
Peak is cumulative since last reset_peak() call (interval-based in profiling).
Example:
>>> sim = MultiRobotSimulationCore.from_dict(config) >>> # ... run simulation with enable_memory_profiling=True ... >>> mem = sim.get_memory_usage() >>> if mem: >>> print(f"Python heap: {mem['current_mb']:.2f} MB, Peak: {mem['peak_mb']:.2f} MB")
pybullet_fleet.data_monitor module
Real-time data monitor window for PyBullet simulation Shows simulation statistics in a separate tkinter window
- class pybullet_fleet.data_monitor.DataMonitor(title='Simulation Monitor', enable_gui=True, width=680, height=480, x=-1, y=-1, initial_target_rtf=None, initial_timestep=None)
Bases:
objectReal-time data monitoring window
- start()
Start Tk in a separate process on macOS, or a thread elsewhere.
- Return type:
- process_events()
Forward subprocess commands at the simulation boundary, even paused.
- Return type:
- stop()
Stop the monitor window.
Tk is not thread-safe, so from another thread this only asks the Tk thread to close the window (it polls
running) and waits for it to end, at most_STOP_JOIN_TIMEOUTseconds.- Return type:
- write_data(sim_data)
Write simulation data to shared file (called from main simulation).
Uses atomic write (write to temp file + os.replace) to prevent the reader from seeing a truncated / partially-written JSON file.
- write_frame(frame)
Write a
MonitorFramethrough the legacy JSON monitor path.The JSON (keys and values) is what it has always been; only the entity list is serialized once per change of
frame.entitiesrather than on every write.- Return type:
- set_command_sink(sink)
Set the thread-safe callable that accepts monitor commands.
- Return type:
- pybullet_fleet.data_monitor.main()
Run standalone data monitor
pybullet_fleet.entity_registry module
Entity class registry for config-driven spawning.
Mirrors the controller registry pattern (register_controller /
create_controller): a lightweight name → class mapping that enables
YAML config to specify type: agent, type: sim_object, or any
user-registered custom entity class.
Built-in entity types are auto-registered at import time:
"agent"→Agent"sim_object"→SimObject
Programmatic registration (Python):
from pybullet_fleet.entity_registry import register_entity_class
register_entity_class("forklift", ForkliftAgent)
Config-driven registration (YAML) — no Python code needed:
entity_classes:
forklift: "my_ros_pkg.entities.ForkliftAgent"
conveyor: "warehouse_sim.conveyor.ConveyorObject"
robots:
- type: forklift
urdf_path: robots/forklift.urdf
pose: [0, 0, 0.05]
The entity_classes section is processed by
register_entity_classes_from_config() before robots are spawned,
so custom types are available for type: dispatch in the robots
section.
- pybullet_fleet.entity_registry.register_entity_class(name, cls)
Register an entity class under name.
- pybullet_fleet.entity_registry.register_entity_classes_from_config(entity_classes)
Register entity classes from a config dictionary via dynamic import.
Each key is the registry name (used as
typein therobotssection) and each value is a dotted Python path"module.path.ClassName".Called automatically by
from_yaml()andfrom_dict()when the config contains anentity_classessection.- Parameters:
entity_classes (
Dict[str,Any]) – Mapping of{name: "dotted.module.ClassName", ...}.- Raises:
ImportError – If the module cannot be imported.
AttributeError – If the class does not exist in the module.
TypeError – If the resolved class is not a
SimObjectsubclass.
- Return type:
Example:
register_entity_classes_from_config({ "forklift": "my_pkg.entities.ForkliftAgent", "conveyor": "warehouse_sim.conveyor.ConveyorObject", })
pybullet_fleet.events module
Lightweight event pub/sub for simulation lifecycle events.
Two usage levels:
Global bus (
sim.events): sim-wide events (pre_step, agent_spawned, etc.)Per-entity bus (
agent.events): entity-specific hooks for subclasses
Handlers execute in priority order (lower = first). Same priority = FIFO. Exceptions in handlers are logged but do not block other handlers.
The simulation’s bus also carries the other per-step hooks: callbacks from
register_callback() and plugin on_step() subscribe to the step events
in tiers of their own, after the handlers registered with EventBus.on().
A handler on a step event can be frequency-limited; the bus then schedules it
on the simulation clock with the same fixed grid as callbacks and plugins.
Pre-defined event names are available as SimEvents constants.
Custom event names (any str) are also supported for user-defined extensions.
- class pybullet_fleet.events.SimEvents
Bases:
objectPre-defined event name constants.
Using these constants prevents typos and enables IDE auto-completion, while the
EventBusstill accepts anystrfor user-defined events.Simulation lifecycle (emitted on
sim.events):sim.events.on(SimEvents.PRE_STEP, handler) sim.events.on(SimEvents.POST_STEP, handler)
Entity lifecycle (emitted on both
sim.eventsandentity.events):sim.events.on(SimEvents.OBJECT_SPAWNED, handler) agent.events.on(SimEvents.ACTION_COMPLETED, handler)
Custom events (any string — no constant needed):
sim.events.on("my_plugin_event", handler)
- PRE_STEP: str = 'pre_step'
dt,sim_time(the time of the previous state).- Type:
Emitted at the start of each step, before the clock advances. kwargs
- STEP: str = 'step'
Emitted after the objects have been updated, before their new poses are written to PyBullet and before the collision check – the point where
register_callback()callbacks run by default. kwargs:dt,sim_time(the time of the new state).
- POST_STEP: str = 'post_step'
dt,sim_time.- Type:
Emitted at the end of each step. kwargs
- PAUSED: str = 'paused'
Emitted when simulation is paused. No kwargs.
- RESUMED: str = 'resumed'
Emitted when simulation is resumed. No kwargs.
- OBJECT_SPAWNED: str = 'object_spawned'
no kwargs.
- Type:
Global
- Type:
obj. Per-entity
- OBJECT_REMOVED: str = 'object_removed'
no kwargs.
- Type:
Global
- Type:
obj. Per-entity
- AGENT_SPAWNED: str = 'agent_spawned'
agent.- Type:
Global only
- AGENT_REMOVED: str = 'agent_removed'
agent.- Type:
Global only
- COLLISION_STARTED: str = 'collision_started'
other.- Type:
Global
- Type:
obj_a,obj_b. Per-entity
- COLLISION_ENDED: str = 'collision_ended'
other.- Type:
Global
- Type:
obj_a,obj_b. Per-entity
- PRE_UPDATE: str = 'pre_update'
dt. Emitted before agent movement/action processing.- Type:
Per-entity only
- POST_UPDATE: str = 'post_update'
dt,moved(bool). Emitted after agent update completes.- Type:
Per-entity only
- ACTION_STARTED: str = 'action_started'
action.- Type:
Global
- Type:
agent,action. Per-entity
- ACTION_COMPLETED: str = 'action_completed'
action,status.- Type:
Global
- Type:
agent,action,status. Per-entity
- pybullet_fleet.events.STEP_EVENTS = frozenset({'post_step', 'pre_step', 'step'})
Events emitted once per step with
dtandsim_time; the only ones a subscription may be frequency-limited on.
- pybullet_fleet.events.Clock
clock()returns the simulation time to schedule on and the timestep.
- class pybullet_fleet.events.EventBus(clock=None)
Bases:
objectLightweight event pub/sub bus.
Usage:
bus = EventBus() bus.on("collision_started", my_handler, priority=0) bus.emit("collision_started", obj_a=a, obj_b=b) bus.off("collision_started", my_handler)
- Parameters:
clock (
Optional[Callable[[],Tuple[float,float]]]) – Returns(now, timestep)for scheduling frequency-limited subscriptions. The simulation’s bus (sim.events) has one; a bus without a clock (a bare or per-entity bus) rejectsfrequency.
An emit calls the subscriptions present when it starts: a handler added or removed by a handler takes effect from the next emit.
- on(event, handler, priority=0, frequency=None)
Register
handlerforevent. Lowerpriorityruns first; equal ones in registration order.- Parameters:
event (
str) – Event name, aSimEventsconstant or any string.handler (
Callable) – Called with the event’s keyword arguments.priority (
int) – Order among this event’s handlers (lower = first).frequency (
Optional[float]) – Rate in Hz, for the step events (pre_step,step,post_step) on a bus with a clock. The handler then runs on a fixed grid ofk / frequencyseconds of simulated time (asregister_callback(frequency=...)does), scheduled on the time it observes, and itsdtis the simulated time since it last ran.Noneor0runs it on every emit, as0does forregister_callback().
- Raises:
ValueError –
frequencyis negative or not finite, is given for an event other than a step event, or the bus has no clock.- Return type:
- off(event, handler)
Unregister
handlerfromevent(every registration of it made withon()).- Return type:
- emit(event, **kwargs)
Fire event. Handlers called in priority order, then callbacks, then plugins.
The simulation emits the step events (
pre_step,step,post_step) once per step. Emitting one onsim.eventsyourself runs everything subscribed to it,register_callback()callbacks and pluginon_step()included, uses up the due beats of the frequency-limited ones, and lets a callback’s exception propagate.- Return type:
- clear(event=None)
Remove the handlers registered with
on(); foreventonly when given.Callbacks and plugins the simulation subscribed are kept.
- Return type:
- has_handlers(event)
Whether emitting
eventwould call anything (handlers, callbacks or plugins).- Return type:
pybullet_fleet.fleet_api module
Transport-neutral fleet state and command API.
The classes in this module intentionally avoid ROS imports. ROS bridge wrappers, RMF plugin paths, and future replay tools can share these Python data structures and call sites without depending on a specific transport.
- class pybullet_fleet.fleet_api.FleetStateProvider(sim_core)
Bases:
objectGenerate deterministic fleet state values from a simulation core.
- get_states()
Return 3D states for all agents.
get_states()uses the more general 3D representation by default. Callget_states_2d()when a planar transport wants a smaller model.- Return type:
list[RobotState3D]
- get_states_2d(names=None)
Return planar states for all or selected agents.
- Return type:
list[RobotState2D]
- get_states_3d(names=None)
Return 3D states for all or selected agents.
- Return type:
list[RobotState3D]
- class pybullet_fleet.fleet_api.FleetCommandDispatcher(sim_core, *, allowed_names=None, retain_command_events=True)
Bases:
objectValidate and apply fleet commands against a simulation core.
- refresh_name_index()
Rebuild the robot-name index used for command dispatch.
- Return type:
- navigate(goals, *, source='python', command_id=None)
Apply one or more navigation goals by robot name.
A target robot provides
get_pose(),set_goal_pose()andpath_rejection(), asAgentdoes.- Return type:
CommandAck
- joint_command(commands, *, source='python', command_id=None)
Apply one or more joint target commands by robot name.
- Return type:
CommandAck
- stop(names, *, source='python', command_id=None)
Stop one or more robots by name.
- Return type:
CommandAck
- attach(commands, *, source='python', command_id=None)
Attach or detach objects for one or more robots by name.
- Return type:
CommandAck
- execute_action(commands, *, source='python', command_id=None)
Queue generic PyBulletFleet actions for one or more robots.
- Return type:
CommandAck
pybullet_fleet.geometry module
Geometric primitives: Pose, Path, and quaternion slerp utilities.
- pybullet_fleet.geometry.Quat
Quaternion in
(x, y, z, w)convention — same as PyBullet.
- pybullet_fleet.geometry.ScalarOrAxes
Scalar limit or per-axis sequence (used for kinematic limits and similar).
- pybullet_fleet.geometry.is_scalar(v)
Return
Trueif v should be treated as a scalar (broadcastable) value.Accepts Python
int/float, numpy numeric scalars, or a 0-d numpy array. Anything else (list, tuple, 1-d ndarray, …) is treated as per-axis.- Return type:
- pybullet_fleet.geometry.as_axes(v, dim=3)
Coerce v to a
(dim,)numpy array, broadcasting scalars.- Raises:
ValueError – If v is array-like but its shape is not
(dim,).- Return type:
- pybullet_fleet.geometry.projected_axis_limit(limit, direction_unit)
Direction-projected scalar limit from per-axis caps.
Given a per-axis cap
arrand a unit directiond, returns the largest scalarvsuch that|d[i]| * v <= arr[i]for every axis:v_max = 1 / max_i ( |d[i]| / arr[i] )
Used to convert per-axis kinematic limits (velocity or acceleration) into the equivalent scalar bound along a given travel direction.
- pybullet_fleet.geometry.clamp_vec_to_limit(vec, limit)
Clamp a vector against a scalar or per-axis cap.
Semantics depend on the shape of limit:
Scalar ⇒ Euclidean magnitude clamp: if
|vec| > limit, the vector is scaled down to lengthlimitwhile preserving direction. Acts as projection onto a sphere of radiuslimit.Per-axis ⇒ component-wise clamp: each
vec[i]is independently clipped to[-limit[i], +limit[i]]. Acts as projection onto an axis-aligned box.
Non-finite scalar limits (
math.inf) short-circuit and return vec unchanged.
- class pybullet_fleet.geometry.Pose(position, orientation=<factory>)
Bases:
objectPosition and orientation representation for any object in the simulation. Compatible with ROS2 geometry_msgs/Pose and PyBullet’s (position, orientation) tuples.
Supports both quaternion and Euler angle representations.
- position
[x, y, z] in world coordinates
- orientation
[x, y, z, w] quaternion (defaults to no rotation)
- property x: float
X coordinate.
- property y: float
Y coordinate.
- property z: float
Z coordinate.
- property roll: float
Roll angle in radians (rotation around x-axis).
- property pitch: float
Pitch angle in radians (rotation around y-axis).
- property yaw: float
Yaw angle in radians (rotation around z-axis).
- classmethod from_xyz(x, y, z)
Create Pose from x, y, z coordinates.
- classmethod from_euler(x, y, z, roll=0.0, pitch=0.0, yaw=0.0)
Create Pose from position and Euler angles.
- classmethod from_pybullet(position, orientation)
Create Pose from PyBullet position and orientation tuples.
- as_position_orientation()
Return (position, orientation) tuple for PyBullet.
- as_tuple()
Return (position, orientation) tuple. Alias for as_position_orientation() for convenience.
- as_euler()
Return orientation as Euler angles (roll, pitch, yaw).
- class pybullet_fleet.geometry.Path(waypoints)
Bases:
objectRepresents a path as a sequence of waypoints (Poses).
- waypoints
List of Pose objects representing the path
Example:
# Create from Pose list (recommended) path = Path([ Pose.from_xyz(0, 0, 0), Pose.from_xyz(1, 0, 0), Pose.from_xyz(1, 1, 0) ]) # Create from positions path = Path.from_positions([[0, 0, 0], [1, 0, 0], [1, 1, 0]]) # Create predefined shapes circle = Path.create_circle(center=[0, 0], radius=1.5) square = Path.create_square(center=[0, 0], side_length=2.0)
- waypoints: List[Pose]
- classmethod from_positions(positions, orientation=None)
Create Path from list of positions with optional shared orientation.
- Parameters:
- Return type:
Path- Returns:
Path instance
Example:
path = Path.from_positions([ [0, 0, 0], [1, 0, 0], [1, 1, 0] ])
- classmethod create_rectangle(center, width, height, rpy=[0.0, 0.0, 0.0])
Create a rectangular path in 3D.
- Parameters:
center (
List[float]) – [x, y, z] center position in world coordinateswidth (
float) – Width of rectangle (X direction in local frame)height (
float) – Height of rectangle (Y direction in local frame)rpy (
List[float]) – [roll, pitch, yaw] in radians. Defaults to [0, 0, 0]. When non-zero, the Z+ axis of the robot will be perpendicular to the rectangle plane.
- Return type:
Path- Returns:
Path instance with waypoints at rectangle corners
Example:
rect = Path.create_rectangle(center=[0, 0, 1], width=3.0, height=2.0) tilted_rect = Path.create_rectangle(center=[0, 0, 1], width=3.0, height=2.0, rpy=[0.1, 0.2, 0])
- classmethod create_square(center, side_length, rpy=[0.0, 0.0, 0.0])
Create a square path in 3D.
- Parameters:
- Return type:
Path- Returns:
Path instance with waypoints at square corners
Example:
square = Path.create_square(center=[0, 0, 0], side_length=2.0) tilted_square = Path.create_square(center=[0, 0, 1], side_length=2.0, rpy=[0.1, 0.2, 0])
Note:
This is a wrapper for create_rectangle with width == height.
- classmethod create_ellipse(center, radius_x, radius_y, num_points=16, rpy=[0.0, 0.0, 0.0], start_angle=0.0, end_angle=6.283185307179586)
Create an elliptical path in 3D.
- Parameters:
center (
List[float]) – [x, y, z] center position in world coordinatesradius_x (
float) – Radius along X axis in local frameradius_y (
float) – Radius along Y axis in local framenum_points (
int) – Number of waypoints along the arcrpy (
List[float]) – [roll, pitch, yaw] in radians. Defaults to [0, 0, 0].start_angle (
float) – Start angle [rad] in the local XY-planeend_angle (
float) – End angle [rad] in the local XY-plane
- Return type:
Path- Returns:
Path instance with waypoints along ellipse
Example:
ellipse = Path.create_ellipse(center=[0, 0, 0], radius_x=2.0, radius_y=1.0) tilted_ellipse = Path.create_ellipse(center=[0, 0, 1], radius_x=2.0, radius_y=1.0, rpy=[0, 0.3, 0])
- classmethod create_circle(center, radius, num_points=16, rpy=[0.0, 0.0, 0.0], start_angle=0.0, end_angle=6.283185307179586)
Create a circular path in 3D.
- Parameters:
center (
List[float]) – [x, y, z] center position in world coordinatesradius (
float) – Circle radiusnum_points (
int) – Number of waypoints along the arcrpy (
List[float]) – [roll, pitch, yaw] in radians. Defaults to [0, 0, 0].start_angle (
float) – Start angle [rad] in the local XY-planeend_angle (
float) – End angle [rad] in the local XY-plane
- Return type:
Path- Returns:
Path instance with waypoints along circle
Example:
circle = Path.create_circle(center=[0, 0, 0], radius=1.5) arc = Path.create_circle(center=[0, 0, 0], radius=1.5, start_angle=0, end_angle=np.pi)
Note:
This is a wrapper for create_ellipse with radius_x == radius_y.
- append(other)
Append waypoints from another path in-place.
Note:
This mutates the current Path. For a non-mutating version, use `combined = path1 + path2`.
- Return type:
- classmethod from_paths(paths)
Create a single Path by concatenating multiple paths.
Example:
circle_arc = Path.create_circle(center=[0, 0, 0.5], radius=2.0, num_points=16, start_angle=0.0, end_angle=np.pi/2) line = Path.from_positions([[1, 1, 0.5], [3, 1, 0.5]]) full = Path.from_paths([circle_arc, line])
- Return type:
Path
- get_total_distance()
Calculate total path length.
- Return type:
- Returns:
Total distance in meters
- visualize(show_lines=True, line_color=None, line_width=2.0, show_waypoints=False, show_axes=False, axis_length=0.3, show_points=False, point_size=0.05, lifetime=0.0)
Visualize path with lines and optional waypoint markers.
- Parameters:
show_lines (
bool) – If True, draw lines connecting waypointsline_color (
List[float]) – RGB color for path lines [r, g, b] (0-1 range), None for defaultline_width (
float) – Width of path linesshow_waypoints (
bool) – If True, show waypoint coordinate axes and pointsshow_axes (
bool) – If True, draw X, Y, Z axes at each waypointaxis_length (
float) – Length of coordinate axes in metersshow_points (
bool) – If True, draw spheres at waypoint positionspoint_size (
float) – Radius of waypoint spheres in meterslifetime (
float) – Debug line lifetime (0 = permanent until reset)
- Return type:
- Returns:
List of debug item IDs (for later removal if needed)
Example:
# Just show path lines path = Path.create_circle(center=[0, 0, 0.5], radius=2.0) path.visualize(line_color=[1, 0, 0]) # Show path with waypoint orientations path.visualize(show_waypoints=True, show_axes=True)
- visualize_waypoints(show_axes=True, axis_length=0.3, show_points=True, point_size=0.05, lifetime=0.0)
Visualize waypoints with coordinate axes for debugging.
- Parameters:
show_axes (
bool) – If True, draw X, Y, Z axes at each waypointaxis_length (
float) – Length of coordinate axes in metersshow_points (
bool) – If True, draw spheres at waypoint positionspoint_size (
float) – Radius of waypoint spheres in meterslifetime (
float) – Debug line lifetime (0 = permanent until reset)
- Return type:
- Returns:
List of debug item IDs (for later removal if needed)
Example:
path = Path.create_square(center=[0, 0, 1], side_length=2.0, rpy=[0.1, 0.2, 0]) debug_ids = path.visualize_waypoints(axis_length=0.5)
- pybullet_fleet.geometry.cross3(a, b)
np.crossfor two 3-vectors, with the same arithmetic.np.crosshandles arbitrary shapes and broadcasting, and that overhead dominated goal setting for differential drive; this is the plain formula.- Return type:
- pybullet_fleet.geometry.quat_to_rot_matrix(quat)
Convert a quaternion
(x, y, z, w)to a 3×3 rotation matrix.Returns the matrix as a flat 9-element tuple in row-major order:
(r00, r01, r02, r10, r11, r12, r20, r21, r22)
This is allocation-free and suitable for hot-path use.
- Parameters:
quat (
Tuple[float,float,float,float]) – Quaternion(x, y, z, w)— same convention as PyBullet. Automatically normalized if not already unit-length.- Return type:
Tuple[float,float,float,float,float,float,float,float,float]- Returns:
9-element tuple representing the 3×3 rotation matrix (row-major).
- Raises:
ValueError – If the quaternion has zero norm.
- pybullet_fleet.geometry.rotate_vector(vec, quat)
Rotate a 3-D vector by a quaternion.
Equivalent to
scipy.spatial.transform.Rotation.from_quat(quat).apply(vec)but avoids SciPy object allocation, making it suitable for per-tick hot paths.
- pybullet_fleet.geometry.quat_from_rotvec(rotvec)
Convert a rotation vector (axis × angle) to a quaternion
(x, y, z, w).Equivalent to
scipy.spatial.transform.Rotation.from_rotvec(rotvec).as_quat().
- pybullet_fleet.geometry.quat_multiply(q1, q2)
Hamilton product of two quaternions in
(x, y, z, w)convention.Equivalent to
(Rotation.from_quat(q1) * Rotation.from_quat(q2)).as_quat(). For active rotations this corresponds to applying q2 first, then q1.
- pybullet_fleet.geometry.quat_angle_between(q0, q1)
Compute the rotation angle (radians) between two quaternions.
Equivalent to
(Rotation.from_quat(q1) * Rotation.from_quat(q0).inv()).magnitude(). Handles the double-cover:qand-qrepresent the same rotation. Inputs are normalized internally, so non-unit quaternions are accepted.
- pybullet_fleet.geometry.rotation_axis_z(q_from, q_to)
World-frame
zcomponent of the unit axis of the shortest rotationq_from -> q_to.Accepts
(4,)or(N, 4)arrays of(x, y, z, w)quaternions and returns a scalar array or(N,). A slerp between the two turns about this axis, so its yaw rate is this times the angular speed:+1for a pure counter-clockwise turn aboutz,-1clockwise,0with no rotation.- Return type:
- class pybullet_fleet.geometry.SlerpPrecomp(dot: float, theta_0: float, sin_theta_0: float, needs_flip: bool)
Bases:
NamedTuplePrecomputed constants for fast quaternion slerp between two keyframes.
- dot: float
Alias for field number 0
- theta_0: float
Alias for field number 1
- sin_theta_0: float
Alias for field number 2
- needs_flip: bool
Alias for field number 3
- pybullet_fleet.geometry.quat_slerp_precompute(q0, q1)
Precompute constants for fast scalar quaternion slerp.
- pybullet_fleet.geometry.quat_slerp(q0, q1, t, precomp)
Fast scalar quaternion slerp for normalized quaternions.
Specialized for the two-keyframe case where q0/q1 are fixed and only t varies per call. Uses math.sin/cos for scalar operations instead of numpy.
Note:
q0 and q1 must be unit quaternions. The normal slerp path preserves unit length by construction; the near-identical fallback normalizes explicitly.
- Parameters:
- Return type:
- Returns:
Interpolated quaternion as numpy array [x, y, z, w].
- pybullet_fleet.geometry.quat_slerp_batch(q0, q1, t, dot, theta0, sin_theta0)
Vectorised SLERP for N quaternion pairs.
Evaluates slerp simultaneously for all N agents using NumPy — the hot path for
BatchDifferentialControllerandBatchOmniController.The caller is responsible for shortest-path correction:
q1must already have had its sign flipped wheredot(q0, q1) < 0, anddotmust be the corrected (non-negative) dot product.- Parameters:
q0 (
ndarray) –(N, 4)start quaternions.q1 (
ndarray) –(N, 4)end quaternions (sign-corrected for shortest path).t (
ndarray) –(N,)interpolation parameters in[0, 1].dot (
ndarray) –(N,)dot productsdot(q0, q1) >= 0.theta0 (
ndarray) –(N,)half-anglesacos(dot).sin_theta0 (
ndarray) –(N,)sin(theta0).
- Return type:
- Returns:
(N, 4)interpolated unit quaternions.
pybullet_fleet.logging_utils module
Logging utilities with lazy evaluation for expensive operations.
Design intent & usage policy: - The standard Python logger always evaluates f-strings and expensive computations, even if the log level is disabled. - LazyLogger/NamedLazyLogger allow you to pass a lambda, so the message is only evaluated if the log level is enabled. - This prevents unnecessary computation and side effects, improving performance.
Usage policy: - For lightweight constants or simple strings, pass them directly (no lambda needed). - For expensive computations or side effects, always wrap in a lambda. - Both are supported for flexibility and easier migration from standard logging.
See test_logging_utils.py for more usage and test examples.
- class pybullet_fleet.logging_utils.LazyLogger(name=None, logger=None)
Bases:
objectLogger wrapper with lazy evaluation for expensive formatting operations.
This prevents expensive string formatting (e.g., NumPy array conversion) when the log level is not enabled.
Usage:
logger = LazyLogger(__name__) logger.debug(lambda: f"Expensive array: {numpy_array}")
Or with the decorator:
@lazy_log def my_logger(): return logging.getLogger(__name__) logger = my_logger() logger.debug(lambda: f"Array: {arr}")
- __init__(name=None, logger=None)
Initialize LazyLogger.
- debug(msg_func, *args, **kwargs)
Log debug message with lazy evaluation.
- info(msg_func, *args, **kwargs)
Log info message with lazy evaluation.
- warning(msg_func, *args, **kwargs)
Log warning message with lazy evaluation.
- error(msg_func, *args, **kwargs)
Log error message with lazy evaluation.
- critical(msg_func, *args, **kwargs)
Log critical message with lazy evaluation.
- property logger: Logger
Get underlying logger instance.
- isEnabledFor(level)
Check if logging is enabled for the given level.
- Return type:
- class pybullet_fleet.logging_utils.NamedLazyLogger(name=None, logger=None, prefix='')
Bases:
LazyLoggerLazyLogger with a dynamic prefix for instance-level identification.
Designed for SimObject/Agent/Action instances where each log line should include identifiers like object_id and name, without manually embedding them in every log call.
The prefix can be updated at any time via
set_prefix()(e.g. afterobject_idis assigned by sim_core).Usage:
# In SimObject.__init__ self._log = NamedLazyLogger(__name__) self._log.set_prefix(f"[obj:{self.object_id}] ") # In Agent.__init__ (after super().__init__) self._log.set_prefix(f"[Agent:{self.object_id}:{self.name}] ") # Log calls — prefix is prepended automatically self._log.info("Path complete") # => [Agent:3:robot_A] Path complete self._log.debug(lambda: f"pos={self.get_pose().position[:2]}") # => [Agent:3:robot_A] pos=[1.0, 2.0] (only evaluated if DEBUG enabled)
Note
The prefix is stored as a plain string and prepended inside
_log_lazyonly when the level is enabled, so the cost is negligible when the message is filtered out.- __init__(name=None, logger=None, prefix='')
Initialize NamedLazyLogger.
- set_prefix(prefix)
Update the prefix prepended to every log message.
Call this whenever the identifying information changes (e.g. after object_id is assigned).
- Parameters:
prefix (
str) – New prefix string (include trailing space if desired)
- property prefix: str
Get current prefix string.
- pybullet_fleet.logging_utils.get_named_lazy_logger(name, prefix='')
Get a NamedLazyLogger instance.
This is the recommended way to create instance-level loggers for SimObject / Agent / Action classes.
- Parameters:
- Return type:
NamedLazyLogger- Returns:
NamedLazyLogger instance
Example:
# In __init__ self._log = get_named_lazy_logger(__name__, f"[Agent:{self.object_id}] ") self._log.debug(lambda: f"pos={pos}")
- pybullet_fleet.logging_utils.get_lazy_logger(name)
Get a LazyLogger instance for the given name.
This is the recommended way to create lazy loggers.
- Parameters:
name (
str) – Logger name (typically __name__)- Return type:
LazyLogger- Returns:
LazyLogger instance
Example:
logger = get_lazy_logger(__name__) logger.debug(lambda: f"Expensive: {numpy_array}")
- pybullet_fleet.logging_utils.wrap_existing_logger(logger)
Wrap an existing logger with lazy evaluation.
- Parameters:
logger (
Logger) – Existing logging.Logger instance- Return type:
LazyLogger- Returns:
LazyLogger wrapping the existing logger
Example:
standard_logger = logging.getLogger(__name__) lazy_logger = wrap_existing_logger(standard_logger) lazy_logger.debug(lambda: f"Array: {arr}")
pybullet_fleet.path_request module
A request to follow a path: the waypoints and how to follow them.
PathRequest is what Agent.request_path and the controllers’
request_path take, what a controller holds while it brakes or finishes
its current path (see GoalReplacement), and
what a MoveAction sends. Agent.set_path
and the controllers’ set_path build one from their arguments.
A request keeps its identity through the copies made along the way (the
approach waypoint Agent.request_path adds is a copy with
dataclasses.replace()), so a caller can ask a controller what became of
the request it sent (path_request_state()).
Identity is not equality: two requests with equal fields are different
requests, and a replace() copy is the same one – build a new
PathRequest to send a new request.
- class pybullet_fleet.path_request.PathRequest(path, final_orientation_align=True, direction=None, auto_approach=True, _token=<factory>)
Bases:
objectWaypoints to follow and how to follow them.
- Parameters:
path (
Sequence[Pose]) – The waypoints, in order (a sequence ofPose; stored as a tuple).final_orientation_align (
bool) – Rotate to the last waypoint’s orientation after reaching its position.direction (
Optional[MovementDirection]) – Movement direction (differential drive only): aMovementDirectionor its string value;Noneuses the controller’sdefault_direction.auto_approach (
bool) – LetAgent.request_pathput the current pose in front of the path when the agent is at rest and far from its first waypoint. Controllers ignore it.
A copy made with
dataclasses.replace()is the same request (seesame_request()); to send a new request, build a new one. Frozen, but not hashable: thePosewaypoints are mutable. Identity does not surviveto_record()/from_record(), so a request restored from a checkpoint is a new one.- path: Sequence[Pose]
- final_orientation_align: bool = True
- direction: MovementDirection | None = None
- auto_approach: bool = True
- same_request(other)
Whether
otheris this request or a copy of it made on its way to a controller.- Return type:
- to_record()
Plain-data form for checkpoints (without
auto_approach: a held request has had its approach applied already).- Return type:
- classmethod from_record(record)
Inverse of
to_record().- Return type:
PathRequest
- class pybullet_fleet.path_request.PathRequestState(value)
Bases:
EnumWhat became of a
PathRequestsent to a controller.- ACTIVE = 'active'
Being followed.
- PENDING = 'pending'
Accepted and held, to start once the agent stops or finishes its path.
- FINISHED = 'finished'
Followed to its end; the agent came to rest there.
- GONE = 'gone'
replaced by another request, dropped from the hold, stopped, braked, cancelled or never sent.
- Type:
Not (or no longer) the controller’s
- UNKNOWN = 'unknown'
The controller does not track requests (a custom controller written against
set_path).
- pybullet_fleet.path_request.request_state(request, active, pending, finished)
request’s state given a controller’s active, pending and last finished requests.- Return type:
PathRequestState
pybullet_fleet.plugin_utils module
Shared registry and factory utilities for Controller, AgentPlugin, and SimPlugin.
Provides:
PluginRegistry— reusable registry withtype:/class:resolution.from_config_introspect()— unifiedconfig dict → __init__ kwargsfactory, used by all three base classes’from_config()classmethods.
Usage in each subsystem:
_registry = PluginRegistry[Controller]("controller")
class Controller(ABC):
def __init_subclass__(cls, **kw):
super().__init_subclass__(**kw)
_registry.auto_register_subclass(cls)
@classmethod
def from_config(cls, config):
return from_config_introspect(cls, (), config)
class AgentPlugin:
@classmethod
def from_config(cls, agent, config):
return from_config_introspect(cls, (agent,), config)
- pybullet_fleet.plugin_utils.from_config_introspect(cls, owner_args, config)
Create an instance by matching config keys to
__init__kwargs.This is the unified factory behind
Controller.from_config(),AgentPlugin.from_config(), andSimPlugin.from_config().- Parameters:
- Return type:
- Returns:
Instance of cls constructed with matched kwargs and
configattribute set to the original dict.
- class pybullet_fleet.plugin_utils.PluginRegistry(label)
Bases:
Generic[T]Self-contained registry supporting
type:andclass:resolution.Each subsystem (Controller, AgentPlugin, SimPlugin) creates one instance. The registry owns its internal dict — no external dict is required.
- Parameters:
label (
str) – Human-readable label for error messages (e.g."controller").
- register(name, cls)
Manually register cls under name.
- Return type:
- unregister(name)
Remove name from the registry. No-op if not present.
- Return type:
- auto_register_subclass(cls)
Auto-register cls if it has
_registry_nameand is concrete.Intended to be called from
__init_subclass__in base classes. Abstract classes (detected viainspect.isabstract()) are skipped.- Return type:
- get(name)
Look up a class by registry name.
- resolve_from_entry(entry, base_class)
Resolve a class from a YAML-style entry dict.
Supports two formats:
{"type": "<registry_name>", ...}— registry lookup.{"class": "<dotted.path>", ...}— dynamic import.
- Parameters:
- Return type:
- Returns:
Resolved class object.
- Raises:
KeyError – If
typename is not in the registry.TypeError – If
classdoes not resolve to a base_class subclass.ValueError – If neither
typenorclassis present.
pybullet_fleet.recorder module
recorder.py — SimulationRecorder for headless/GUI simulation recording.
Captures frames via getCameraImage and saves as GIF or MP4.
Uses GPU rendering (ER_BULLET_HARDWARE_OPENGL) in GUI mode,
CPU rendering (ER_TINY_RENDERER) for headless/custom cameras.
Integrates with MultiRobotSimulationCore via the callback system.
Output format is determined by file extension:
.gif— Animated GIF via Pillow (always available).mp4— H.264 MP4 via imageio + pyav (requirespip install imageio[pyav])
Usage:
# GIF (default)
sim.start_recording("output.gif", duration=4.0, fps=15)
sim.run_simulation(duration=5.0)
# MP4 (smaller files, better quality)
sim.start_recording("output.mp4", duration=4.0, fps=30)
sim.run_simulation(duration=5.0)
# Via environment variable (zero code changes)
# RECORD=output.mp4 python pybullet_fleet/examples/scale/100robots_grid_demo.py
# Direct instantiation
rec = SimulationRecorder(sim_core, output="output.mp4", duration=4.0)
rec.start()
sim_core.run_simulation(duration=5.0)
rec.stop()
rec.save()
- class pybullet_fleet.recorder.SimulationRecorder(sim_core, output='recording.gif', width=800, height=600, fps=15, duration=None, camera_mode='auto', camera_params=None, orbit_degrees=60.0, time_base='sim')
Bases:
objectRecord simulation frames and save as animated GIF or MP4.
Captures RGB frames using
p.getCameraImage(). UsesER_TINY_RENDERER(CPU) for headless/custom cameras, orER_BULLET_HARDWARE_OPENGL(GPU) in"gui"mode for faster rendering that matches the GUI window exactly.Output format is auto-detected from the file extension:
.gif— Animated GIF via Pillow (always available).mp4— H.264 MP4 via imageio + pyav (requirespip install imageio[pyav])
Camera modes:
"auto"— Compute scene AABB, position camera overhead with auto-framing. Automatically promoted to"gui"when running inp.GUImode."gui"— Record exactly what the GUI camera shows, usingER_BULLET_HARDWARE_OPENGL(GPU). Mouse pan/zoom/rotate is captured in real time. Only valid inp.GUImode."orbit"— Same as auto + camera orbits horizontally over the recording."manual"— Use explicit camera parameters fromcamera_params.
Time bases:
"sim"— (default) Capture at fixed sim-time intervals. Playback always looks like 1× speed regardless of how fast the simulation ran."real"— Capture at wall-clock intervals. Playback reflects actual execution speed (e.g. a 10× sim produces a 10× fast video).
- Parameters:
sim_core (
MultiRobotSimulationCore) – The simulation core instance to record.output (
str) – Output file path (.gifor.mp4). Directory is created automatically.width (
int) – Frame width in pixels.height (
int) – Frame height in pixels.fps (
int) – Capture frequency and playback FPS.duration (
Optional[float]) – Recording duration in simulation seconds (time_base="sim") or wall-clock seconds (time_base="real").Nonefor manual stop.camera_mode (
str) –"auto"|"gui"|"orbit"|"manual"."auto"is promoted to"gui"whenparams.guiis True.camera_params (
Optional[Dict[str,Any]]) – Camera parameters for"manual"mode. Keys:camera_target,camera_distance,camera_yaw,camera_pitch.orbit_degrees (
float) – Total horizontal orbit angle in degrees (for"orbit"mode).time_base (
str) –"sim"(default) or"real". Controls capture timing and duration measurement. See Time bases above.
- start()
Begin recording. Registers a capture callback on sim_core.
- Return type:
- stop()
Stop recording. Unregisters the capture callback.
- Return type:
- save()
Write captured frames to file (GIF or MP4, auto-detected from extension).
- Return type:
- Returns:
The output file path.
- Raises:
ValueError – If no frames have been captured.
RuntimeError – If MP4 is requested but
imageiois not installed.
- property is_recording: bool
Whether the recorder is currently capturing frames.
- property frame_count: int
Number of frames captured so far.
pybullet_fleet.robot_models module
Robot model resolution and auto-detection.
Provides a 3-tier model resolution system (URDF and SDF):
Tier 1 (
pybullet_data): Always available withpip install pybullet.Tier 2 (ROS packages): Available when ROS description packages are installed.
Tier 3 (
robot_descriptions): Available viapip install robot_descriptions.
Usage:
from pybullet_fleet.robot_models import resolve_model
path = resolve_model("panda") # Tier 1: pybullet_data
path = resolve_model("robots/arm.urdf") # Direct path: returned as-is
path = resolve_model("kiva_shelf") # SDF model from pybullet_data
- class pybullet_fleet.robot_models.ModelEntry(rel_path, tier, install_hint='', xacro_args='')
Bases:
objectRegistry entry for a known robot model.
- rel_path: str
- tier: str
- install_hint: str = ''
- xacro_args: str = ''
- pybullet_fleet.robot_models.add_search_path(directory)
Register a directory to search for URDF/SDF files by name.
User search paths are checked before the
KNOWN_MODELSregistry, allowing users to shadow built-in models with custom versions.Example:
from pybullet_fleet.robot_models import add_search_path, resolve_model add_search_path("/opt/company_robots") path = resolve_model("my_agv") # → /opt/company_robots/my_agv.urdf
- Parameters:
directory (
str) – Absolute or relative path to a directory containing.urdfor.sdffiles.- Raises:
ValueError – If the directory does not exist.
- Return type:
- pybullet_fleet.robot_models.remove_search_path(directory)
Remove a previously registered search directory.
No-op if the directory was not registered.
- pybullet_fleet.robot_models.get_search_paths()
Return the current list of user search paths (read-only copy).
- pybullet_fleet.robot_models.register_model(name, path_or_entry, *, force=False)
Register a custom model so it can be resolved by name.
This is the recommended way to make any URDF/SDF loadable via
resolve_model(name)— including models frompybullet_data, ROS packages, orrobot_descriptionsthat are not in the built-inKNOWN_MODELSregistry.Example:
from pybullet_fleet.robot_models import register_model, resolve_model # Simple: register an absolute path register_model("my_agv", "/opt/robots/my_agv.urdf") # Or register a pybullet_data model by relative path + tier register_model("sphere", ModelEntry("sphere2.urdf", "pybullet_data")) path = resolve_model("my_agv")
- Parameters:
name (
str) – Short model name (e.g."my_agv").path_or_entry (
Union[str,ModelEntry]) – Either an absolute path to a URDF/SDF file, or aModelEntryfor full tier metadata.force (
bool) – IfTrue, overwrite an existing entry. By default, raisesValueErrorto prevent accidental overwrites.
- Raises:
ValueError – If name is already registered and force is
False.- Return type:
- pybullet_fleet.robot_models.unregister_model(name)
Remove a model from
KNOWN_MODELS.No-op if the name is not registered.
- pybullet_fleet.robot_models.resolve_model(name_or_path)
Resolve a model name or file path to an absolute URDF/SDF path.
Resolution order:
If
name_or_pathcontains a path separator (os.sepor/) or ends with.urdf/.sdf, treat as a direct file path: absolute paths and paths that exist relative to the CWD are returned as-is; a bundled relative path (e.g."robots/mobile_robot.urdf") otherwise resolves to the packaged asset (absolute), falling back to the raw value if not found.Search user-registered directories (see
add_search_path()).Look up in
KNOWN_MODELSregistry and resolve by tier.Auto-discovery fallback: scan
pybullet_datafiles androbot_descriptionsmodules for a matching name.Raise
FileNotFoundErrorwith install instructions.
Auto-discovery does not modify
KNOWN_MODELS.- Parameters:
name_or_path (
str) – Model name (e.g."panda","kiva_shelf") or file path.- Return type:
- Returns:
Absolute path to the model file (URDF or SDF).
- Raises:
FileNotFoundError – If the model cannot be resolved.
- pybullet_fleet.robot_models.resolve_urdf(name_or_path)
Backward-compatible alias for
resolve_model().Deprecated since version Use:
resolve_model()instead.resolve_urdfwill be removed in a future release.- Return type:
- pybullet_fleet.robot_models.discover_models(tier)
Scan a tier and return all discoverable models.
Unlike
KNOWN_MODELS(curated subset), this scans the actual installed package and returns every model found.- Parameters:
tier (
str) –"pybullet_data"or"robot_descriptions".- Return type:
- Returns:
Dict mapping short model name → absolute URDF/SDF path.
- Raises:
ValueError – If tier is not a supported scan target.
- pybullet_fleet.robot_models.list_all_models()
Check availability of all known models.
- class pybullet_fleet.robot_models.RobotProfile(urdf_path, robot_type='unknown', ee_link_name=None, movable_joint_names=<factory>, joint_lower_limits=<factory>, joint_upper_limits=<factory>, joint_max_velocities=<factory>, num_joints=0, _movable_joint_indices=<factory>, arm_reach=None, ee_link_index=-1)
Bases:
objectAuto-detected robot profile from URDF introspection.
This is a pre-spawn, read-only snapshot intended for external tooling (GUIs, catalog browsers, spawn helpers). It is not used by
Agentat runtime — the Agent maintains its own joint info, IK state, and velocity limits independently. Modifying aRobotProfileinstance has no effect on a running simulation.All fields can be overridden after detection or via
auto_detect_profile(..., **overrides).- urdf_path: str
- robot_type: str = 'unknown'
- num_joints: int = 0
- ee_link_index: int = -1
- make_joint_targets(fractions, agent)
Build a full joint-target list from per-movable-joint fractions.
Each fraction in
[-1, 1]is mapped to the joint’s limit range:target = mid + fraction * half_range
Fixed joints and unmapped joints keep their current position.
- Parameters:
- Return type:
- Returns:
A list with one target per joint (
len(agent.joint_info)), suitable foragent.set_all_joints_targets().
- pybullet_fleet.robot_models.detect_robot_type(body_id, physics_client)
Detect robot type from an already-loaded PyBullet body.
Unlike
auto_detect_profile(), this does not load or remove any bodies — it introspects a body that is already in the simulation. This makes it safe to call in GUI mode without corrupting GPU resources.Note
Best-effort heuristic. The classification relies on joint types and link-name keywords, which does not cover all robot designs. Known limitations:
A differential-drive robot with a passive caster (bounded revolute) is mis-classified as
"mobile_manipulator".Humanoids and hexapods do not match the quadruped keyword set and fall back to
"arm"or"unknown".Grippers with only bounded joints are classified as
"arm".
Use
auto_detect_profile(..., robot_type="mobile")or the**overridesparameter to correct mis-detections.
- pybullet_fleet.robot_models.auto_detect_profile(urdf_path_or_body_id, physics_client, **overrides)
Introspect a URDF/SDF or an already-loaded PyBullet body.
When urdf_path_or_body_id is a string, the URDF/SDF is loaded temporarily and removed after introspection. When it is an int (PyBullet body ID), the already-loaded body is introspected in place — no load or remove occurs. Use the
intform in GUI mode to avoid GPU resource corruption fromremoveBody.Robot type detection is heuristic-based (see
detect_robot_type()for known limitations). Passrobot_type=in overrides to correct any mis-detection.- Parameters:
- Return type:
RobotProfile- Returns:
RobotProfile with detected (or overridden) values.
pybullet_fleet.sdf_loader module
SDF / mesh world loader for PyBulletFleet.
Why self-implemented? PyBullet’s loadSDF() crashes on multi-root-link
models (segfault) and rejects Gazebo SDF joints without <dynamics> defaults.
No usable Python SDF→URDF library exists — sdformat_urdf is C++-only with
no Python bindings, pysdf (PyPI) fails to build on Python 3.12, and
libsdformat14 is a C++ template API not callable via ctypes.
This module provides:
load_mesh_directory()— OBJ/STL mesh directory loader (from world_loader).load_sdf_world()— Load a single SDF<model>(building) as meshes.load_sdf_world_file()— Load a.worldfile, resolving<include>elements (Gazebo Fuel URIs,model://local refs) into SimObjects.resolve_sdf_to_urdf()— Convert a robot SDF into a temporary URDF.
Backward-compatible aliases:
load_rmf_world()→load_mesh_directory()
- pybullet_fleet.sdf_loader.DEFAULT_SCENERY_COLOR = [0.7, 0.7, 0.7, 1.0]
Default color for scenery objects without material info. Matches Gazebo Sim (Harmonic) default — a neutral light grey that renders well under PyBullet’s default lighting.
- pybullet_fleet.sdf_loader.load_mesh_directory(mesh_dir, sim_core=None, collision_mode=CollisionMode.NORMAL_3D, mesh_scale=None, rgba_color=None, pattern='*.obj')
Load mesh files from a directory as static SimObjects.
Scans
mesh_dirfor files matchingpatternand creates a static SimObject for each one. Object names are derived from filenames (stem).Originally written for rmf_demos environments where
rmf_building_map_toolsgenerates OBJ meshes with world-space vertices, but works with any directory of mesh files.- Parameters:
mesh_dir (
str) – Directory containing mesh filessim_core – Simulation core for registration
collision_mode (
CollisionMode) – Collision mode for environment objectsmesh_scale (
Optional[List[float]]) – Optional scale override [sx, sy, sz] (default: [1,1,1])rgba_color (
Optional[List[float]]) – Optional color override [r,g,b,a] (default: grey)pattern (
str) – Glob pattern for mesh files (default:'*.obj')
- Return type:
List[SimObject]- Returns:
List of SimObject instances (one per mesh file)
- Raises:
FileNotFoundError – If
mesh_dirdoes not exist.
- pybullet_fleet.sdf_loader.load_rmf_world(*args, **kwargs)
Backward-compatible alias for
load_mesh_directory().Deprecated since version Use:
load_mesh_directory()instead.- Return type:
List[SimObject]
- pybullet_fleet.sdf_loader.load_sdf_world(sdf_path, sim_core=None, collision_mode=CollisionMode.STATIC, rgba_color=None, mass=0.0, pickable=False, strip_materials=False)
Load building/prop models from an SDF file.
Parses all
<model>elements, iterates over their<link>children, extracts mesh<uri>from the first<visual>and the link-level<pose>, then creates aSimObjectfor each.Supports SDF files containing multiple top-level
<model>elements.This correctly handles rmf_building_map_tools output where floor meshes have world-baked vertices (pose = 0) and wall meshes have local vertices with per-link pose offsets.
- Parameters:
sdf_path (
str) – Absolute path tomodel.sdf.sim_core – Simulation core for object registration.
collision_mode (
CollisionMode) – Collision mode for environment objects (default:STATIC— static scenery participates in collision detection without moving).rgba_color (
Optional[List[float]]) – Optional colour override[r, g, b, a].mass (
float) – Mass for the created objects (default: 0.0 for static).pickable (
bool) – Whether objects can be picked up (default: False).
- Return type:
List[SimObject]- Returns:
List of created SimObject instances.
Example:
from pybullet_fleet.sdf_loader import load_sdf_world objects = load_sdf_world( "/rmf_demos_ws/.../building_L1/model.sdf", sim_core=sim, )
- pybullet_fleet.sdf_loader.load_sdf_world_file(world_path, sim_core=None, collision_mode=CollisionMode.STATIC, skip_models=None, resource_paths=None, force_color=None)
Load a Gazebo
.worldfile with<include>elements.Parses the
<world>element, resolves each<include>to a local model directory (via Fuel download ormodel://search), then callsload_sdf_world()for the building model and creates SimObjects for furniture/prop models.- Parameters:
world_path (
str) – Absolute path to the.worldfile.sim_core – Simulation core for registration.
collision_mode (
CollisionMode) – Collision mode for loaded objects.skip_models (
Optional[List[str]]) – Model names to skip (e.g. robot names likeTinyRobot).resource_paths (
Optional[List[str]]) – Additional directories to search formodel://URIs.
- Return type:
List[SimObject]- Returns:
All SimObjects loaded from the world file.
- pybullet_fleet.sdf_loader.resolve_sdf_to_urdf(sdf_path, model_yaw_offset=0.0)
Convert an SDF robot model to a temporary URDF file.
PyBullet cannot reliably load Gazebo SDF files (
model://URIs, missing joint dynamics defaults). This function:Parses the SDF XML.
Resolves
model://mesh URIs to absolute filesystem paths.Adds missing
<dynamics>defaults that PyBullet requires.Writes a minimal URDF to a temporary file.
The caller is responsible for deleting the temp file when done (or it will be cleaned up on process exit by the OS).
The base link’s
<pose>yaw is automatically detected and applied to visual/collision origins, somodel_yaw_offsetis normally not needed.- Parameters:
- Return type:
- Returns:
Absolute path to the generated temporary URDF file.
Example:
from pybullet_fleet.sdf_loader import resolve_sdf_to_urdf urdf_path = resolve_sdf_to_urdf("/path/to/TinyRobot/model.sdf") agent = Agent.from_urdf(urdf_path, ...)
pybullet_fleet.sim_object module
sim_object.py Base class for simulation objects with attachment support.
- class pybullet_fleet.sim_object.ShapeParams(shape_type=None, mesh_path=None, mesh_scale=<factory>, half_extents=<factory>, radius=0.5, height=1.0, rgba_color=<factory>, frame_pose=None)
Bases:
objectParameters for visual or collision shape.
Similar to URDF’s <visual> and <collision> tags, this allows full control over shape type, geometry, appearance, and frame offset.
- shape_type
Shape type - “box”, “sphere”, “cylinder”, “mesh”, or None (no shape)
- mesh_path
Path to mesh file (required if shape_type=”mesh”)
- mesh_scale
Mesh scaling [sx, sy, sz] (for mesh shapes)
- half_extents
Box half extents [hx, hy, hz] (for box shapes)
- radius
Sphere/cylinder radius (for sphere/cylinder shapes)
- height
Cylinder height (for cylinder shapes)
- rgba_color
RGBA color [r, g, b, a] (for visual shapes, ignored for collision)
- frame_pose
Shape offset as Pose object (relative to body frame)
Example:
# Box visual visual = ShapeParams( shape_type="box", half_extents=[0.5, 0.3, 0.2], rgba_color=[0.8, 0.2, 0.2, 1.0] ) # Mesh collision collision = ShapeParams( shape_type="mesh", mesh_path="collision.obj", mesh_scale=[1.0, 1.0, 1.0] ) # Sphere with offset sphere = ShapeParams( shape_type="sphere", radius=0.5, rgba_color=[0.0, 1.0, 0.0, 1.0], frame_pose=Pose.from_xyz(0, 0, 0.5) )
- radius: float = 0.5
- height: float = 1.0
- frame_pose: Pose | None = None
- classmethod from_dict(d)
Create ShapeParams from a configuration dictionary.
Recognised keys match the dataclass fields:
shape_type,mesh_path,mesh_scale,half_extents,radius,height,rgba_color. Missing keys use dataclass defaults.
- class pybullet_fleet.sim_object.LoadedUrdf(body_id: int, mass: float | None, name: str | None, path: str)
Bases:
NamedTupleWhat both
from_urdffactories need out of a loaded URDF.- body_id: int
Alias for field number 0
- path: str
Alias for field number 3
- pybullet_fleet.sim_object.load_urdf_body(urdf_path, pose=None, *, mass=None, use_fixed_base=True, global_scaling=1.0, physics_client_id)
Load a URDF and settle the three things both factories need from it.
Shared by
SimObject.from_urdf()andAgent.from_urdf(), which otherwise differ only in what they wrap the body in.- Parameters:
urdf_path (
str) – Model name or path, resolved viaresolve_model().pose (
Optional[Pose]) – Where to place the base (default: origin).mass (
Optional[float]) –0.0overrides every link to mass 0 for kinematic use;Nonekeeps the URDF’s own values; anything else is taken as given.use_fixed_base (
bool) – If True, the base is fixed in space.global_scaling (
float) – Uniform scale factor.physics_client_id (
int) – Client to load into.
- Return type:
LoadedUrdf- Returns:
A
LoadedUrdf. The mass is totalled across every link rather than read from the base alone, becauseuse_fixed_basezeroes the base: a multi-link URDF would otherwise report mass 0 while its own links are still dynamic. The name is the URDF’s own robot name, for a caller with nothing better. The path is the resolved one, so a caller that needs it does not pay forresolve_model()twice – for an auto-discovered name that is an uncachedrobot_descriptionsscan, and a second resolution that disagreed would orphan the body just loaded.- Raises:
FileNotFoundError – If the URDF cannot be loaded.
- class pybullet_fleet.sim_object.SimObjectSpawnParams(visual_shape=None, collision_shape=None, initial_pose=<factory>, mass=0.0, pickable=True, name=None, visual_frame_pose=None, collision_frame_pose=None, collision_mode=CollisionMode.NORMAL_3D, user_data=<factory>, urdf_path=None)
Bases:
objectParameters for spawning a SimObject.
- visual_shape
Visual shape parameters (ShapeParams or None)
- collision_shape
Collision shape parameters (ShapeParams or None)
- urdf_path
Model name or path to a URDF file, as an alternative to
visual_shape/collision_shape. Mutually exclusive with them; the URDF wins if both are given.
- initial_pose
Initial Pose (position and orientation) in world coordinates (default: origin)
- mass
Object mass in kg (0.0 for static objects, >0 for dynamic)
- pickable
Whether this object can be picked by robots (default: True)
- name
Optional string name for human-readable identification (default: None). Duplicates allowed - multiple objects can share the same name. Use for debugging, logging, filtering (e.g., “LeftRobot”, “Pallet_A”). For unique identification, use object_id instead.
- user_data
Optional dictionary for custom metadata (default: empty dict)
Note
Managers calculate positions automatically and may override initial_pose.
Example:
# Box visual + sphere collision with name params = SimObjectSpawnParams( visual_shape=ShapeParams( shape_type="box", half_extents=[0.5, 0.3, 0.2], rgba_color=[1.0, 0.0, 0.0, 1.0] ), collision_shape=ShapeParams( shape_type="sphere", radius=0.3 ), initial_pose=Pose.from_xyz(0, 0, 1), mass=1.0, name="Pallet_A" # Human-readable name (duplicates allowed) ) obj = SimObject.from_params(params, sim_core) # Later: Use object_id for unique lookup retrieved_obj = sim_core.get_object_by_id(obj.object_id) # Or filter by name (may return multiple objects) pallets = [o for o in sim_core.objects if o.name == "Pallet_A"]
- visual_shape: ShapeParams | None = None
- collision_shape: ShapeParams | None = None
- initial_pose: Pose
- mass: float = 0.0
- pickable: bool = True
- visual_frame_pose: Pose | None = None
- collision_frame_pose: Pose | None = None
- collision_mode: CollisionMode = 'normal_3d'
- classmethod from_dict(config)
Create SimObjectSpawnParams from a configuration dictionary.
Accepts both programmatic dicts (with
ShapeParams/Poseobjects) and raw YAML dicts (withposelist,yaw, and shape sub-dicts).- YAML-style keys:
name (str, required): Object name. visual_shape (dict | ShapeParams, optional): Visual shape definition. collision_shape (dict | ShapeParams, optional): Collision shape. urdf_path (str, optional): URDF model name or path, instead of the shape definitions. pose (list):
[x, y, z]position. Alternative toinitial_pose. yaw (float): Yaw angle in radians (used withpose). initial_pose (Pose): Pose object (takes precedence overpose). mass (float): Default0.0(static). pickable (bool): DefaultTrue. collision_mode (str | CollisionMode): Default"normal_3d". user_data (dict): Default{}.
- Parameters:
- Return type:
SimObjectSpawnParams- Returns:
SimObjectSpawnParams instance.
- Raises:
ValueError – If
nameis missing.
- class pybullet_fleet.sim_object.SimObject(body_id, sim_core=None, pickable=True, mass=None, collision_mode=CollisionMode.NORMAL_3D, name=None, user_data=None)
Bases:
objectBase class for simulation objects (robots, pallets, obstacles). Supports attachment/detachment and kinematic teleportation.
- Object Identification:
- object_id: Unique integer ID assigned by sim_core (used for lookups and internal tracking).
This is the primary identifier for programmatic access.
- name: Optional string name for human-readable identification (used for debugging, logging, filtering).
Multiple objects can share the same name (duplicates allowed). Not guaranteed to be unique - use object_id for unique identification.
- Parameters:
- object_id
Unique integer ID (assigned by sim_core, use for lookups)
- name
Optional string name (duplicates allowed, use for debugging/filtering)
- body_id
PyBullet body ID
- mass
Object mass in kg
- pickable
Whether this object can be picked by robots
- collision_mode
Collision detection mode (NORMAL_3D, STATIC, DISABLED; NORMAL_2D is deprecated)
- user_data
Dictionary for custom metadata (default: empty dict)
- attached_objects: List[SimObject]
- update(dt)
Called every simulation step for objects with
_needs_update = True.Override in subclasses to implement per-step behavior (e.g. device state machines, animated objects).
- property events: EventBus
Per-entity EventBus. Created on first access (lazy).
Use in subclasses to hook into entity-specific events:
class WarehouseRobot(Agent): def __init__(self, ...): super().__init__(...) from pybullet_fleet.events import SimEvents self.events.on(SimEvents.COLLISION_STARTED, self._on_bump) self.events.on(SimEvents.ACTION_COMPLETED, self._on_task_done)
- set_name(name)
Set the object name and update the log prefix accordingly.
Use this instead of directly setting
self.nameto ensure the log prefix stays in sync.
- classmethod create_shared_shapes(visual_shape=None, collision_shape=None, physics_client_id=None)
Create shared visual and collision shapes for fast object spawning.
This method caches mesh shapes by their parameters and physics client, so multiple objects with identical mesh parameters on one client will reuse the same PyBullet shape IDs.
Note: Primitive shapes (box, sphere, cylinder) are NOT cached, as PyBullet handles them very efficiently and caching adds unnecessary overhead.
A mesh collision shape PyBullet cannot build (a Gazebo
.dae, say) is replaced by none, with a warning: the body is visual-only. That result is cached like a success, so every later call with the same parameters on the same client returns the visual-only pair at once, without another attempt or warning. Building the same mesh again would fail the same way and log once per spawn; to retry after fixing the file, start a new simulation (a reset or reconnect forgets the client’s shapes).- Parameters:
visual_shape (
Optional[ShapeParams]) – ShapeParams for visual geometrycollision_shape (
Optional[ShapeParams]) – ShapeParams for collision geometryphysics_client_id (
Optional[int]) – PyBullet physics client the shapes are created on; pass the simulation’ssim_core.client. Leaving it out is deprecated: it falls back to PyBullet’s default client (0) with aDeprecationWarning, which is the wrong client when more than one simulation runs in the process.
- Return type:
- Returns:
(visual_id, collision_id) tuple
Example:
visual_id, collision_id = create_shared_shapes( visual_shape=ShapeParams( shape_type="mesh", mesh_path="visual.obj", mesh_scale=[1.0, 1.0, 1.0], rgba_color=[0.8, 0.2, 0.2, 1.0] ), collision_shape=ShapeParams( shape_type="box", half_extents=[0.5, 0.3, 0.2] ), physics_client_id=sim_core.client )
- classmethod from_mesh(visual_shape=None, collision_shape=None, pose=None, mass=0.0, pickable=True, sim_core=None, collision_mode=CollisionMode.NORMAL_3D, name=None, user_data=None)
Create a SimObject with optional visual and collision shapes.
- Parameters:
visual_shape (
Optional[ShapeParams]) – ShapeParams for visual geometrycollision_shape (
Optional[ShapeParams]) – ShapeParams for collision geometrypose (
Pose) – Initial Pose (position and orientation, default: origin)mass (
float) – Object mass (0.0 for static)pickable (
bool) – Whether object can be picked by robotssim_core – Reference to simulation core
name (
Optional[str]) – Optional human-readable name (duplicates allowed)
- Return type:
SimObject- Returns:
SimObject instance
Example:
# Box visual + sphere collision obj = SimObject.from_mesh( visual_shape=ShapeParams( shape_type="box", half_extents=[0.5, 0.3, 0.2], rgba_color=[0.8, 0.2, 0.2, 1.0] ), collision_shape=ShapeParams( shape_type="sphere", radius=0.4 ), pose=Pose.from_xyz(0, 0, 1), mass=1.0, sim_core=sim_core )
- classmethod from_urdf(urdf_path, pose=None, sim_core=None, mass=0.0, pickable=False, collision_mode=CollisionMode.NORMAL_3D, use_fixed_base=True, global_scaling=1.0, name=None, user_data=None)
Load a URDF file and wrap the body in a SimObject.
The counterpart of
from_sdf()for single-body URDF models, and the non-agent counterpart ofAgent.from_urdf().Use this for static structure – walls, fixtures, shelving, fencing – that has a URDF but no behaviour. Such a body does not belong in the per-step update loop:
SimObject._needs_updateisFalse, sostep_once()skips it entirely, where anAgentis visited every step to walk an empty action queue, check joints it does not have and sweep plugins it does not own. Measured on a scene of 2376 fixed-base, jointless, controller-less bodies: 15.98 ms per step as Agents against 0.78 ms as SimObjects.Without this method, a URDF-defined static body has to be created as an Agent, because
urdf_pathexists only onAgentSpawnParams.- Parameters:
urdf_path (
str) – Model name (e.g."panda") or path to a URDF file. Resolved viaresolve_model().pose (
Optional[Pose]) – Initial Pose (default: origin).sim_core – Simulation core for registration.
mass (
Optional[float]) –0.0(the default) overrides every link to mass 0 for kinematic use;Nonekeeps the URDF’s own mass values.pickable (
bool) – Whether the object can be picked up (default: False, since scenery is the usual case).collision_mode (
CollisionMode) – Collision detection mode.use_fixed_base (
bool) – If True, the base is fixed in space.global_scaling (
float) – Uniform scale factor.name (
Optional[str]) – Human-readable name (default: the URDF’s own robot name).
- Return type:
SimObject- Returns:
SimObject instance.
- Raises:
FileNotFoundError – If the URDF cannot be loaded.
Example:
tile = SimObject.from_urdf( "frame_tile.urdf", pose=Pose.from_xyz(1.0, 2.0, 0.0), sim_core=sim, collision_mode=CollisionMode.STATIC, )
- classmethod from_sdf(sdf_path, sim_core=None, collision_mode=CollisionMode.NORMAL_3D, global_scaling=1.0, name_prefix=None, pickable=False, use_fixed_base=True)
Load an SDF file and wrap each body in a SimObject.
Uses PyBullet’s
p.loadSDF()to load the file and creates a SimObject for each body. All objects are auto-registered tosim_coreif provided.Note
PyBullet’s SDF loader does NOT support
<world>tags,<include>tags, ormodel://URIs. Use for individual SDF models (e.g., pybullet_data’s kiva_shelf, wsg50_gripper).- Parameters:
sdf_path (
str) – Path to SDF file (resolved via resolve_model())sim_core – Simulation core for registration
collision_mode (
CollisionMode) – Collision detection mode for all loaded objectsglobal_scaling (
float) – Uniform scale factorname_prefix (
Optional[str]) – Prefix for names (default: SDF filename stem)pickable (
bool) – Whether objects can be picked upuse_fixed_base (
bool) – If True, fix base (mass=0, kinematic)
- Return type:
List[SimObject]- Returns:
List of SimObject instances (one per body in the SDF)
Example:
shelves = SimObject.from_sdf( 'kiva_shelf/model.sdf', sim_core=sim ) for shelf in shelves: print(f'{shelf.name}: {shelf.get_pose()}')
- classmethod from_params(spawn_params, sim_core=None)
Create a SimObject from SimObjectSpawnParams.
- Parameters:
spawn_params (
SimObjectSpawnParams) – SimObjectSpawnParams instancesim_core – Reference to simulation core
- Return type:
SimObject- Returns:
SimObject instance
Example:
params = SimObjectSpawnParams( visual_shape=ShapeParams( shape_type="mesh", mesh_path="pallet.obj", mesh_scale=[0.5, 0.5, 0.5], rgba_color=[0.8, 0.6, 0.4, 1.0] ), collision_shape=ShapeParams( shape_type="box", half_extents=[0.5, 0.4, 0.1] ), initial_pose=Pose.from_xyz(0, 0, 0.1), mass=1.0 ) obj = SimObject.from_params(params, sim_core)
- classmethod from_dict(config, sim_core=None)
Create a SimObject from a raw config dict.
Combines
SimObjectSpawnParams.from_dict()andfrom_params()in a single call. Usescls._spawn_params_clsso subclasses automatically use their own SpawnParams.
- property is_static: bool
Whether this object is static (never moves).
Returns True if collision_mode is STATIC. This property is read-only. To change collision mode, use set_collision_mode() method.
- set_collision_mode(mode)
Change collision detection mode for this object.
This method updates the collision mode and notifies sim_core to update all collision-related caches (AABB, spatial grid, etc.).
- Parameters:
mode (
CollisionMode) – New CollisionMode- Return type:
Example:
# Change to static obj.set_collision_mode(CollisionMode.STATIC) # Disable collision obj.set_collision_mode(CollisionMode.DISABLED) # Enable collision again obj.set_collision_mode(CollisionMode.NORMAL_3D)
- get_pose()
Return current position and orientation as Pose object.
Performance optimization:
Kinematic objects (mass=0): Always returns cached pose since position only changes via set_pose(), which updates the cache.
Dynamic objects: Caches within the same simulation timestep to avoid redundant PyBullet API calls. Cache is invalidated when sim_time advances.
- Return type:
Pose
- set_pose(pose, preserve_velocity=True)
Set position and orientation from a Pose object.
Two-phase step behaviour (see
docs/design/two-phase-step/spec.md):Outside ``step_once()`` (immediate path): writes to PyBullet via
resetBasePositionAndOrientationand, for kinematic objects, refreshes the AABB + spatial grid immediately. Same behaviour as legacy callers.Inside ``step_once()`` (buffered path,
sim_core._in_step == True): updates only the internal pose cache and registers this object for the Phase 2 / Phase 3 batch flush.get_pose()returns the new pose immediately (cache is the source of truth), but PyBullet’s view, AABBs, and the spatial grid are not refreshed until the flush runs later in the samestep_once()invocation. A no-op set_pose (same pose as cache) is skipped entirely with zero PyBullet cost.
Attached children (base-link attachments) are propagated recursively through the same code path — so they take the buffered path inside the step and the immediate path outside it.
- Parameters:
pose (
Pose) – Pose object containing position and orientationpreserve_velocity (
bool) – If True, preserve current velocity after setting pose. If False, velocity is reset to zero (default behavior of PyBullet). For kinematic objects (mass=0), velocity preservation has no effect, so this is automatically set to False for performance.
- Return type:
- Returns:
True if the object moved (position or orientation changed), False otherwise
- set_pose_raw(position, orientation, preserve_velocity=True)
Set position and orientation from raw lists/tuples (no Pose allocation).
This is the fast path for internal use where position and orientation are already available as lists/tuples, avoiding Pose object creation overhead.
- attach_object(obj, parent_link_index=-1, relative_pose=None, joint_type=4, keep_world_pose=False)
Attach another SimObject to this object.
- Parameters:
obj (
SimObject) – Object to attachparent_link_index (
Union[int,str]) – Link index (int) or link name (str) to attach to. -1 or"base_link"for the base link.relative_pose (
Optional[Pose]) – Position and orientation offset in parent link’s frame as Pose object (default: None, which uses Pose(position=[0, 0, 0], orientation=[0, 0, 0, 1]))joint_type (
int) – PyBullet joint type (default: JOINT_FIXED)keep_world_pose (
bool) – If True, automatically computerelative_poseso that the child keeps its current world position and orientation. Cannot be combined with an explicitrelative_pose.
- Return type:
- Returns:
True if attachment successful, False otherwise
- Raises:
ValueError – If both
relative_poseandkeep_world_pose=Trueare specified.
Example:
# Attach to base link at 0.5m in front agent.attach_object(pallet, relative_pose=Pose.from_xyz(0.5, 0, 0)) # Keep the child where it currently is in the world agent.attach_object(box, parent_link_index=2, keep_world_pose=True) # Attach to specific link by name agent.attach_object(box, parent_link_index="end_effector")
- detach_object(obj, drop_pose=None, drop_relative_pose=None)
Detach an object from this object.
After detaching, the object can optionally be teleported:
drop_pose— absolute world pose.drop_relative_pose— offset applied to the object’s current (pre-detach) world pose (position and orientation are composed viamultiplyTransforms).Neither — the object stays at its current world position.
These two parameters are mutually exclusive.
- Parameters:
obj (
SimObject) – Object to detachdrop_pose (
Optional[Pose]) – Absolute world pose to teleport the object to after detaching. Mutually exclusive withdrop_relative_pose.drop_relative_pose (
Optional[Pose]) – Pose offset relative to the object’s current (pre-detach) world pose. Mutually exclusive withdrop_pose.
- Return type:
- Returns:
True if detachment successful, False otherwise
- Raises:
ValueError – If both
drop_poseanddrop_relative_poseare specified.
Example:
# Detach and leave in place agent.detach_object(pallet) # Detach and place at absolute world position agent.detach_object(pallet, drop_pose=Pose.from_xyz(10, 5, 0.1)) # Detach and offset from current position (e.g. lower by 0.5m) agent.detach_object(pallet, drop_relative_pose=Pose.from_xyz(0, 0, -0.5))
- get_attached_objects()
Return list of objects attached to this object.
- Return type:
List[SimObject]- Returns:
List of attached SimObject instances
- get_kinematic_attachment_state()
Describe a supported physics-off attachment without runtime body IDs.
- property pickable: bool
Whether another object may attach this one (pick it up).
- is_attached()
Check if this object is attached to another object.
- Return type:
- Returns:
True if attached to another object, False otherwise
- find_nearest_pickable(search_radius=1.0)
Find the nearest pickable, unattached SimObject within radius.
Convenience wrapper around
tools.find_nearest()that searches from this object’s current position with the standardpickable and not attachedfilter.Distance is measured from each object’s base origin, as before. The candidates come through the collision spatial hash, so the cost follows how crowded the search area is rather than how many objects the simulation holds; objects whose shape sits far off their origin are tracked separately and are still found.
- register_callback(callback, frequency=0.25)
Register a callback function to be executed periodically.
- execute_callbacks(current_time)
Execute registered callbacks based on their frequency.
pybullet_fleet.sim_plugin module
SimPlugin — lifecycle-managed simulation plugins.
Gazebo World Plugin equivalent for PyBulletFleet. Plugins receive
lifecycle callbacks and can access the full simulation API via
self.sim_core.
All lifecycle methods (on_init, on_step, on_reset,
on_shutdown) are optional no-ops by default. Override only the
methods your plugin needs.
Step-based plugin (called every sim step / at a fixed frequency):
class TrafficMonitor(SimPlugin):
def on_init(self) -> None:
self.counts = {}
def on_step(self, dt: float) -> None:
for a in self.sim_core.agents:
self.counts[a.name] = self.counts.get(a.name, 0) + 1
sim.register_plugin(TrafficMonitor, config={}, frequency=2.0)
Event-driven plugin (reacts to EventBus events, no per-step work):
class CollisionLogger(SimPlugin):
def on_init(self) -> None:
self.sim_core.events.on(
SimEvents.COLLISION_STARTED, self._on_collision
)
def _on_collision(self, obj_a, obj_b):
print(f"Collision: {obj_a.name} <-> {obj_b.name}")
sim.register_plugin(CollisionLogger)
YAML-driven usage:
plugins:
- class: "my_pkg.plugins.TrafficMonitor"
frequency: 2.0
config:
log_interval: 5.0
- pybullet_fleet.sim_plugin.register_sim_plugin(name, cls)
Register a sim plugin class under name.
- Return type:
- pybullet_fleet.sim_plugin.create_sim_plugin(name, sim_core, config=None, frequency=None, phase=None)
Create a sim plugin by registered name.
Convenience wrapper around
create_sim_plugin_from_entry().- Parameters:
name (
str) – Registry name (e.g."workcell").sim_core (
MultiRobotSimulationCore) – The simulation core instance.config (
Optional[Dict[str,Any]]) – Optional configuration dict.frequency (
Optional[float]) – Step frequency in Hz (None= every step).phase (
Optional[str]) – When in the stepon_step()runs ("pre_step","step"or"post_step");Nonekeeps the class’s own.
- Raises:
KeyError – If name is not registered.
- Return type:
SimPlugin
- pybullet_fleet.sim_plugin.create_sim_plugin_from_entry(entry, sim_core)
Create a sim plugin from a YAML-style config entry.
Supports two formats:
Registry shorthand:
{"type": "workcell", "config": {...}}Dotted path:
{"class": "my_pkg.MyPlugin", "config": {...}}
Both formats support an optional
frequencyfield (Hz) and an optionalphasefield (pre_step,steporpost_step; seeSimPlugin.step_phase).- Parameters:
- Return type:
SimPlugin- Returns:
Instantiated
SimPluginwithfrequencyandphaseset.- Raises:
KeyError – If
typeis not in the registry.TypeError – If
classdoes not resolve to a SimPlugin subclass.ValueError – If neither
typenorclassis present, orfrequencyorphaseis not valid.
- pybullet_fleet.sim_plugin.list_sim_plugins()
Return a copy of the sim plugin registry for inspection.
- class pybullet_fleet.sim_plugin.SimPlugin(sim_core)
Bases:
objectBase class for simulation plugins.
Plugins receive lifecycle callbacks and can access the full simulation API via
self.sim_core.All lifecycle hooks are optional no-ops by default — override only what your plugin needs. Step-based plugins override
on_step(); event-driven plugins subscribe toself.sim_core.eventsinon_init()and leaveon_stepalone.Lifecycle:
__init__(sim_core) # construction (typed kwargs in subclasses) on_init() # after world/robots are spawned on_step(dt) # each simulation step (frequency-controlled) on_reset() # when simulation is reset on_shutdown() # before PyBullet disconnects
Subclasses with a
_registry_nameclass attribute are auto-registered via_registry_nameclass attribute (e.g._registry_name = "workcell").- default_step_phase: CallbackPhase | str = 'step'
a
CallbackPhaseor its value. A subclass may set"pre_step"or"post_step";register_plugin(phase=...)and the YAMLphasefield override it per instance. Namedstep_phase, notphase, so that a plugin’s own state can keep that common name.- Type:
When in the step
on_step()runs, by default for this class
- property step_phase: CallbackPhase
When in the step
on_step()runs, as forregister_callback(phase=...).PRE_STEP: at the start of the step, before the clock advances and before anything moves (sim_timeis the previous state’s).STEP(default): after the objects have been updated, before the poses are written and the collision check.POST_STEP: at the end of the step, after the collision check.
Read when the plugin is registered: set it before, through
register_plugin(phase=...), the YAMLphasefield ordefault_step_phase. Setting it once the plugin is registered raisesRuntimeError.
- property frequency: float | None
Step frequency in Hz;
Nonecallson_step()every step.Changing it starts a fresh schedule on the new rate.
- classmethod from_config(sim_core, config=None)
Create from config dict, matching keys to
__init__parameters.Works like
Controller.from_config(): inspects the subclass__init__signature and passes matching keys as kwargs. The raw config dict is stored asconfig.
- on_init()
Called after world and robots are spawned.
Override to query
self.sim_core.agents, subscribe to events, or perform one-time setup. No-op by default.- Return type:
- on_step(dt)
Called each simulation step (subject to frequency control).
Override for step-based logic. Event-driven plugins can leave this as a no-op and react via
self.sim_core.eventsinstead.
- on_reset()
Called when the simulation is reset. Override to clear plugin state.
- Return type:
- on_shutdown()
Called before PyBullet disconnects. Override to release resources.
- Return type:
pybullet_fleet.states module
Transport-neutral fleet state snapshot types.
- class pybullet_fleet.states.RobotState2D(name, object_id, position, yaw, linear_velocity=(0.0, 0.0), angular_velocity=0.0, is_moving=False, battery_soc=None, is_charging=None)
Bases:
objectMinimal planar state for one robot.
- name: str
- object_id: int
- yaw: float
- angular_velocity: float = 0.0
- is_moving: bool = False
pybullet_fleet.tools module
- pybullet_fleet.tools.body_to_world_velocity_2d(vx_body, vy_body, yaw)
Rotate 2-D body-frame velocity to world frame using yaw only.
- Parameters:
- Return type:
- Returns:
(vx, vy)in world frame.
Example:
>>> body_to_world_velocity_2d(1.0, 0.0, yaw=math.pi / 2) (0.0, 1.0) # facing +Y, forward maps to +Y
- pybullet_fleet.tools.body_to_world_velocity_3d(vx_body, vy_body, vz_body, orientation)
Rotate 3-D body-frame velocity to world frame using full quaternion.
Uses the same quaternion convention as PyBullet:
(x, y, z, w).- Parameters:
- Return type:
- Returns:
(vx, vy, vz)in world frame.
Example:
>>> from scipy.spatial.transform import Rotation >>> q = Rotation.from_euler("z", 90, degrees=True).as_quat() # xyzw >>> body_to_world_velocity_3d(1.0, 0.0, 0.0, tuple(q)) (0.0, 1.0, 0.0)
- pybullet_fleet.tools.normalize_vector_param(value, param_name, dim=3)
Normalize a parameter to a numpy array of specified dimension.
This is a utility function for handling parameters that can be either: - A single float (applied to all dimensions) - A list of floats (one per dimension)
Commonly used for velocity/acceleration limits that can be uniform or per-axis.
- Parameters:
- Return type:
- Returns:
Numpy array of shape (dim,)
- Raises:
ValueError – If list length doesn’t match dimension
Example:
>>> normalize_vector_param(2.0, "max_vel", 3) array([2., 2., 2.]) >>> normalize_vector_param([1.0, 2.0, 3.0], "max_vel", 3) array([1., 2., 3.])
- pybullet_fleet.tools.resolve_link_index(body_id, link, physics_client_id=0)
Resolve link name to index.
- Parameters:
body_id (
int) – PyBullet body IDlink (
Union[int,str]) – Link index (int) or name (str). -1 or “base_link” for base link.physics_client_id (
int) – PyBullet client the body lives on. Pass the simulation’s client (sim_core.client) when more than one simulation runs in the process; the default is PyBullet’s first client.
- Return type:
- Returns:
Link index (int). Returns -1 if link is “base_link” or if link name not found.
Example:
>>> index = resolve_link_index(robot.body_id, "sensor_mast") >>> index = resolve_link_index(robot.body_id, 2) # Also accepts int >>> index = resolve_link_index(robot.body_id, "base_link") # Returns -1
- pybullet_fleet.tools.resolve_joint_index(body_id, joint, physics_client_id=0)
Resolve joint name to index.
- Parameters:
- Return type:
- Returns:
Joint index (int). Returns -1 if joint name not found.
Example:
>>> idx = resolve_joint_index(robot.body_id, "elbow_joint") >>> idx = resolve_joint_index(robot.body_id, 2)
- pybullet_fleet.tools.calculate_offset_pose(target_position, current_position, offset, keep_height=True)
Calculate pose at specified offset distance from target.
This unified function can be used for various offset calculations: - Approach poses (approach_offset): Position before reaching target - Pick poses (pick_offset): Position where pick operation occurs - Drop poses (drop_offset): Position where drop operation occurs
- Parameters:
- Return type:
Pose- Returns:
Pose object at the offset position, oriented to face the target
Example:
>>> # Approach pose (1.5m away from target) >>> approach = calculate_offset_pose([5, 0, 0.1], [0, 0, 0.3], offset=1.5) >>> >>> # Pick pose (0.3m away from target) >>> pick = calculate_offset_pose([5, 0, 0.1], [0, 0, 0.3], offset=0.3) >>> >>> # At target position (0m offset) >>> drop = calculate_offset_pose([5, 0, 0.1], [0, 0, 0.3], offset=0.0)
- pybullet_fleet.tools.world_to_grid(pos, spacing, offset=None)
Convert world coordinates to grid indices (always 3D), with offset.
- Parameters:
- Return type:
- Returns:
[ix, iy, iz] grid indices
- pybullet_fleet.tools.grid_to_world(grid, spacing, offset=None)
Convert grid indices to world coordinates (always 3D), with offset.
- Parameters:
- Return type:
- Returns:
[x, y, z] world coordinates
- pybullet_fleet.tools.world_to_grid_2d(pos, spacing)
2D wrapper for world_to_grid.
- pybullet_fleet.tools.grid_to_world_2d(grid, spacing)
2D wrapper for grid_to_world.
- pybullet_fleet.tools.grid_execution(grid_num=None, spacing=None, offset=None, func=None, args=None)
Calls the callback function func(grid_index, world_pos, **args) at each grid point.
- Parameters:
grid_num (
List[int]) – [x_num, y_num, z_num] number of grids in each axis (default: [1, 1, 1])spacing (
List[float]) – [spacing_x, spacing_y, spacing_z] grid spacing (default: [1.0, 1.0, 1.0])offset (
Optional[List[float]]) – [offset_x, offset_y, offset_z] offset (default: [0.0, 0.0, 0.0])func (
Optional[Callable]) – Callback function(grid_index: List[int], world_pos: List[float], **args) - grid_index: [ix, iy, iz] grid indices - world_pos: [x, y, z] world coordinatesargs (
Optional[Dict]) – Additional arguments to pass to the callback function
- Return type:
- pybullet_fleet.tools.find_nearest(objects, position, search_radius, predicate=None, exclude=None, use_2d=False)
Find the nearest object from position within search_radius.
A generic spatial nearest-neighbour query over objects that expose
get_pose().position. Filtering is done via an optional predicate callable and an exclude instance.- Parameters:
objects (
Iterable[Any]) – Iterable of objects withget_pose().positionattribute.position (
Sequence[float]) –[x, y, z]reference position in world frame.search_radius (
float) – Maximum search distance (metres).predicate (
Optional[Callable[[Any],bool]]) – Optional filter — called with each object, returnTrueto include. WhenNoneall objects are candidates.exclude (
Optional[Any]) – Single object instance to skip (typicallyself).use_2d (
bool) – WhenTrue, compare only XY distance (ignore Z). Useful for finding items on tables/shelves near a floor-level waypoint.
- Return type:
- Returns:
The nearest matching object, or
Noneif nothing found.
Example:
# Find nearest pickable, unattached object from a world position obj = find_nearest( sim_core.sim_objects, position=[5, 0, 0], search_radius=2.0, predicate=lambda o: o.pickable and not o.is_attached(), exclude=agent, )
pybullet_fleet.types module
types.py Common types and enumerations used across the package.
This module contains shared type definitions to avoid circular imports and provide a single source of truth for common types.
- class pybullet_fleet.types.MotionMode(value)
-
Motion mode for robot movement control.
- OMNIDIRECTIONAL
Robot can move in any direction without rotating first (holonomic)
- DIFFERENTIAL
Robot must rotate to face target, then move forward (non-holonomic)
- OMNIDIRECTIONAL = 'omnidirectional'
- DIFFERENTIAL = 'differential'
- class pybullet_fleet.types.PosePhase(value)
-
Phase for TPI pose control (shared by all kinematic controllers).
- ROTATE
Robot is rotating in place (slerp TPI)
- FORWARD
Robot is moving forward in a straight line (distance TPI)
- ROTATE = 'rotate'
- FORWARD = 'forward'
- class pybullet_fleet.types.MovementDirection(value)
-
Movement direction for robot motion.
- Note: This is only used in differential drive mode (MotionMode.DIFFERENTIAL).
In omnidirectional mode, the robot always faces the movement direction.
- FORWARD
Robot X+ axis points towards target, moves forward along path
- BACKWARD
Robot X- axis points towards target (X+ points away), moves along path (robot appears to move “backward” relative to its X+ orientation)
- AUTO
Automatically choose FORWARD or BACKWARD based on the angle between the robot’s current heading and the movement direction. Uses BACKWARD when the goal is more than 90° behind the robot.
- FORWARD = 'forward'
- BACKWARD = 'backward'
- AUTO = 'auto'
- class pybullet_fleet.types.ActionStatus(value)
Bases:
EnumAction execution status.
- NOT_STARTED
Action has not begun execution
- IN_PROGRESS
Action is currently executing
- COMPLETED
Action completed successfully
- FAILED
Action failed to complete
- CANCELLED
Action was cancelled before completion
- NOT_STARTED = 'not_started'
- IN_PROGRESS = 'in_progress'
- COMPLETED = 'completed'
- FAILED = 'failed'
- CANCELLED = 'cancelled'
- class pybullet_fleet.types.SpatialHashCellSizeMode(value)
Bases:
EnumCollision detection spatial hash cell size calculation mode.
Determines how the spatial hash grid cell size is calculated for efficient broad-phase collision detection.
- CONSTANT
Fixed cell size provided by user (fastest, requires manual tuning)
- AUTO_ADAPTIVE
Recalculate on object add/remove (adaptive, some overhead)
- AUTO_INITIAL
Calculate once at simulation start (default, balanced performance)
- CONSTANT = 'constant'
- AUTO_ADAPTIVE = 'auto_adaptive'
- AUTO_INITIAL = 'auto_initial'
- class pybullet_fleet.types.DoorState(value)
-
Door operational state.
- CLOSED
Door is fully closed.
- OPENING
Door is transitioning toward the open position.
- OPEN
Door is fully open.
- CLOSING
Door is transitioning toward the closed position.
- CLOSED = 'closed'
- OPENING = 'opening'
- OPEN = 'open'
- CLOSING = 'closing'
- class pybullet_fleet.types.CallbackPhase(value)
-
When in a simulation step a
register_callback()callback or a plugin’son_step()runs.Each value is the name of the step event it subscribes to on
sim.events(SimEvents.PRE_STEP,SimEvents.STEP,SimEvents.POST_STEP); callbacks run after that event’s handlers, and plugins after the callbacks.- PRE_STEP
At the start of the step, right after the
pre_stepevent’s handlers and before the clock advances:sim_timeis still the previous state’s time, and nothing has moved yet. Use it to apply commands that this step should act on.
- STEP
After the objects have been updated, before their new poses are written to PyBullet and before the collision check.
- POST_STEP
At the end of the step, right after the
post_stepevent, once the poses are written and the step’s collision check has run.
- PRE_STEP = 'pre_step'
- STEP = 'step'
- POST_STEP = 'post_step'
- class pybullet_fleet.types.GoalReplacement(value)
-
What a moving agent does with a new goal or path it cannot reach from its current motion.
A new path set while the agent is moving continues that motion when the straight-line trajectory to its first waypoint exists from the current velocity within the configured limits: the goal lies on the line of motion, ahead or behind, and the agent can still stop at it. Otherwise – a goal inside the braking distance, off the line of motion, or one that needs a turn in place – this setting decides.
WAIT_COMPLETEalone also holds a path the agent could continue into: the current path has priority. Only the latest held path is kept; dropping one is logged.- BRAKE
Accept the path; brake along the current motion at the configured deceleration, then start the path from rest.
- REJECT
Refuse the path (
set_pathreturnsFalse); the current motion runs on. The refusal is temporary: the same path is taken once the agent is at rest.
- WAIT_COMPLETE
Accept every path set while a path is in progress; finish the current one (reach its goal and stop), then start the new path from rest. With no path in progress (a velocity command) it brakes like
BRAKE.
- IMMEDIATE
Accept the path and start it from rest at once, dropping the current velocity in a single step – the only mode that does not respect the configured deceleration.
- BRAKE = 'brake'
- REJECT = 'reject'
- WAIT_COMPLETE = 'wait_complete'
- IMMEDIATE = 'immediate'
- class pybullet_fleet.types.ControllerMode(value)
-
Internal mode for KinematicController state machine.
- IDLE
No active command — zero velocity, no pose target.
- VELOCITY
Processing cmd_vel input (body-frame velocity).
- POSE
Processing goal_pose / path via TPI trajectory.
- IDLE = 'idle'
- VELOCITY = 'velocity'
- POSE = 'pose'
- class pybullet_fleet.types.CollisionMode(value)
Bases:
EnumCollision detection mode for individual objects.
Determines how an object participates in collision detection: - Clearance on the z axis (NORMAL_2D vs NORMAL_3D) - Movement type (static vs dynamic) - Collision detection enablement
- NORMAL_3D
Normal collision detection (default) - A pair is a candidate when its AABBs are within the collision clearance on every axis - For dynamic/kinematic objects
- NORMAL_2D
Deprecated, use NORMAL_3D. As NORMAL_3D, without the clearance on the z axis (z is not ignored) - A pair involving one needs real z overlap; x and y get the clearance as for NORMAL_3D - Differs from NORMAL_3D only with a non-zero clearance (CLOSEST_POINTS / HYBRID) - Setting it emits a FutureWarning; it still works and will be removed in a future release
- STATIC
Static object mode (never moves, but has collision) - Registered in collision system during spawn - Never updates AABB/spatial grid (performance optimization) - Examples: walls, shelves, structures
- DISABLED
Collision detection completely disabled (ghost object) - No AABB calculation - No spatial grid registration - No collision checking - PyBullet physics collision also disabled - Examples: decorative objects, visual markers, UI elements
- Note: The actual collision filtering (e.g., ignore_static) is done at
core_simulation level, not in this mode definition.
Example
# Normal 3D robot robot = SimObject(…, collision_mode=CollisionMode.NORMAL_3D)
# Static structure wall = SimObject(…, collision_mode=CollisionMode.STATIC)
# Ghost object (no collision) decoration = SimObject(…, collision_mode=CollisionMode.DISABLED)
- NORMAL_3D = 'normal_3d'
- NORMAL_2D = 'normal_2d'
- STATIC = 'static'
- DISABLED = 'disabled'
- class pybullet_fleet.types.CollisionDetectionMethod(value)
Bases:
EnumCollision detection method for narrow-phase collision checking.
Determines which PyBullet API to use for detecting actual contacts between objects after broad-phase filtering (AABB + spatial hashing).
Design Philosophy (from design document): - Physics OFF (kinematics): Use CLOSEST_POINTS for safety margin detection - Physics ON (physics): Use CONTACT_POINTS for actual contact logging
- CLOSEST_POINTS
Use getClosestPoints() - distance-based, kinematics-safe (RECOMMENDED DEFAULT) Best for: kinematics motion, safety clearance, collision avoidance Works with: Physics ON/OFF, stable with resetBasePositionAndOrientation
- CONTACT_POINTS
Use getContactPoints() - physics contact manifold (PHYSICS MODE). Best for physics simulation, actual contact logging, and debugging. Requires an explicit collision-detection pass; stepSimulation() is the normal physics path. Cache/solver-dependent for kinematic pairs.
- HYBRID
Use getContactPoints when either object uses physics; use getClosestPoints only for kinematic-kinematic pairs (ADVANCED). Best for mixed physics/kinematics with different detection needs.
- Recommended defaults:
physics_enabled=False → CLOSEST_POINTS (default)
physics_enabled=True → CONTACT_POINTS or HYBRID
- CLOSEST_POINTS = 'closest_points'
- CONTACT_POINTS = 'contact_points'
- HYBRID = 'hybrid'
pybullet_fleet.world_loader module
Backward-compatibility shim — all functions moved to sdf_loader.
- pybullet_fleet.world_loader.load_mesh_directory(mesh_dir, sim_core=None, collision_mode=CollisionMode.NORMAL_3D, mesh_scale=None, rgba_color=None, pattern='*.obj')
Load mesh files from a directory as static SimObjects.
Scans
mesh_dirfor files matchingpatternand creates a static SimObject for each one. Object names are derived from filenames (stem).Originally written for rmf_demos environments where
rmf_building_map_toolsgenerates OBJ meshes with world-space vertices, but works with any directory of mesh files.- Parameters:
mesh_dir (
str) – Directory containing mesh filessim_core – Simulation core for registration
collision_mode (
CollisionMode) – Collision mode for environment objectsmesh_scale (
Optional[List[float]]) – Optional scale override [sx, sy, sz] (default: [1,1,1])rgba_color (
Optional[List[float]]) – Optional color override [r,g,b,a] (default: grey)pattern (
str) – Glob pattern for mesh files (default:'*.obj')
- Return type:
List[SimObject]- Returns:
List of SimObject instances (one per mesh file)
- Raises:
FileNotFoundError – If
mesh_dirdoes not exist.
- pybullet_fleet.world_loader.load_rmf_world(*args, **kwargs)
Backward-compatible alias for
load_mesh_directory().Deprecated since version Use:
load_mesh_directory()instead.- Return type:
List[SimObject]
Module contents
pybullet_fleet package General-purpose PyBullet simulation library for multi-robot fleets
- class pybullet_fleet.ActionStatus(value)
Bases:
EnumAction execution status.
- NOT_STARTED
Action has not begun execution
- IN_PROGRESS
Action is currently executing
- COMPLETED
Action completed successfully
- FAILED
Action failed to complete
- CANCELLED
Action was cancelled before completion
- NOT_STARTED = 'not_started'
- IN_PROGRESS = 'in_progress'
- COMPLETED = 'completed'
- FAILED = 'failed'
- CANCELLED = 'cancelled'
- class pybullet_fleet.CallbackPhase(value)
-
When in a simulation step a
register_callback()callback or a plugin’son_step()runs.Each value is the name of the step event it subscribes to on
sim.events(SimEvents.PRE_STEP,SimEvents.STEP,SimEvents.POST_STEP); callbacks run after that event’s handlers, and plugins after the callbacks.- PRE_STEP
At the start of the step, right after the
pre_stepevent’s handlers and before the clock advances:sim_timeis still the previous state’s time, and nothing has moved yet. Use it to apply commands that this step should act on.
- STEP
After the objects have been updated, before their new poses are written to PyBullet and before the collision check.
- POST_STEP
At the end of the step, right after the
post_stepevent, once the poses are written and the step’s collision check has run.
- PRE_STEP = 'pre_step'
- STEP = 'step'
- POST_STEP = 'post_step'
- class pybullet_fleet.GoalReplacement(value)
-
What a moving agent does with a new goal or path it cannot reach from its current motion.
A new path set while the agent is moving continues that motion when the straight-line trajectory to its first waypoint exists from the current velocity within the configured limits: the goal lies on the line of motion, ahead or behind, and the agent can still stop at it. Otherwise – a goal inside the braking distance, off the line of motion, or one that needs a turn in place – this setting decides.
WAIT_COMPLETEalone also holds a path the agent could continue into: the current path has priority. Only the latest held path is kept; dropping one is logged.- BRAKE
Accept the path; brake along the current motion at the configured deceleration, then start the path from rest.
- REJECT
Refuse the path (
set_pathreturnsFalse); the current motion runs on. The refusal is temporary: the same path is taken once the agent is at rest.
- WAIT_COMPLETE
Accept every path set while a path is in progress; finish the current one (reach its goal and stop), then start the new path from rest. With no path in progress (a velocity command) it brakes like
BRAKE.
- IMMEDIATE
Accept the path and start it from rest at once, dropping the current velocity in a single step – the only mode that does not respect the configured deceleration.
- BRAKE = 'brake'
- REJECT = 'reject'
- WAIT_COMPLETE = 'wait_complete'
- IMMEDIATE = 'immediate'
- class pybullet_fleet.MotionMode(value)
-
Motion mode for robot movement control.
- OMNIDIRECTIONAL
Robot can move in any direction without rotating first (holonomic)
- DIFFERENTIAL
Robot must rotate to face target, then move forward (non-holonomic)
- OMNIDIRECTIONAL = 'omnidirectional'
- DIFFERENTIAL = 'differential'
- class pybullet_fleet.MovementDirection(value)
-
Movement direction for robot motion.
- Note: This is only used in differential drive mode (MotionMode.DIFFERENTIAL).
In omnidirectional mode, the robot always faces the movement direction.
- FORWARD
Robot X+ axis points towards target, moves forward along path
- BACKWARD
Robot X- axis points towards target (X+ points away), moves along path (robot appears to move “backward” relative to its X+ orientation)
- AUTO
Automatically choose FORWARD or BACKWARD based on the angle between the robot’s current heading and the movement direction. Uses BACKWARD when the goal is more than 90° behind the robot.
- FORWARD = 'forward'
- BACKWARD = 'backward'
- AUTO = 'auto'
- class pybullet_fleet.PathRequest(path, final_orientation_align=True, direction=None, auto_approach=True, _token=<factory>)
Bases:
objectWaypoints to follow and how to follow them.
- Parameters:
path (
Sequence[Pose]) – The waypoints, in order (a sequence ofPose; stored as a tuple).final_orientation_align (
bool) – Rotate to the last waypoint’s orientation after reaching its position.direction (
Optional[MovementDirection]) – Movement direction (differential drive only): aMovementDirectionor its string value;Noneuses the controller’sdefault_direction.auto_approach (
bool) – LetAgent.request_pathput the current pose in front of the path when the agent is at rest and far from its first waypoint. Controllers ignore it.
A copy made with
dataclasses.replace()is the same request (seesame_request()); to send a new request, build a new one. Frozen, but not hashable: thePosewaypoints are mutable. Identity does not surviveto_record()/from_record(), so a request restored from a checkpoint is a new one.- path: Sequence[Pose]
- final_orientation_align: bool = True
- direction: MovementDirection | None = None
- auto_approach: bool = True
- same_request(other)
Whether
otheris this request or a copy of it made on its way to a controller.- Return type:
- to_record()
Plain-data form for checkpoints (without
auto_approach: a held request has had its approach applied already).- Return type:
- classmethod from_record(record)
Inverse of
to_record().- Return type:
PathRequest
- class pybullet_fleet.PathRequestState(value)
Bases:
EnumWhat became of a
PathRequestsent to a controller.- ACTIVE = 'active'
Being followed.
- PENDING = 'pending'
Accepted and held, to start once the agent stops or finishes its path.
- FINISHED = 'finished'
Followed to its end; the agent came to rest there.
- GONE = 'gone'
replaced by another request, dropped from the hold, stopped, braked, cancelled or never sent.
- Type:
Not (or no longer) the controller’s
- UNKNOWN = 'unknown'
The controller does not track requests (a custom controller written against
set_path).
- class pybullet_fleet.PosePhase(value)
-
Phase for TPI pose control (shared by all kinematic controllers).
- ROTATE
Robot is rotating in place (slerp TPI)
- FORWARD
Robot is moving forward in a straight line (distance TPI)
- ROTATE = 'rotate'
- FORWARD = 'forward'
- class pybullet_fleet.Pose(position, orientation=<factory>)
Bases:
objectPosition and orientation representation for any object in the simulation. Compatible with ROS2 geometry_msgs/Pose and PyBullet’s (position, orientation) tuples.
Supports both quaternion and Euler angle representations.
- position
[x, y, z] in world coordinates
- orientation
[x, y, z, w] quaternion (defaults to no rotation)
- property x: float
X coordinate.
- property y: float
Y coordinate.
- property z: float
Z coordinate.
- property roll: float
Roll angle in radians (rotation around x-axis).
- property pitch: float
Pitch angle in radians (rotation around y-axis).
- property yaw: float
Yaw angle in radians (rotation around z-axis).
- classmethod from_xyz(x, y, z)
Create Pose from x, y, z coordinates.
- classmethod from_euler(x, y, z, roll=0.0, pitch=0.0, yaw=0.0)
Create Pose from position and Euler angles.
- classmethod from_pybullet(position, orientation)
Create Pose from PyBullet position and orientation tuples.
- as_position_orientation()
Return (position, orientation) tuple for PyBullet.
- as_tuple()
Return (position, orientation) tuple. Alias for as_position_orientation() for convenience.
- as_euler()
Return orientation as Euler angles (roll, pitch, yaw).
- class pybullet_fleet.Path(waypoints)
Bases:
objectRepresents a path as a sequence of waypoints (Poses).
- waypoints
List of Pose objects representing the path
Example:
# Create from Pose list (recommended) path = Path([ Pose.from_xyz(0, 0, 0), Pose.from_xyz(1, 0, 0), Pose.from_xyz(1, 1, 0) ]) # Create from positions path = Path.from_positions([[0, 0, 0], [1, 0, 0], [1, 1, 0]]) # Create predefined shapes circle = Path.create_circle(center=[0, 0], radius=1.5) square = Path.create_square(center=[0, 0], side_length=2.0)
- waypoints: List[Pose]
- classmethod from_positions(positions, orientation=None)
Create Path from list of positions with optional shared orientation.
- Parameters:
- Return type:
Path- Returns:
Path instance
Example:
path = Path.from_positions([ [0, 0, 0], [1, 0, 0], [1, 1, 0] ])
- classmethod create_rectangle(center, width, height, rpy=[0.0, 0.0, 0.0])
Create a rectangular path in 3D.
- Parameters:
center (
List[float]) – [x, y, z] center position in world coordinateswidth (
float) – Width of rectangle (X direction in local frame)height (
float) – Height of rectangle (Y direction in local frame)rpy (
List[float]) – [roll, pitch, yaw] in radians. Defaults to [0, 0, 0]. When non-zero, the Z+ axis of the robot will be perpendicular to the rectangle plane.
- Return type:
Path- Returns:
Path instance with waypoints at rectangle corners
Example:
rect = Path.create_rectangle(center=[0, 0, 1], width=3.0, height=2.0) tilted_rect = Path.create_rectangle(center=[0, 0, 1], width=3.0, height=2.0, rpy=[0.1, 0.2, 0])
- classmethod create_square(center, side_length, rpy=[0.0, 0.0, 0.0])
Create a square path in 3D.
- Parameters:
- Return type:
Path- Returns:
Path instance with waypoints at square corners
Example:
square = Path.create_square(center=[0, 0, 0], side_length=2.0) tilted_square = Path.create_square(center=[0, 0, 1], side_length=2.0, rpy=[0.1, 0.2, 0])
Note:
This is a wrapper for create_rectangle with width == height.
- classmethod create_ellipse(center, radius_x, radius_y, num_points=16, rpy=[0.0, 0.0, 0.0], start_angle=0.0, end_angle=6.283185307179586)
Create an elliptical path in 3D.
- Parameters:
center (
List[float]) – [x, y, z] center position in world coordinatesradius_x (
float) – Radius along X axis in local frameradius_y (
float) – Radius along Y axis in local framenum_points (
int) – Number of waypoints along the arcrpy (
List[float]) – [roll, pitch, yaw] in radians. Defaults to [0, 0, 0].start_angle (
float) – Start angle [rad] in the local XY-planeend_angle (
float) – End angle [rad] in the local XY-plane
- Return type:
Path- Returns:
Path instance with waypoints along ellipse
Example:
ellipse = Path.create_ellipse(center=[0, 0, 0], radius_x=2.0, radius_y=1.0) tilted_ellipse = Path.create_ellipse(center=[0, 0, 1], radius_x=2.0, radius_y=1.0, rpy=[0, 0.3, 0])
- classmethod create_circle(center, radius, num_points=16, rpy=[0.0, 0.0, 0.0], start_angle=0.0, end_angle=6.283185307179586)
Create a circular path in 3D.
- Parameters:
center (
List[float]) – [x, y, z] center position in world coordinatesradius (
float) – Circle radiusnum_points (
int) – Number of waypoints along the arcrpy (
List[float]) – [roll, pitch, yaw] in radians. Defaults to [0, 0, 0].start_angle (
float) – Start angle [rad] in the local XY-planeend_angle (
float) – End angle [rad] in the local XY-plane
- Return type:
Path- Returns:
Path instance with waypoints along circle
Example:
circle = Path.create_circle(center=[0, 0, 0], radius=1.5) arc = Path.create_circle(center=[0, 0, 0], radius=1.5, start_angle=0, end_angle=np.pi)
Note:
This is a wrapper for create_ellipse with radius_x == radius_y.
- append(other)
Append waypoints from another path in-place.
Note:
This mutates the current Path. For a non-mutating version, use `combined = path1 + path2`.
- Return type:
- classmethod from_paths(paths)
Create a single Path by concatenating multiple paths.
Example:
circle_arc = Path.create_circle(center=[0, 0, 0.5], radius=2.0, num_points=16, start_angle=0.0, end_angle=np.pi/2) line = Path.from_positions([[1, 1, 0.5], [3, 1, 0.5]]) full = Path.from_paths([circle_arc, line])
- Return type:
Path
- get_total_distance()
Calculate total path length.
- Return type:
- Returns:
Total distance in meters
- visualize(show_lines=True, line_color=None, line_width=2.0, show_waypoints=False, show_axes=False, axis_length=0.3, show_points=False, point_size=0.05, lifetime=0.0)
Visualize path with lines and optional waypoint markers.
- Parameters:
show_lines (
bool) – If True, draw lines connecting waypointsline_color (
List[float]) – RGB color for path lines [r, g, b] (0-1 range), None for defaultline_width (
float) – Width of path linesshow_waypoints (
bool) – If True, show waypoint coordinate axes and pointsshow_axes (
bool) – If True, draw X, Y, Z axes at each waypointaxis_length (
float) – Length of coordinate axes in metersshow_points (
bool) – If True, draw spheres at waypoint positionspoint_size (
float) – Radius of waypoint spheres in meterslifetime (
float) – Debug line lifetime (0 = permanent until reset)
- Return type:
- Returns:
List of debug item IDs (for later removal if needed)
Example:
# Just show path lines path = Path.create_circle(center=[0, 0, 0.5], radius=2.0) path.visualize(line_color=[1, 0, 0]) # Show path with waypoint orientations path.visualize(show_waypoints=True, show_axes=True)
- visualize_waypoints(show_axes=True, axis_length=0.3, show_points=True, point_size=0.05, lifetime=0.0)
Visualize waypoints with coordinate axes for debugging.
- Parameters:
show_axes (
bool) – If True, draw X, Y, Z axes at each waypointaxis_length (
float) – Length of coordinate axes in metersshow_points (
bool) – If True, draw spheres at waypoint positionspoint_size (
float) – Radius of waypoint spheres in meterslifetime (
float) – Debug line lifetime (0 = permanent until reset)
- Return type:
- Returns:
List of debug item IDs (for later removal if needed)
Example:
path = Path.create_square(center=[0, 0, 1], side_length=2.0, rpy=[0.1, 0.2, 0]) debug_ids = path.visualize_waypoints(axis_length=0.5)
- class pybullet_fleet.RobotState2D(name, object_id, position, yaw, linear_velocity=(0.0, 0.0), angular_velocity=0.0, is_moving=False, battery_soc=None, is_charging=None)
Bases:
objectMinimal planar state for one robot.
- name: str
- object_id: int
- yaw: float
- angular_velocity: float = 0.0
- is_moving: bool = False
- class pybullet_fleet.RobotState3D(name, object_id, position, orientation, linear_velocity=(0.0, 0.0, 0.0), angular_velocity=(0.0, 0.0, 0.0), is_moving=False, battery_soc=None, is_charging=None)
Bases:
objectMinimal 3D state for one robot.
- name: str
- object_id: int
- is_moving: bool = False
- class pybullet_fleet.RobotGoalCommand2D(name, position, yaw=0.0, z=None, command_id=None)
Bases:
objectPlanar navigation command for one robot.
zis the goal’s height.None(the default) keeps the robot’s present height, so a planar goal never moves it up or down; a goal at another height is a 3D move, which a moving robot can only continue into along its line of motion (seeAgent.set_path()).- name: str
- yaw: float = 0.0
- to_pose(current_z=0.0)
Convert this command to a simulation
Pose.current_zis the robot’s present height, used whenzisNone.- Return type:
Pose
- class pybullet_fleet.RobotGoalCommand3D(name, position, orientation=(0.0, 0.0, 0.0, 1.0), command_id=None)
Bases:
object3D navigation command for one robot.
- name: str
- to_pose(current_z=0.0)
Convert this command to a simulation
Pose.current_zis accepted for symmetry withRobotGoalCommand2D.to_pose()and unused: a 3D goal names its height.- Return type:
Pose
- class pybullet_fleet.RobotAttachCommand(name, attach, object_name='', parent_link='base_link', offset=<factory>, search_radius=0.5)
Bases:
objectAttach or detach a simulation object for one robot.
- name: str
- attach: bool
- object_name: str = ''
- parent_link: str = 'base_link'
- offset: Pose
- search_radius: float = 0.5
- class pybullet_fleet.RobotActionCommand(name, action_type, action_params_json='', command_id=None)
Bases:
objectGeneric PyBulletFleet action command for one robot.
- name: str
- action_type: str
- action_params_json: str = ''
- class pybullet_fleet.RobotJointPositionsCommand(name, positions)
Bases:
objectOrdered joint target command for one robot.
- name: str
- class pybullet_fleet.RobotNamedJointPositionsCommand(name, positions)
Bases:
objectNamed joint target command for one robot.
- name: str
- class pybullet_fleet.CommandAck(command_id, source, sim_time, accepted_names=<factory>, rejected=<factory>)
Bases:
objectResult of accepting or rejecting a fleet command.
- command_id: str
- source: str
- sim_time: float
- property ok: bool
Whether at least one target was accepted and none were rejected.
- class pybullet_fleet.CommandEvent(command_id, source, sim_time, command_type, target_names, accepted_names, rejected=<factory>)
Bases:
objectCommand trace event emitted before mutating simulation state.
- command_id: str
- source: str
- sim_time: float
- command_type: str
- class pybullet_fleet.FleetStateProvider(sim_core)
Bases:
objectGenerate deterministic fleet state values from a simulation core.
- get_states()
Return 3D states for all agents.
get_states()uses the more general 3D representation by default. Callget_states_2d()when a planar transport wants a smaller model.- Return type:
list[RobotState3D]
- get_states_2d(names=None)
Return planar states for all or selected agents.
- Return type:
list[RobotState2D]
- get_states_3d(names=None)
Return 3D states for all or selected agents.
- Return type:
list[RobotState3D]
- class pybullet_fleet.FleetCommandDispatcher(sim_core, *, allowed_names=None, retain_command_events=True)
Bases:
objectValidate and apply fleet commands against a simulation core.
- refresh_name_index()
Rebuild the robot-name index used for command dispatch.
- Return type:
- navigate(goals, *, source='python', command_id=None)
Apply one or more navigation goals by robot name.
A target robot provides
get_pose(),set_goal_pose()andpath_rejection(), asAgentdoes.- Return type:
CommandAck
- joint_command(commands, *, source='python', command_id=None)
Apply one or more joint target commands by robot name.
- Return type:
CommandAck
- stop(names, *, source='python', command_id=None)
Stop one or more robots by name.
- Return type:
CommandAck
- attach(commands, *, source='python', command_id=None)
Attach or detach objects for one or more robots by name.
- Return type:
CommandAck
- execute_action(commands, *, source='python', command_id=None)
Queue generic PyBulletFleet actions for one or more robots.
- Return type:
CommandAck
- class pybullet_fleet.MultiRobotSimulationCore(params, collision_color=None)
Bases:
object- classmethod from_yaml(yaml_path='config.yaml')
Create and initialise a simulation from a YAML config file.
Supports two YAML layouts:
Nested (recommended) —
simulation,world, andentitiessections:simulation: gui: true physics: false world: world_file: "/path/to/office.world" entities: - name: robot0 urdf_path: "robots/mobile_robot.urdf" pose: [0, 0, 0.05] - type: sim_object name: box0 visual_shape: shape_type: box half_extents: [0.3, 0.3, 0.1] pose: [3, 0, 0.1]
Flat (legacy) — all keys at the top level:
gui: true physics: false timestep: 0.1
Custom entity types — register classes via dotted Python paths so
type:dispatch works without any Python code:entity_classes: forklift: "my_ros_pkg.entities.ForkliftAgent" conveyor: "warehouse_sim.conveyor.ConveyorObject" entities: - type: forklift urdf_path: robots/forklift.urdf pose: [0, 0, 0.05]
When a
worldsection is present andenable_flooris not explicitly set in the simulation config, the floor plane is automatically disabled (the world geometry replaces it).- Parameters:
yaml_path (
str) – Path to YAML config file.- Return type:
MultiRobotSimulationCore- Returns:
Fully initialised
MultiRobotSimulationCorewith world loaded and robots spawned (if configured).
- classmethod from_dict(config)
Create MultiRobotSimulationCore from a configuration dictionary.
Supports both flat simulation-params dicts and nested dicts with
simulation,world, andentitiessections. When nested keys are present they are processed the same way asfrom_yaml().An optional
entity_classessection maps names to dotted Python paths for dynamic class registration (seefrom_yaml()for details).
- events: EventBus
- setup_monitor()
- Return type:
- property sim_objects: List[SimObject]
List of all simulation objects (Agent, SimObject, etc.).
- property last_monitor_frame: MonitorFrame | None
Return the most recently published toolkit-neutral monitor frame.
- property gui_follow_enabled: bool
Return whether the viewport follows the selected entity.
- enqueue_gui_command(command)
Queue a monitor request for the next simulation-step boundary.
This method is safe to call from a tkinter callback. It deliberately does not mutate simulation state or make PyBullet calls on the caller’s thread. Returns
Falseonly when the bounded queue is full.- Return type:
- request_single_step(source='api')
Request one step while paused, without re-entering
step_once().The request is consumed by the outer
step_onceinvocation. A request made while running is ignored because normal stepping already advances the simulation.- Return type:
- property agents: List[Agent]
List of Agent instances.
- find_objects_by_name(name)
Return all registered simulation objects whose name matches.
Names are not required to be unique. The result follows registration order and includes Agents, which are also SimObjects.
- Return type:
List[SimObject]
- find_agents_by_name(name)
Return matching Agents in registration order.
- Return type:
List[Agent]
- get_unique_object_by_name(name)
Return one named object, or raise if absent or ambiguous.
- Return type:
SimObject
- get_unique_agent_by_name(name)
Return one named Agent, or raise if absent or ambiguous.
- Return type:
Agent
- property params: SimulationParams
Simulation parameters.
- property step_count: int
Current simulation step count.
- property sim_time: float
Simulated time of the state you see (read-only).
Outside a step it is the completed step’s time, the same as
get_completed_step_boundary(). Insidestep_once()the clock advances right after thepre_stepevent, so from the object update on – callbacks, plugins, the collision check,post_step– it is the time of the state that step computes. Apre_stepsubscriber sees the previous step’s time. To move the clock (resuming from a checkpoint), userestore_completed_step_boundary().
- get_completed_step_boundary()
Return the completed step and canonical elapsed time outside a step.
- configure_state_recording(*, profile, output=None, checkpoint_every_steps=1, records=())
Record a supported execution profile during ordinary simulation runs.
State recording is distinct from camera/video recording. The profile declares what can be restored; named records capture caller-owned data at the same completed boundary. Unsupported live state fails at capture.
- Return type:
- restore_completed_step_boundary(step, elapsed_time)
Restore the clock of a fresh, initialized fixed-step simulation.
- Return type:
- property collision_count: int
Total number of collisions detected.
- property enable_memory_profiling: bool
Whether memory profiling is enabled.
- property last_profiling: Mapping[str, Any] | None
Timing values from the most recently completed profiled step.
The mapping has the same timing fields (in milliseconds) as
step_once()withreturn_profiling=True, including custom fields added byrecord_profiling(). It is updated only when timing is measured: either time profiling is enabled or that step was called withreturn_profiling=True. Otherwise it isNone.Simulation plugins and callbacks execute before the current step’s later phases have completed, so they observe the previous completed step through this property. The returned mapping is read-only.
- register_plugin(plugin_or_cls, config=None, frequency=None, phase=None)
Register a simulation plugin.
- Parameters:
plugin_or_cls (
Union[TypeVar(_SimPluginT, bound= SimPlugin),Type[TypeVar(_SimPluginT, bound= SimPlugin)]]) – Either aSimPlugininstance or aSimPluginsubclass (will be instantiated).config (
Optional[Dict[str,Any]]) – Config dict (only used when plugin_or_cls is a class).frequency (
Optional[float]) – Step frequency in Hz (None= every step).phase (
Union[CallbackPhase,str,None]) – When in the stepSimPlugin.on_step()runs, aCallbackPhaseor its value ("pre_step","step","post_step"), as forregister_callback().Nonekeeps the plugin’s ownSimPlugin.step_phase("step"unless the class sets another).
- Return type:
TypeVar(_SimPluginT, bound= SimPlugin)- Returns:
The registered
SimPlugininstance.- Raises:
TypeError – If plugin_or_cls is not a SimPlugin.
ValueError – If
frequencyorphaseis not valid.
- property plugins: List[SimPlugin]
Read-only list of active plugins.
- register_callback(callback, frequency=None, phase=CallbackPhase.STEP)
Register a callback function to be called during simulation.
- Parameters:
callback (
Callable) – Function with signature callback(sim_core, dt) -> None - sim_core: Reference to MultiRobotSimulationCore instance - dt: Simulated time since this callback last ran (seconds)frequency (
Optional[float]) – Callback frequency in Hz. If None (or 0), called every simulation step. Due times are a fixed grid ofk / frequencyseconds of simulated time, so a callback neither skips beats nor drifts; it runs at most once per step, and the first time one interval into the run.phase (
Union[CallbackPhase,str]) –When in the step the callback runs, a
CallbackPhaseor its value as a string.CallbackPhase.PRE_STEP/"pre_step": at the start of the step, right after thepre_stepevent’s handlers, before the clock advances and before anything moves.sim_core.sim_timeis still the previous state’s time. Use it to apply commands this step should act on.CallbackPhase.STEP/"step"(default): after the objects have been updated, before their new poses are written to PyBullet and before the collision check.CallbackPhase.POST_STEP/"post_step": at the end of the step, right after thepost_stepevent: poses are written, and when the step ran a collision check (seecollision_check_frequency) the active pairs are those of the new poses. Use it to publish or record the step’s outcome.
In every phase
sim_core.sim_timeis the time of the state the callback sees: the previous state’s inPRE_STEP, the end of the step inSTEPandPOST_STEP; stamp anything read from the bodies with it. All three schedule theirfrequencyon it.
- Raises:
ValueError –
frequencyis negative or not finite, orphaseis not aCallbackPhase.- Return type:
A callback’s exception is not caught (unlike a plugin’s): it propagates out of
step_once(), and the rest of the step is skipped. What has happened by then depends on the phase:PRE_STEP: the clock has not advanced (sim_timeandstep_countstay at the previous state) and nothing has moved; the laterpre_stepcallbacks and plugins and the whole update are skipped.STEP: the clock has advanced and the objects have moved; later callbacks, the step’s plugins, the pose flush, the collision check, thepost_stepevent and thePOST_STEPcallbacks are skipped.POST_STEP: the step is complete except for later callbacks, thepost_stepplugins and what follows them.
In every phase the state recorder’s completed step and the DataMonitor refresh are skipped.
A callback is a subscription to the
phaseevent onevents(the event of the same name,SimEvents.PRE_STEP,SimEvents.STEPorSimEvents.POST_STEP) in a tier of its own: it runs after that event’s handlers, whatever their priority, and callbacks run in registration order.events.on(phase, handler, frequency=...)is the keyword-argument form of the same hook, with the same schedule; its exceptions are logged instead of raised.Example:
def my_callback(sim_core, dt): for obj in sim_core.sim_objects: if isinstance(obj, Agent): # Update agent logic pass sim_core.register_callback(my_callback, frequency=10.0) # 10 Hz def publish(sim_core, dt): stamp = sim_core.sim_time ... sim_core.register_callback(publish, frequency=10.0, phase=CallbackPhase.POST_STEP)
- register_behavior_tree(tree)
Register a behavior tree to tick once per simulation step.
treemust providetick(sim_core, dt). Registration is idempotent by object identity, and the returned tree makes inline use convenient. The tree’stickmethod remains public for deterministic unit tests and custom stepping loops.- Return type:
BehaviorTree
- unregister_behavior_tree(tree)
Stop automatically ticking a tree previously registered with this simulation.
- Return type:
- property behavior_trees: Tuple[BehaviorTree, ...]
Behavior trees automatically ticked by this simulation.
- register_manager(manager)
Register a
SimObjectManager(or subclass) with this simulation.Registered managers are automatically synchronised when objects are removed via
remove_object()or the simulation isreset(). The manager’ssim_coreattribute is set to self.A manager can only be registered once; duplicate calls are ignored.
- Parameters:
manager (
SimObjectManager) – The manager instance to register.- Return type:
Example:
from pybullet_fleet.agent_manager import AgentManager mgr = AgentManager() sim.register_manager(mgr) mgr.spawn_agents_grid(10, grid_params, spawn_params) # When sim.remove_object(agent) is called later, # mgr.objects is kept in sync automatically.
- unregister_manager(manager)
Remove a manager from the registry.
- Return type:
- Returns:
True if the manager was found and removed, False otherwise.
- get_manager(name)
Return the registered
AgentManagerwith the given name, orNone.- Parameters:
name (
str) – The name assigned to the manager (name:field in YAML, or thename=argument passed toAgentManager).- Return type:
Example:
sim = MultiRobotSimulationCore.from_yaml("config.yaml") fleet = sim.get_manager("delivery_fleet") for agent in fleet.objects: agent.set_path([goal])
- unregister_callback(callback_func)
Remove a registered callback by function reference.
- start_recording(output='recording.gif', width=800, height=600, fps=15, duration=None, camera_mode='auto', time_base='sim', **kwargs)
Start recording the simulation as an animated GIF or MP4.
Frames are captured via
getCameraImage(ER_TINY_RENDERER)at the specified fps frequency. Works in bothp.DIRECTandp.GUI.Output format is auto-detected from the file extension:
.gif— Animated GIF via Pillow (always available).mp4— H.264 MP4 via imageio + pyav (requirespip install imageio[pyav])
Time bases:
"sim"(default) — Capture at fixed sim-time intervals. Playback always looks like 1× speed."real"— Capture at wall-clock intervals. Playback reflects actual execution speed (e.g. 10× sim → 10× video).
- Parameters:
output (
str) – Output file path (.gifor.mp4). Parent directories created automatically.width (
int) – Frame width in pixels.height (
int) – Frame height in pixels.fps (
int) – Capture frequency and playback FPS.duration (
Optional[float]) – Recording duration in sim-seconds (time_base="sim") or wall-clock seconds (time_base="real").Nonefor manual stop.camera_mode (
str) –"auto"|"gui"|"orbit"|"manual"."auto"is promoted to"gui"when running in GUI mode.time_base (
str) –"sim"or"real". Controls capture timing.**kwargs (
Any) – Passed toSimulationRecorder(e.g.orbit_degrees,camera_params).
- Return type:
- Returns:
SimulationRecorderinstance.
Example:
sim.start_recording("output.gif", duration=4.0) sim.start_recording("output.mp4", duration=4.0, fps=30) sim.start_recording("perf.mp4", duration=4.0, time_base="real") sim.run_simulation(duration=5.0) # File is auto-saved when run_simulation ends
- stop_recording()
Stop recording and save the output file.
- set_collision_check_frequency(frequency=None)
Set the frequency (Hz, number of times per second) for collision detection.
- Parameters:
frequency (
Optional[float]) – Collision check frequency in Hz (times per second) - None: Check every step (highest accuracy, highest cost) - 0: Disable collision checking (no collision detection) - > 0: Check at specified frequency (e.g., 1.0 = once per second)- Return type:
Example:
sim.set_collision_check_frequency(None) # Every step sim.set_collision_check_frequency(1.0) # 1 Hz (once per second) sim.set_collision_check_frequency(10.0) # 10 Hz sim.set_collision_check_frequency(0) # Disable
Note: Higher frequency increases computational cost but improves collision detection accuracy.
- setup_pybullet()
Initialize PyBullet with GUI panels hidden.
- Return type:
- disable_rendering()
Disable rendering during object spawning for better performance.
- Return type:
- enable_rendering()
Enable rendering before starting simulation.
- Return type:
- batch_spawn()
Context manager for optimised batch spawning.
Disables rendering and defers spatial-grid rebuild until the context exits. Use when spawning many objects at once.
Rendering state is saved on entry and restored on exit. If rendering was already disabled (e.g. during the initial setup phase before
run_simulation()), it stays disabled afterbatch_spawn()exits.Example:
with sim_core.batch_spawn(): for params in params_list: Agent.from_params(params, sim_core) # rendering restored to previous state, spatial grid rebuilt once
- set_poses(object_ids, positions, orientations, *, preserve_velocity=True)
Set poses for N objects in one call (batch / high-throughput path).
Use this when poses are already in array form (ROS
PoseArray, vectorized controllers, NumPy pipelines). For single-object writes preferSimObject.set_pose()with aPoseobject — this method intentionally takes raw ndarrays to avoid per-objectPoseallocations on the hot path.Internally honours the same two-phase semantics as
SimObject.set_pose: insidestep_once()the writes are buffered to be flushed in Phase 2, outside they propagate to PyBullet immediately.get_pose/get_posesalways reflect the new values regardless of phase.- Parameters:
object_ids (
Sequence[int]) – N object ids to write to (in matching order).positions (
ndarray) –(N, 3)float array of XYZ positions.orientations (
ndarray) –(N, 4)float array of XYZW quaternions.preserve_velocity (
bool) – If True, preserve current velocities (dynamic objects only; ignored for kinematic objects).
- Raises:
ValueError – if shapes don’t match
(N, 3)/(N, 4)forN = len(object_ids).KeyError – if any
object_idis not registered in this sim.
- Return type:
- get_poses(object_ids)
Return
(positions, orientations)arrays for N objects (batch read).Counterpart of
set_poses(). Returns raw ndarrays for direct use in vectorized math, ROS message construction, or controller state. For single-object reads preferSimObject.get_pose()which returns aPoseobject.Reads each object’s cached pose (no PyBullet API call), so values are always consistent with the two-phase semantics — buffered writes made during the current step are visible immediately.
- notify_geometry_changed(obj)
Tell the simulation that
obj’s links moved without its base pose being set.A joint moved by
Agent.set_joint_position(), by the joint interpolation of a kinematic agent or by restoring a checkpoint calls this already. Call it after moving a body’s joints directly through PyBullet (p.resetJointState).The body counts as moved for the next collision check, and its broadphase AABB (the union of its link boxes) and spatial-hash cells follow the links. Outside a step that happens at once. Inside a step a kinematic or
STATICbody is refreshed with the flushed poses before the collision check; a physics body is re-read afterstepSimulation()anyway.- Parameters:
obj (
SimObject) – The object whose links moved.- Return type:
- set_collision_ignore_filter(ignore)
Exclude the touching pairs
ignore(obj_a, obj_b)returnsTruefor from collision results.An ignored pair is treated as not touching everywhere a collision shows up: it is not an active pair, not counted, not recoloured, not in the collision observation and raises no
COLLISION_STARTED. A pair that becomes ignored while active is resolved (COLLISION_ENDED) on the next collision check, and an ignored pair that stops being ignored is checked again on the next one, whether or not either body moved. So the filter may depend on state that changes at run time – which object carries which, say. It is applied on top ofignore_attached_collision.Noneremoves it.Ignored pairs skip the narrow phase, so the filter is called, on each collision check, for every broad-phase candidate pair involving a moved object, every active pair and every pair it ignored last time until they move apart; keep it cheap.
- Return type:
- set_collision_margin(margin)
Change the clearance and recheck stationary pairs on the next collision check.
- Parameters:
margin (
Union[float,Sequence[float]]) – Metres, for every direction, or an(x, y, z)sequence with one clearance per world axis (seeSimulationParams.collision_margin).- Raises:
ValueError – If the margin, or any component, is negative or not finite, or a sequence does not have three components.
- Return type:
- set_collision_spatial_hash_cell_size_mode(mode=None, cell_size=None)
Set collision detection spatial hash cell size mode and recalculate/rebuild grid.
This method allows dynamic mode switching and always recalculates the cell_size based on the spatial_hash_cell_size_mode setting (or override via parameters).
- Parameters:
- Return type:
- Returns:
The calculated cell_size (always > 0, falls back to 1.0 if no AABBs available)
Example:
# Recalculate with current mode sim_core.set_collision_spatial_hash_cell_size_mode() # Switch to constant mode with specific size sim_core.set_collision_spatial_hash_cell_size_mode( mode=SpatialHashCellSizeMode.CONSTANT, cell_size=3.0 ) # Switch to auto_adaptive mode sim_core.set_collision_spatial_hash_cell_size_mode( mode=SpatialHashCellSizeMode.AUTO_ADAPTIVE )
- add_object(obj)
Add an object to simulation and register it with all necessary caches.
This method centralizes object registration logic for consistency and maintainability. Called automatically by SimObject.__init__() when sim_core is provided.
- Parameters:
obj (
SimObject) – The SimObject instance to add- Return type:
Example:
# Manual addition (not recommended - SimObject does this automatically) obj = SimObject(body_id=body_id, sim_core=None) sim_core.add_object(obj) # Automatic addition (recommended) obj = SimObject(body_id=body_id, sim_core=sim_core) # Calls add_object() internally
- remove_object(obj)
Remove an object from simulation and clean up all caches.
- Parameters:
obj (
SimObject) – The SimObject instance to remove- Return type:
Example:
obj = sim_core.spawn_robot(...) # ... later ... sim_core.remove_object(obj)
- configure_visualizer(enable_structure_transparency=None, enable_shadows=None)
Configure PyBullet visualizer settings with keyboard control.
- Parameters:
- Return type:
Custom keyboard shortcuts (active during simulation): - Press SPACE to pause/play simulation - Press ‘t’ to toggle structure transparency ON/OFF
Camera controls (always active in GUI mode): - Right-drag to pan camera - Press arrow keys to pan camera horizontally - Press ‘=’ to zoom in, ‘-’ to zoom out - Press ‘o’ for top-down view
PyBullet built-in keyboard shortcuts (always available): - Press ‘w’ to toggle wireframe / collision shape display - Press ‘g’ to toggle grid display - Press ‘j’ to toggle joint axes display
- configure_gui_lighting(lighting_config=None)
Apply optional PyBullet GUI main-light and shadow-map settings.
lighting_configacceptslight_position(three coordinates),shadow_map_world_sizeandshadow_map_resolution. The normal PyBullet GUI has one main light; this does not model USD light prims.- Return type:
- compute_scene_bounds()
Compute scene bounding box from all sim_object positions.
Returns a
(center, extent)tuple where center is the mean position[cx, cy, cz]and extent is the axis-aligned size[ex, ey, ez](i.e.max - minper axis).When the scene is empty both lists are
[0.0, 0.0, 0.0].This is used by
setup_camera()(GUI) andSimulationRecorder(offscreen) so that both share the same scene-framing logic.
- setup_camera(camera_config=None, entity_positions=None)
Set up camera view based on configuration.
Valid
camera_modevalues:"auto"(default) — Auto-calculates camera distance and target from entity positions orsim_objects."manual"— Uses explicitcamera_distance,camera_yaw,camera_pitch, andcamera_targetfrom the config.
Interactive controls (right-drag/arrow-key pan, +/- zoom, o=top-down) are always enabled in GUI mode regardless of camera_mode.
- query_aabb(aabb_min, aabb_max)
Objects whose AABB overlaps the box
[aabb_min, aabb_max].Looks only at the objects registered in the collision spatial hash cells the box reaches, so the cost depends on how crowded the box is, not on how many objects the simulation holds. Every object is registered in each cell its AABB reaches, and kinematic and physics objects are re-registered on every step whatever the collision check frequency, so the hash answers for the current step. Before the hash exists, or when the box spans more cells than there are objects, every object is tested instead.
Objects with collision
DISABLEDare not in the hash; they are tested directly against their PyBullet AABB. A pose written outside a step is applied at once and answered for. Inside a step (from a callback or a controller), a written pose is buffered and reaches PyBullet only when the step flushes it: until then such an object is tested against the AABB of the pose it had when the step began. Joints are not buffered: an object whose links moved in the step (notify_geometry_changed) is tested against its links as they are now, at the base pose PyBullet holds.- Parameters:
- Return type:
List[SimObject]- Returns:
The overlapping objects, in no particular order.
Example:
# Everything within 0.5 m of a point, as a box nearby = sim.query_aabb((x - 0.5, y - 0.5, z - 0.5), (x + 0.5, y + 0.5, z + 0.5))
- pickable_candidates_near(position, radius)
Every pickable object whose base origin may be within
radiusofposition.A superset, for a search by base origin such as
SimObject.find_nearest_pickable(): it may also hold objects farther away or not pickable, so the caller measures the distance and checkspickableitself. The objects come through the spatial hash, as forquery_aabb(), plus those the hash cannot place by their origin: a pickable shape set more than a cell off its origin, objects with collisionDISABLED, and objects with a pose written in the current step and not yet flushed (their cached pose is already the new one). Before the hash exists, every object.
- get_aabbs()
Get the AABB of every simulation object, each covering all of the body’s links.
- filter_aabb_pairs(ignore_static=None, moved_objects=None, return_profiling=False)
Filter AABB pairs for collision detection with moved-based optimization. Only checks pairs involving moved objects.
- Parameters:
ignore_static (
Optional[bool]) – If True, skip collision checks with static objectsmoved_objects (
Optional[Set[int]]) – Set of object IDs that moved since last check. If None, uses self._moved_this_step (default behavior)return_profiling (
bool) – If True, include timing information in return value
- Returns:
pairs: List of (obj_id_i, obj_id_j) tuples for candidate collision pairs
timings: dict with get_aabbs, spatial_hashing, aabb_filtering (in ms) if return_profiling=True, else None
- Return type:
Tuple of (pairs, timings)
Example:
# Without profiling pairs, _ = sim.filter_aabb_pairs() # With profiling pairs, timings = sim.filter_aabb_pairs(return_profiling=True) print(f"AABB filtering took {timings['total']:.2f}ms")
- check_collisions(collision_color=None, ignore_static=None, return_profiling=False)
Check for collisions between robots using incremental updates.
Only re-checks collision pairs involving moved objects for efficiency. Maintains _active_collision_pairs as persistent state.
- Parameters:
- Returns:
pairs: List of currently active collision pairs (obj_id_i, obj_id_j)
timings: dict with get_aabbs, spatial_hashing, aabb_filtering, contact_points, total (in ms) if return_profiling=True, else None
- Return type:
Tuple of (pairs, timings)
Example:
# Without profiling active_pairs, _ = sim.check_collisions() # With profiling active_pairs, timings = sim.check_collisions(return_profiling=True) print(f"Collision check took {timings['total']:.2f}ms")
- get_active_collision_pairs()
Get currently active collision pairs.
- Return type:
- Returns:
List of (object_id_i, object_id_j) tuples for all active collisions. Pairs are sorted such that object_id_i < object_id_j.
Example:
# Check if any collisions are active if sim_core.get_active_collision_pairs(): print("Collisions detected!") # Get detailed collision info for obj_id_i, obj_id_j in sim_core.get_active_collision_pairs(): obj_i = sim_core._sim_objects_dict[obj_id_i] obj_j = sim_core._sim_objects_dict[obj_id_j] print(f"Collision: {obj_i} <-> {obj_j}")
- get_collision_observation()
Return the latest completed collision check, or
Nonebefore one runs.A skipped step does not update the check timestamp. Each pair also has its own sample timestamp because incremental checks may leave an active pair unmeasured during a later completed check.
- Return type:
Optional[CollisionObservation]
- update_monitor()
Update simulation monitor with current statistics.
Calculates actual simulation speed from a 10-second sliding window, logs monitor data via logger, and writes to DataMonitor if enabled.
- Return type:
- flush_monitor()
Build and write a monitor frame now if the window is behind; return whether it did.
Running, the next refresh (
monitor_update_interval) shows any change, andclose()flushes, so only a program that stops callingstep_once()and keeps the simulation open needs this.- Return type:
- initialize_simulation()
Initialize simulation state before running.
This method prepares the simulation for execution by: - Resetting simulation counters (step_count, collision_count, sim_time) - Clearing movement tracking state - Configuring visualizer settings (transparency, collision shapes) - Enabling rendering for GUI mode
Called automatically by run_simulation(), but can also be called manually for custom simulation loops or when restarting simulation.
Example:
# Automatic (recommended) sim.run_simulation(duration=10.0) # Manual initialization for custom loop sim.initialize_simulation() while custom_condition: sim.step_once()
- Return type:
- reset()
Reset simulation to a clean state (no objects, fresh PyBullet world).
Removes all objects from the simulation, resets PyBullet, re-applies physics-engine parameters, optionally reloads the ground plane (only when
enable_flooris True), and re-initialises counters viainitialize_simulation().After calling
reset()the simulation is ready for new objects to be spawned. Callbacks registered viaregister_callback()are preserved (their schedules restart ininitialize_simulation).Example:
sim.reset() # All objects removed, PyBullet world cleared agent = Agent.from_params(params, sim) sim.step_once()
- Return type:
- load_world(world_config, skip_models=None)
Load world environment from a configuration dictionary.
Supports three sources (checked in priority order):
world_file— a Gazebo.worldfile with<include>elements (buildings, furniture, props).sdf— a single SDF model file (building geometry).mesh_dir— a directory of OBJ/STL mesh files.
- Parameters:
world_config (
Dict[str,Any]) –Dictionary with world loading options:
{ "world_file": "/path/to/office.world", "skip_models": ["TinyRobot", "TeleportDispenser"], } or:: {"sdf": "/path/to/model.sdf"} or:: {"mesh_dir": "/path/to/meshes/"}
skip_models (
Optional[List[str]]) – Model names to skip when loading a.worldfile (e.g. robot names that are spawned separately).
- Return type:
List[SimObject]- Returns:
List of
SimObjectinstances created from the world.
Example:
sim = MultiRobotSimulationCore(SimulationParams(enable_floor=False)) sim.initialize_simulation() objs = sim.load_world({"world_file": "/maps/office.world"})
- spawn_robots_from_config(robots_config)
Spawn robots/entities from a YAML-style configuration list.
Each entry in robots_config is a dict understood by
AgentSpawnParams.from_dict()(or the appropriateSpawnParamsfor the entitytype). SDF models are automatically converted to temporary URDF files viaresolve_sdf_to_urdf(), and model names are resolved throughresolve_model().Grid spawning: If an entry contains a
gridkey, the entry is expanded into multiple entities placed on a grid. Thegriddict is parsed byfrom_dict()and supports two formats:Count-based (convenience):
{ "urdf_path": "robots/mobile_robot.urdf", "controller": {"type": "omni"}, "grid": { "count": 50, "spacing": [3.0, 3.0], "offset": [0, 0, 0.05], "columns": 10, # optional }, }
Range-based (explicit grid extents):
{ "urdf_path": "robots/mobile_robot.urdf", "grid": { "x_min": 0, "x_max": 9, "y_min": 0, "y_max": 4, "spacing": [3.0, 3.0, 0.0], "offset": [0, 0, 0.05], }, }
Grid entries create a manager internally and register it with this simulation, so objects are automatically synchronised on
remove_object()andreset().Batch processing: Declare a named manager with
fleet_controller.typeand route the entity group to it. All entities in the group are added to that manager:"managers": [{ "name": "delivery_fleet", "fleet_controller": {"type": "batch_differential"}, }] "entities": [{ "urdf_path": "robots/simple_cube.urdf", "controller": {"type": "differential"}, "manager": "delivery_fleet", "grid": {"count": 100, "spacing": [2, 2]}, }]
Entity type dispatch: If an entry contains a
typekey (e.g."agent","sim_object", or a custom registered type), the corresponding class from the entity registry is used. Default is"agent".- Parameters:
robots_config (
List[Dict[str,Any]]) – List of robot/entity parameter dicts.- Return type:
List[SimObject]- Returns:
List of spawned
SimObject(or subclass) instances.
Example:
sim.spawn_robots_from_config([ # Individual robot {"urdf_path": "robots/mobile_robot.urdf", "pose": [0, 0, 0.05]}, # Grid routed to a named batch manager { "urdf_path": "robots/mobile_robot.urdf", "controller": {"type": "omni"}, "manager": "delivery_fleet", "grid": {"count": 20, "spacing": [3, 3]}, }, # Grid assigned to a named manager { "urdf_path": "robots/mobile_robot.urdf", "manager": "delivery_fleet", "grid": {"count": 50, "spacing": [2, 2]}, }, # Custom entity type {"type": "forklift", "urdf_path": "robots/forklift.urdf", "pose": [10, 0, 0]}, ])
- run_simulation(duration=None, *, resume=False)
Run the simulation for a specified duration.
- Parameters:
duration (
Optional[float]) – Absolute simulation-time cutoff in seconds (not wall time). If None, uses self._params.duration. If duration <= 0, runs indefinitely.resume (
bool) – Continue an explicitly restored completed-step state without resetting its clock. A core returned by the supported recording loader resumes on its first plain call too.
- Return type:
Example:
# Run for 10 seconds (simulation time) sim.run_simulation(duration=10.0) # Run indefinitely (until Ctrl+C or GUI closed) sim.run_simulation(duration=0)
- close()
Release everything this simulation owns, including its client.
run_simulation()has always done this on the way out, but a program that drivesstep_once()itself, or a test that only builds a scene, never reached that code – and nothing else disconnected. An undisconnected client leaks for the life of the process, and because PyBullet’s module-level calls resolve against a default client, the next simulation in the same process then finds bodies and joints “not found” rather than failing where the leak happened.Safe to call more than once, and safe on a simulation that was never run. A second call does nothing at all: shutdown callbacks run once, so a plugin that closes a file or a socket in
on_shutdown()is not asked to do it twice bywith sim:around arun_simulation()that already closed.Releasing the client is unconditional. Finalising a recording can raise – saving an MP4 without
imageio, for one – and letting that escape before the disconnect would leak the very client this exists to release.- Return type:
- record_profiling(name, value_ms)
Record a custom profiling measurement (in milliseconds).
Call this from within Agent.update() or callback code to accumulate timing data. Multiple calls per step are summed (e.g., 100 agents each recording their custom_logic time). Auto-registers the field on first use.
The recorded field appears in both _print_profiling_summary() output and step_once(return_profiling=True) results alongside built-in fields.
- Parameters:
- Return type:
Example:
# Inside your custom Agent.update(): t0 = time.perf_counter() self._do_custom_logic(dt) self.sim_core.record_profiling('custom_logic', (time.perf_counter() - t0) * 1000)
- pause()
Pause the simulation. step_once will be skipped while paused.
- Return type:
- resume()
Resume the simulation after a pause.
- Return type:
- property is_paused: bool
Return True if the simulation is currently paused.
- step_once(return_profiling=False)
Execute one simulation step.
Performs agent updates, callbacks, physics step, collision detection, and monitoring. If enable_time_profiling is True, detailed timing information is logged.
- Parameters:
return_profiling (
bool) – If True, return timing breakdown dictionary instead of logging. Useful for external profiling tools.- Return type:
- Returns:
If return_profiling=True, returns dict with timing breakdown in milliseconds:
{ 'phase1_update': float, # agent.update + callbacks + plugin on_step 'phase2_pose_flush': float, # flush buffered poses to PyBullet 'phase3_aabb_grid_flush': float, # kinematic AABB + spatial-grid refresh 'agent_update': float, # per-object update loop (subset of phase1; compat) 'callbacks': float, # CallbackPhase.STEP callbacks (not plugins) 'step_simulation': float, # p.stepSimulation(); non-zero only if physics=True 'collision_check': float, 'collision_breakdown': { # present only when collision ran 'get_aabbs': float, 'spatial_hashing': float, 'aabb_filtering': float, 'contact_points': float, # narrow phase; non-zero only if physics=True 'total': float, }, 'events_pre_step': float, # handlers of the pre_step event 'callbacks_pre_step': float, # CallbackPhase.PRE_STEP callbacks 'events_step': float, # handlers of the step event (before callbacks) 'events_post_step': float, 'callbacks_post_step': float, # CallbackPhase.POST_STEP callbacks 'events_collision': float, 'monitor_update': float, 'total': float, }
Otherwise returns None.
Performance note: time.perf_counter() calls have negligible overhead (<0.1% for 10k objects). The profiling measurements themselves do not significantly impact simulation performance.
- get_memory_usage()
Get current memory usage (requires enable_memory_profiling=True).
- Return type:
- Returns:
Dictionary with current and peak memory usage in MB, or None if not enabled. Keys: ‘current_mb’, ‘peak_mb’
Note
Returns Python heap memory tracked by tracemalloc, NOT RSS (process memory).
tracemalloc tracks Python object allocations, not C extensions or OS-level memory.
For total process memory (RSS), use: psutil.Process().memory_info().rss
Peak is cumulative since last reset_peak() call (interval-based in profiling).
Example:
>>> sim = MultiRobotSimulationCore.from_dict(config) >>> # ... run simulation with enable_memory_profiling=True ... >>> mem = sim.get_memory_usage() >>> if mem: >>> print(f"Python heap: {mem['current_mb']:.2f} MB, Peak: {mem['peak_mb']:.2f} MB")
- class pybullet_fleet.SimulationParams(target_rtf=1.0, timestep=0.1, duration=0, gui=True, physics=False, monitor=True, enable_monitor_gui=None, monitor_update_interval=None, monitor_log_interval=1.0, collision_check_frequency=None, log_level='warn', max_steps_per_frame=10, max_sleep_frames=4.0, gui_min_fps=30, enable_collision_shapes=False, enable_structure_transparency=False, enable_shadows=True, enable_gui_panel=False, ignore_static_collision=True, ignore_attached_collision=True, enable_time_profiling=False, profiling_interval=100, enable_memory_profiling=False, enable_collision_color_change=False, spatial_hash_cell_size_mode=SpatialHashCellSizeMode.AUTO_INITIAL, spatial_hash_cell_size=None, collision_detection_method=None, collision_margin=0.02, multi_cell_threshold=1.5, enable_floor=True, camera_config=None, lighting_config=None, model_paths=None, window_width=1024, window_height=768, monitor_width=680, monitor_height=480, monitor_x=-1, monitor_y=-1)
Bases:
objectSimulation configuration parameters.
All fields have sensible defaults for headless kinematics-based simulation. Use
from_config/from_dictto load from YAML files.- target_rtf: float = 1.0
- timestep: float = 0.1
- duration: float = 0
- gui: bool = True
- physics: bool = False
- monitor: bool = True
- enable_monitor_gui: bool | None = None
Whether the DataMonitor opens a window.
None(the default) followsgui: a headless simulation collects monitor data without putting a Tk window on screen.TrueorFalseis honoured as given, so a monitor window without the PyBullet viewer is still available.
- monitor_update_interval: float | None = None
Simulated seconds between DataMonitor refreshes while
monitoris on. A refresh buildslast_monitor_frameand writes the file the monitor window reads (every 0.5 wall seconds).None(the default) is 0.25 s while the monitor window is open (enable_monitor_gui, orguiwhen that isNone) and 1 s otherwise;0is every step. Simulated time: at a real-time factor above 1 a short interval means more writes per wall second. While paused, a selection, follow or pause change, and a single step, refresh at once. Read once, when the simulation is created.
- monitor_log_interval: float = 1.0
Wall-clock seconds between
[MONITOR]lines logged at INFO – RTF, collision totals, step count – independent ofmonitor,guiandmonitor_update_interval.monitordrives the DataMonitor, whose line is logged at DEBUG; this keeps those figures in the log whether or not anything is on screen. Default 1 s;0logs none. Wall clock rather than simulated time, so the log’s volume does not scale with the real-time factor.
- log_level: str = 'warn'
- max_steps_per_frame: int = 10
- max_sleep_frames: float = 4.0
- gui_min_fps: int = 30
- enable_collision_shapes: bool = False
- enable_structure_transparency: bool = False
- enable_shadows: bool = True
- enable_gui_panel: bool = False
- ignore_static_collision: bool = True
- ignore_attached_collision: bool = True
Do not count contact between objects on one attachment tree (
attach_object): a carrier, its loads and their loads touch one another by design. Contact with anything outside the tree is reported.
- enable_time_profiling: bool = False
- profiling_interval: int = 100
- enable_memory_profiling: bool = False
- enable_collision_color_change: bool = False
- spatial_hash_cell_size_mode: SpatialHashCellSizeMode = 'auto_initial'
- collision_detection_method: CollisionDetectionMethod | None = None
- collision_margin: float | Tuple[float, float, float] = 0.02
Clearance, in metres, within which CLOSEST_POINTS (and the kinematic pairs of HYBRID) report a pair that does not touch; CONTACT_POINTS ignores it. A number applies to every direction; an
(x, y, z)triple (a list in YAML) gives one clearance per world axis, for example(0.05, 0.05, 0.0)to report bodies side by side but not one passing close above or below another. A triple acts in the broad phase: each AABB axis is enlarged by that axis’s clearance, so two bodies whose AABBs are farther apart than that on any axis are never reported. The narrow phase judges the straight-line gap against the largest component, so(m, m, m)is the same asm, and(m, m, 0)reports whatCollisionMode.NORMAL_2Dwithmdid, for every pair.
- multi_cell_threshold: float = 1.5
- enable_floor: bool = True
- window_width: int = 1024
- window_height: int = 768
- monitor_width: int = 680
- monitor_height: int = 480
- monitor_x: int = -1
- monitor_y: int = -1
- classmethod from_config(config_path='config.yaml')
- Return type:
SimulationParams
- class pybullet_fleet.SpatialHashCellSizeMode(value)
Bases:
EnumCollision detection spatial hash cell size calculation mode.
Determines how the spatial hash grid cell size is calculated for efficient broad-phase collision detection.
- CONSTANT
Fixed cell size provided by user (fastest, requires manual tuning)
- AUTO_ADAPTIVE
Recalculate on object add/remove (adaptive, some overhead)
- AUTO_INITIAL
Calculate once at simulation start (default, balanced performance)
- CONSTANT = 'constant'
- AUTO_ADAPTIVE = 'auto_adaptive'
- AUTO_INITIAL = 'auto_initial'
- class pybullet_fleet.SimulationRecorder(sim_core, output='recording.gif', width=800, height=600, fps=15, duration=None, camera_mode='auto', camera_params=None, orbit_degrees=60.0, time_base='sim')
Bases:
objectRecord simulation frames and save as animated GIF or MP4.
Captures RGB frames using
p.getCameraImage(). UsesER_TINY_RENDERER(CPU) for headless/custom cameras, orER_BULLET_HARDWARE_OPENGL(GPU) in"gui"mode for faster rendering that matches the GUI window exactly.Output format is auto-detected from the file extension:
.gif— Animated GIF via Pillow (always available).mp4— H.264 MP4 via imageio + pyav (requirespip install imageio[pyav])
Camera modes:
"auto"— Compute scene AABB, position camera overhead with auto-framing. Automatically promoted to"gui"when running inp.GUImode."gui"— Record exactly what the GUI camera shows, usingER_BULLET_HARDWARE_OPENGL(GPU). Mouse pan/zoom/rotate is captured in real time. Only valid inp.GUImode."orbit"— Same as auto + camera orbits horizontally over the recording."manual"— Use explicit camera parameters fromcamera_params.
Time bases:
"sim"— (default) Capture at fixed sim-time intervals. Playback always looks like 1× speed regardless of how fast the simulation ran."real"— Capture at wall-clock intervals. Playback reflects actual execution speed (e.g. a 10× sim produces a 10× fast video).
- Parameters:
sim_core (
MultiRobotSimulationCore) – The simulation core instance to record.output (
str) – Output file path (.gifor.mp4). Directory is created automatically.width (
int) – Frame width in pixels.height (
int) – Frame height in pixels.fps (
int) – Capture frequency and playback FPS.duration (
Optional[float]) – Recording duration in simulation seconds (time_base="sim") or wall-clock seconds (time_base="real").Nonefor manual stop.camera_mode (
str) –"auto"|"gui"|"orbit"|"manual"."auto"is promoted to"gui"whenparams.guiis True.camera_params (
Optional[Dict[str,Any]]) – Camera parameters for"manual"mode. Keys:camera_target,camera_distance,camera_yaw,camera_pitch.orbit_degrees (
float) – Total horizontal orbit angle in degrees (for"orbit"mode).time_base (
str) –"sim"(default) or"real". Controls capture timing and duration measurement. See Time bases above.
- start()
Begin recording. Registers a capture callback on sim_core.
- Return type:
- stop()
Stop recording. Unregisters the capture callback.
- Return type:
- save()
Write captured frames to file (GIF or MP4, auto-detected from extension).
- Return type:
- Returns:
The output file path.
- Raises:
ValueError – If no frames have been captured.
RuntimeError – If MP4 is requested but
imageiois not installed.
- property is_recording: bool
Whether the recorder is currently capturing frames.
- property frame_count: int
Number of frames captured so far.
- class pybullet_fleet.SimObject(body_id, sim_core=None, pickable=True, mass=None, collision_mode=CollisionMode.NORMAL_3D, name=None, user_data=None)
Bases:
objectBase class for simulation objects (robots, pallets, obstacles). Supports attachment/detachment and kinematic teleportation.
- Object Identification:
- object_id: Unique integer ID assigned by sim_core (used for lookups and internal tracking).
This is the primary identifier for programmatic access.
- name: Optional string name for human-readable identification (used for debugging, logging, filtering).
Multiple objects can share the same name (duplicates allowed). Not guaranteed to be unique - use object_id for unique identification.
- Parameters:
- object_id
Unique integer ID (assigned by sim_core, use for lookups)
- name
Optional string name (duplicates allowed, use for debugging/filtering)
- body_id
PyBullet body ID
- mass
Object mass in kg
- pickable
Whether this object can be picked by robots
- collision_mode
Collision detection mode (NORMAL_3D, STATIC, DISABLED; NORMAL_2D is deprecated)
- user_data
Dictionary for custom metadata (default: empty dict)
- attached_objects: List[SimObject]
- update(dt)
Called every simulation step for objects with
_needs_update = True.Override in subclasses to implement per-step behavior (e.g. device state machines, animated objects).
- property events: EventBus
Per-entity EventBus. Created on first access (lazy).
Use in subclasses to hook into entity-specific events:
class WarehouseRobot(Agent): def __init__(self, ...): super().__init__(...) from pybullet_fleet.events import SimEvents self.events.on(SimEvents.COLLISION_STARTED, self._on_bump) self.events.on(SimEvents.ACTION_COMPLETED, self._on_task_done)
- set_name(name)
Set the object name and update the log prefix accordingly.
Use this instead of directly setting
self.nameto ensure the log prefix stays in sync.
- classmethod create_shared_shapes(visual_shape=None, collision_shape=None, physics_client_id=None)
Create shared visual and collision shapes for fast object spawning.
This method caches mesh shapes by their parameters and physics client, so multiple objects with identical mesh parameters on one client will reuse the same PyBullet shape IDs.
Note: Primitive shapes (box, sphere, cylinder) are NOT cached, as PyBullet handles them very efficiently and caching adds unnecessary overhead.
A mesh collision shape PyBullet cannot build (a Gazebo
.dae, say) is replaced by none, with a warning: the body is visual-only. That result is cached like a success, so every later call with the same parameters on the same client returns the visual-only pair at once, without another attempt or warning. Building the same mesh again would fail the same way and log once per spawn; to retry after fixing the file, start a new simulation (a reset or reconnect forgets the client’s shapes).- Parameters:
visual_shape (
Optional[ShapeParams]) – ShapeParams for visual geometrycollision_shape (
Optional[ShapeParams]) – ShapeParams for collision geometryphysics_client_id (
Optional[int]) – PyBullet physics client the shapes are created on; pass the simulation’ssim_core.client. Leaving it out is deprecated: it falls back to PyBullet’s default client (0) with aDeprecationWarning, which is the wrong client when more than one simulation runs in the process.
- Return type:
- Returns:
(visual_id, collision_id) tuple
Example:
visual_id, collision_id = create_shared_shapes( visual_shape=ShapeParams( shape_type="mesh", mesh_path="visual.obj", mesh_scale=[1.0, 1.0, 1.0], rgba_color=[0.8, 0.2, 0.2, 1.0] ), collision_shape=ShapeParams( shape_type="box", half_extents=[0.5, 0.3, 0.2] ), physics_client_id=sim_core.client )
- classmethod from_mesh(visual_shape=None, collision_shape=None, pose=None, mass=0.0, pickable=True, sim_core=None, collision_mode=CollisionMode.NORMAL_3D, name=None, user_data=None)
Create a SimObject with optional visual and collision shapes.
- Parameters:
visual_shape (
Optional[ShapeParams]) – ShapeParams for visual geometrycollision_shape (
Optional[ShapeParams]) – ShapeParams for collision geometrypose (
Pose) – Initial Pose (position and orientation, default: origin)mass (
float) – Object mass (0.0 for static)pickable (
bool) – Whether object can be picked by robotssim_core – Reference to simulation core
name (
Optional[str]) – Optional human-readable name (duplicates allowed)
- Return type:
SimObject- Returns:
SimObject instance
Example:
# Box visual + sphere collision obj = SimObject.from_mesh( visual_shape=ShapeParams( shape_type="box", half_extents=[0.5, 0.3, 0.2], rgba_color=[0.8, 0.2, 0.2, 1.0] ), collision_shape=ShapeParams( shape_type="sphere", radius=0.4 ), pose=Pose.from_xyz(0, 0, 1), mass=1.0, sim_core=sim_core )
- classmethod from_urdf(urdf_path, pose=None, sim_core=None, mass=0.0, pickable=False, collision_mode=CollisionMode.NORMAL_3D, use_fixed_base=True, global_scaling=1.0, name=None, user_data=None)
Load a URDF file and wrap the body in a SimObject.
The counterpart of
from_sdf()for single-body URDF models, and the non-agent counterpart ofAgent.from_urdf().Use this for static structure – walls, fixtures, shelving, fencing – that has a URDF but no behaviour. Such a body does not belong in the per-step update loop:
SimObject._needs_updateisFalse, sostep_once()skips it entirely, where anAgentis visited every step to walk an empty action queue, check joints it does not have and sweep plugins it does not own. Measured on a scene of 2376 fixed-base, jointless, controller-less bodies: 15.98 ms per step as Agents against 0.78 ms as SimObjects.Without this method, a URDF-defined static body has to be created as an Agent, because
urdf_pathexists only onAgentSpawnParams.- Parameters:
urdf_path (
str) – Model name (e.g."panda") or path to a URDF file. Resolved viaresolve_model().pose (
Optional[Pose]) – Initial Pose (default: origin).sim_core – Simulation core for registration.
mass (
Optional[float]) –0.0(the default) overrides every link to mass 0 for kinematic use;Nonekeeps the URDF’s own mass values.pickable (
bool) – Whether the object can be picked up (default: False, since scenery is the usual case).collision_mode (
CollisionMode) – Collision detection mode.use_fixed_base (
bool) – If True, the base is fixed in space.global_scaling (
float) – Uniform scale factor.name (
Optional[str]) – Human-readable name (default: the URDF’s own robot name).
- Return type:
SimObject- Returns:
SimObject instance.
- Raises:
FileNotFoundError – If the URDF cannot be loaded.
Example:
tile = SimObject.from_urdf( "frame_tile.urdf", pose=Pose.from_xyz(1.0, 2.0, 0.0), sim_core=sim, collision_mode=CollisionMode.STATIC, )
- classmethod from_sdf(sdf_path, sim_core=None, collision_mode=CollisionMode.NORMAL_3D, global_scaling=1.0, name_prefix=None, pickable=False, use_fixed_base=True)
Load an SDF file and wrap each body in a SimObject.
Uses PyBullet’s
p.loadSDF()to load the file and creates a SimObject for each body. All objects are auto-registered tosim_coreif provided.Note
PyBullet’s SDF loader does NOT support
<world>tags,<include>tags, ormodel://URIs. Use for individual SDF models (e.g., pybullet_data’s kiva_shelf, wsg50_gripper).- Parameters:
sdf_path (
str) – Path to SDF file (resolved via resolve_model())sim_core – Simulation core for registration
collision_mode (
CollisionMode) – Collision detection mode for all loaded objectsglobal_scaling (
float) – Uniform scale factorname_prefix (
Optional[str]) – Prefix for names (default: SDF filename stem)pickable (
bool) – Whether objects can be picked upuse_fixed_base (
bool) – If True, fix base (mass=0, kinematic)
- Return type:
List[SimObject]- Returns:
List of SimObject instances (one per body in the SDF)
Example:
shelves = SimObject.from_sdf( 'kiva_shelf/model.sdf', sim_core=sim ) for shelf in shelves: print(f'{shelf.name}: {shelf.get_pose()}')
- classmethod from_params(spawn_params, sim_core=None)
Create a SimObject from SimObjectSpawnParams.
- Parameters:
spawn_params (
SimObjectSpawnParams) – SimObjectSpawnParams instancesim_core – Reference to simulation core
- Return type:
SimObject- Returns:
SimObject instance
Example:
params = SimObjectSpawnParams( visual_shape=ShapeParams( shape_type="mesh", mesh_path="pallet.obj", mesh_scale=[0.5, 0.5, 0.5], rgba_color=[0.8, 0.6, 0.4, 1.0] ), collision_shape=ShapeParams( shape_type="box", half_extents=[0.5, 0.4, 0.1] ), initial_pose=Pose.from_xyz(0, 0, 0.1), mass=1.0 ) obj = SimObject.from_params(params, sim_core)
- classmethod from_dict(config, sim_core=None)
Create a SimObject from a raw config dict.
Combines
SimObjectSpawnParams.from_dict()andfrom_params()in a single call. Usescls._spawn_params_clsso subclasses automatically use their own SpawnParams.
- property is_static: bool
Whether this object is static (never moves).
Returns True if collision_mode is STATIC. This property is read-only. To change collision mode, use set_collision_mode() method.
- set_collision_mode(mode)
Change collision detection mode for this object.
This method updates the collision mode and notifies sim_core to update all collision-related caches (AABB, spatial grid, etc.).
- Parameters:
mode (
CollisionMode) – New CollisionMode- Return type:
Example:
# Change to static obj.set_collision_mode(CollisionMode.STATIC) # Disable collision obj.set_collision_mode(CollisionMode.DISABLED) # Enable collision again obj.set_collision_mode(CollisionMode.NORMAL_3D)
- get_pose()
Return current position and orientation as Pose object.
Performance optimization:
Kinematic objects (mass=0): Always returns cached pose since position only changes via set_pose(), which updates the cache.
Dynamic objects: Caches within the same simulation timestep to avoid redundant PyBullet API calls. Cache is invalidated when sim_time advances.
- Return type:
Pose
- set_pose(pose, preserve_velocity=True)
Set position and orientation from a Pose object.
Two-phase step behaviour (see
docs/design/two-phase-step/spec.md):Outside ``step_once()`` (immediate path): writes to PyBullet via
resetBasePositionAndOrientationand, for kinematic objects, refreshes the AABB + spatial grid immediately. Same behaviour as legacy callers.Inside ``step_once()`` (buffered path,
sim_core._in_step == True): updates only the internal pose cache and registers this object for the Phase 2 / Phase 3 batch flush.get_pose()returns the new pose immediately (cache is the source of truth), but PyBullet’s view, AABBs, and the spatial grid are not refreshed until the flush runs later in the samestep_once()invocation. A no-op set_pose (same pose as cache) is skipped entirely with zero PyBullet cost.
Attached children (base-link attachments) are propagated recursively through the same code path — so they take the buffered path inside the step and the immediate path outside it.
- Parameters:
pose (
Pose) – Pose object containing position and orientationpreserve_velocity (
bool) – If True, preserve current velocity after setting pose. If False, velocity is reset to zero (default behavior of PyBullet). For kinematic objects (mass=0), velocity preservation has no effect, so this is automatically set to False for performance.
- Return type:
- Returns:
True if the object moved (position or orientation changed), False otherwise
- set_pose_raw(position, orientation, preserve_velocity=True)
Set position and orientation from raw lists/tuples (no Pose allocation).
This is the fast path for internal use where position and orientation are already available as lists/tuples, avoiding Pose object creation overhead.
- attach_object(obj, parent_link_index=-1, relative_pose=None, joint_type=4, keep_world_pose=False)
Attach another SimObject to this object.
- Parameters:
obj (
SimObject) – Object to attachparent_link_index (
Union[int,str]) – Link index (int) or link name (str) to attach to. -1 or"base_link"for the base link.relative_pose (
Optional[Pose]) – Position and orientation offset in parent link’s frame as Pose object (default: None, which uses Pose(position=[0, 0, 0], orientation=[0, 0, 0, 1]))joint_type (
int) – PyBullet joint type (default: JOINT_FIXED)keep_world_pose (
bool) – If True, automatically computerelative_poseso that the child keeps its current world position and orientation. Cannot be combined with an explicitrelative_pose.
- Return type:
- Returns:
True if attachment successful, False otherwise
- Raises:
ValueError – If both
relative_poseandkeep_world_pose=Trueare specified.
Example:
# Attach to base link at 0.5m in front agent.attach_object(pallet, relative_pose=Pose.from_xyz(0.5, 0, 0)) # Keep the child where it currently is in the world agent.attach_object(box, parent_link_index=2, keep_world_pose=True) # Attach to specific link by name agent.attach_object(box, parent_link_index="end_effector")
- detach_object(obj, drop_pose=None, drop_relative_pose=None)
Detach an object from this object.
After detaching, the object can optionally be teleported:
drop_pose— absolute world pose.drop_relative_pose— offset applied to the object’s current (pre-detach) world pose (position and orientation are composed viamultiplyTransforms).Neither — the object stays at its current world position.
These two parameters are mutually exclusive.
- Parameters:
obj (
SimObject) – Object to detachdrop_pose (
Optional[Pose]) – Absolute world pose to teleport the object to after detaching. Mutually exclusive withdrop_relative_pose.drop_relative_pose (
Optional[Pose]) – Pose offset relative to the object’s current (pre-detach) world pose. Mutually exclusive withdrop_pose.
- Return type:
- Returns:
True if detachment successful, False otherwise
- Raises:
ValueError – If both
drop_poseanddrop_relative_poseare specified.
Example:
# Detach and leave in place agent.detach_object(pallet) # Detach and place at absolute world position agent.detach_object(pallet, drop_pose=Pose.from_xyz(10, 5, 0.1)) # Detach and offset from current position (e.g. lower by 0.5m) agent.detach_object(pallet, drop_relative_pose=Pose.from_xyz(0, 0, -0.5))
- get_attached_objects()
Return list of objects attached to this object.
- Return type:
List[SimObject]- Returns:
List of attached SimObject instances
- get_kinematic_attachment_state()
Describe a supported physics-off attachment without runtime body IDs.
- property pickable: bool
Whether another object may attach this one (pick it up).
- is_attached()
Check if this object is attached to another object.
- Return type:
- Returns:
True if attached to another object, False otherwise
- find_nearest_pickable(search_radius=1.0)
Find the nearest pickable, unattached SimObject within radius.
Convenience wrapper around
tools.find_nearest()that searches from this object’s current position with the standardpickable and not attachedfilter.Distance is measured from each object’s base origin, as before. The candidates come through the collision spatial hash, so the cost follows how crowded the search area is rather than how many objects the simulation holds; objects whose shape sits far off their origin are tracked separately and are still found.
- register_callback(callback, frequency=0.25)
Register a callback function to be executed periodically.
- execute_callbacks(current_time)
Execute registered callbacks based on their frequency.
- class pybullet_fleet.UsdImportDiagnostic(severity, code, message, prim_path=None, schema_type=None, asset_path=None)
Bases:
objectA JSON-serializable diagnostic emitted while importing a USD stage.
- severity: str
- code: str
- message: str
- class pybullet_fleet.UsdImportOptions(collision=True, collision_required=False, include_invisible=False, include_point_instances=True, point_instance_warning=1000, max_point_instances=5000, max_collision_triangles_per_mesh=50000, max_collision_triangles_total=500000, texture_brightness=1.0)
Bases:
objectControls for
load_usd_world().PointInstancer expansion is bounded before any PyBullet bodies are created, preventing a composed warehouse stage from allocating an unbounded number of static meshes.
- collision: bool = True
- collision_required: bool = False
- include_invisible: bool = False
- include_point_instances: bool = True
- point_instance_warning: int = 1000
- max_point_instances: int = 5000
- max_collision_triangles_per_mesh: int = 50000
- max_collision_triangles_total: int = 500000
- texture_brightness: float = 1.0
- class pybullet_fleet.UsdImportReport(source_stage, source_up_axis, source_meters_per_unit, target_convention='Z-up metres', stage_to_pbf_transform='identity', created_object_ids=<factory>, normalized_object_poses=<factory>, normalized_world_transforms=<factory>, object_transform_modes=<factory>, diagnostics=<factory>)
Bases:
objectResult and source metadata for one USD world import.
- source_stage: str
- source_up_axis: str
- source_meters_per_unit: float
- target_convention: str = 'Z-up metres'
- stage_to_pbf_transform: str = 'identity'
- diagnostics: list[UsdImportDiagnostic]
- property objects_created: int
Number of static objects created by the import.
- pybullet_fleet.load_usd_world(usd_path, *, sim_core, options=None)
Load supported OpenUSD meshes as static objects in
sim_core.Supported rigid or uniformly-scaled transforms become the corresponding
SimObject.poseand mesh scale. Other affine transforms are baked into emitted OBJ vertices. Both paths normalize visual and collision geometry through the same single stage-to-PyBullet transform.- Parameters:
usd_path (
str|Path) – Local.usd,.usda,.usdc, or.usdzstage.sim_core (
Any) – ConnectedMultiRobotSimulationCoreto receive the imported static objects. It may be initialized later byrun_simulation(). A custom-step loop should initialize after loading and before its first step.options (
UsdImportOptions|None) – Import controls. Defaults toUsdImportOptions.
- Return type:
UsdImportReport- Returns:
Import report including object IDs keyed by stable USD prim path.
- Raises:
ImportError – If the optional
usddependency is not installed.FileNotFoundError – If
usd_pathdoes not exist.ValueError – If stage metadata is unsupported or cannot be opened.
- class pybullet_fleet.WorkerBehaviorTree(root, blackboard=<factory>, seed=0, tree_id='MainTree', waypoint_sets=<factory>, *, agent, navigation_adapter=None)
Bases:
AgentBehaviorTreeWorker-specific zone selection and wait actions.
- class pybullet_fleet.WorkerActionId(value)
-
Worker-specific portable Action IDs.
- SELECT_GOAL_FROM_WAYPOINT_SET = 'SelectGoalFromWaypointSet'
- WAIT_RANDOM = 'WaitRandom'
- class pybullet_fleet.AgentBehaviorTree(root, blackboard=<factory>, seed=0, tree_id='MainTree', *, agent, navigation_adapter=None)
Bases:
BehaviorTreeCommon behavior-tree actions for mobile PyBulletFleet agents.
- agent: GoalPoseAgent
- navigation_adapter: NavigationAdapter | None = None
- class pybullet_fleet.AgentActionId(value)
-
Portable Action IDs implemented for mobile agents.
- NAVIGATE_TO = 'NavigateTo'
- class pybullet_fleet.BehaviorTree(root, blackboard=<factory>, seed=0, tree_id='MainTree')
Bases:
objectExecute the common strict BehaviorTree.CPP XML profile.
This class has no PyBulletFleet dependency. Subclasses provide only their supported leaf actions; it remains smaller than the full C++ runtime.
- root: Element
- seed: int = 0
- tree_id: str = 'MainTree'
- classmethod from_file(path, *, blackboard=None, seed=0, **subclass_kwargs)
- Return type:
BehaviorTree
- tick(sim_core, _dt)
Simulation callback compatible with
sim.register_callback.- Return type:
- class pybullet_fleet.BehaviorTreeNodeType(value)
-
Control and leaf node tags supported by the portable XML profile.
- SEQUENCE = 'Sequence'
- FALLBACK = 'Fallback'
- REPEAT = 'Repeat'
- ACTION = 'Action'
- class pybullet_fleet.NavigationAdapter(*args, **kwargs)
Bases:
ProtocolBackend-neutral navigation operations used by agent behavior trees.
- start_navigation(goal)
Start navigation toward
goalfor this adapter’s execution target.Return
Falsewhen the target refuses the goal for now (for example, it is moving and cannot turn toward it within its limits); the action then tries again on its next tick.NoneorTruemeans started.
- navigation_status()
Return the lifecycle state of the currently active navigation.
- Return type:
NavigationStatus
- class pybullet_fleet.NavigationStatus(value)
-
Portable lifecycle outcomes for one navigation request.
- RUNNING = 'running'
- SUCCEEDED = 'succeeded'
- FAILED = 'failed'
- CANCELLED = 'cancelled'
- class pybullet_fleet.PyBulletFleetNavigationAdapter(agent)
Bases:
objectMap portable navigation requests to the existing Agent goal API.
- agent: GoalPoseAgent
- start_navigation(goal)
- Return type:
- navigation_status()
- Return type:
NavigationStatus
- class pybullet_fleet.TickResult(value)
-
Outcomes returned by a behavior-tree node tick.
- SUCCESS = 'success'
- FAILURE = 'failure'
- RUNNING = 'running'
- class pybullet_fleet.EventBus(clock=None)
Bases:
objectLightweight event pub/sub bus.
Usage:
bus = EventBus() bus.on("collision_started", my_handler, priority=0) bus.emit("collision_started", obj_a=a, obj_b=b) bus.off("collision_started", my_handler)
- Parameters:
clock (
Optional[Callable[[],Tuple[float,float]]]) – Returns(now, timestep)for scheduling frequency-limited subscriptions. The simulation’s bus (sim.events) has one; a bus without a clock (a bare or per-entity bus) rejectsfrequency.
An emit calls the subscriptions present when it starts: a handler added or removed by a handler takes effect from the next emit.
- on(event, handler, priority=0, frequency=None)
Register
handlerforevent. Lowerpriorityruns first; equal ones in registration order.- Parameters:
event (
str) – Event name, aSimEventsconstant or any string.handler (
Callable) – Called with the event’s keyword arguments.priority (
int) – Order among this event’s handlers (lower = first).frequency (
Optional[float]) – Rate in Hz, for the step events (pre_step,step,post_step) on a bus with a clock. The handler then runs on a fixed grid ofk / frequencyseconds of simulated time (asregister_callback(frequency=...)does), scheduled on the time it observes, and itsdtis the simulated time since it last ran.Noneor0runs it on every emit, as0does forregister_callback().
- Raises:
ValueError –
frequencyis negative or not finite, is given for an event other than a step event, or the bus has no clock.- Return type:
- off(event, handler)
Unregister
handlerfromevent(every registration of it made withon()).- Return type:
- emit(event, **kwargs)
Fire event. Handlers called in priority order, then callbacks, then plugins.
The simulation emits the step events (
pre_step,step,post_step) once per step. Emitting one onsim.eventsyourself runs everything subscribed to it,register_callback()callbacks and pluginon_step()included, uses up the due beats of the frequency-limited ones, and lets a callback’s exception propagate.- Return type:
- clear(event=None)
Remove the handlers registered with
on(); foreventonly when given.Callbacks and plugins the simulation subscribed are kept.
- Return type:
- has_handlers(event)
Whether emitting
eventwould call anything (handlers, callbacks or plugins).- Return type:
- class pybullet_fleet.SimEvents
Bases:
objectPre-defined event name constants.
Using these constants prevents typos and enables IDE auto-completion, while the
EventBusstill accepts anystrfor user-defined events.Simulation lifecycle (emitted on
sim.events):sim.events.on(SimEvents.PRE_STEP, handler) sim.events.on(SimEvents.POST_STEP, handler)
Entity lifecycle (emitted on both
sim.eventsandentity.events):sim.events.on(SimEvents.OBJECT_SPAWNED, handler) agent.events.on(SimEvents.ACTION_COMPLETED, handler)
Custom events (any string — no constant needed):
sim.events.on("my_plugin_event", handler)
- PRE_STEP: str = 'pre_step'
dt,sim_time(the time of the previous state).- Type:
Emitted at the start of each step, before the clock advances. kwargs
- STEP: str = 'step'
Emitted after the objects have been updated, before their new poses are written to PyBullet and before the collision check – the point where
register_callback()callbacks run by default. kwargs:dt,sim_time(the time of the new state).
- POST_STEP: str = 'post_step'
dt,sim_time.- Type:
Emitted at the end of each step. kwargs
- PAUSED: str = 'paused'
Emitted when simulation is paused. No kwargs.
- RESUMED: str = 'resumed'
Emitted when simulation is resumed. No kwargs.
- OBJECT_SPAWNED: str = 'object_spawned'
no kwargs.
- Type:
Global
- Type:
obj. Per-entity
- OBJECT_REMOVED: str = 'object_removed'
no kwargs.
- Type:
Global
- Type:
obj. Per-entity
- AGENT_SPAWNED: str = 'agent_spawned'
agent.- Type:
Global only
- AGENT_REMOVED: str = 'agent_removed'
agent.- Type:
Global only
- COLLISION_STARTED: str = 'collision_started'
other.- Type:
Global
- Type:
obj_a,obj_b. Per-entity
- COLLISION_ENDED: str = 'collision_ended'
other.- Type:
Global
- Type:
obj_a,obj_b. Per-entity
- PRE_UPDATE: str = 'pre_update'
dt. Emitted before agent movement/action processing.- Type:
Per-entity only
- POST_UPDATE: str = 'post_update'
dt,moved(bool). Emitted after agent update completes.- Type:
Per-entity only
- ACTION_STARTED: str = 'action_started'
action.- Type:
Global
- Type:
agent,action. Per-entity
- ACTION_COMPLETED: str = 'action_completed'
action,status.- Type:
Global
- Type:
agent,action,status. Per-entity
- class pybullet_fleet.Agent(body_id, urdf_path=None, motion_mode=MotionMode.DIFFERENTIAL, use_fixed_base=False, collision_mode=CollisionMode.NORMAL_3D, sim_core=None, name=None, user_data=None, mass=None, ik_params=None, joint_tolerance=None, controller=None, notify_spawn=True, pickable=False)
Bases:
SimObjectAgent class with goal-based position control.
Inherits from SimObject to get attach/detach and callback functionality. Supports both mobile robots (use_fixed_base=False) and fixed robots (use_fixed_base=True). Supports both Mesh and URDF loading.
- Class Attributes:
- _spawn_params_cls: The SpawnParams dataclass used by config-driven
grid spawning (
AgentSpawnParams).
- Class Constants:
- _KINEMATIC_JOINT_FALLBACK_VELOCITY: Default max joint velocity for
revolute joints (rad/s) used when the URDF
<limit velocity="...">is 0 or missing.- _KINEMATIC_PRISMATIC_FALLBACK_VELOCITY: Default max joint velocity
for prismatic joints (m/s) used when the URDF limit is 0 or missing.
- _DEFAULT_JOINT_TOLERANCE: Default tolerance (rad / m) for joint
target comparison methods.
Features: - Accepts Pose goals (compatible with ROS2 geometry_msgs/Pose) - Max velocity and acceleration constraints (for mobile robots) - Current pose query API - Shared shape optimization for fast spawning - Fixed robot support (non-moving objects) - URDF support with joint control - Attach/detach objects (inherited from SimObject)
Object Identification (inherited from SimObject): - object_id: Unique integer ID (assigned by sim_core, use for lookups) - name: Optional string name (duplicates allowed, use for debugging/filtering)
This class is designed to be eventually controlled by ROS2 nodes, so the API follows ROS message conventions.
- __init__(body_id, urdf_path=None, motion_mode=MotionMode.DIFFERENTIAL, use_fixed_base=False, collision_mode=CollisionMode.NORMAL_3D, sim_core=None, name=None, user_data=None, mass=None, ik_params=None, joint_tolerance=None, controller=None, notify_spawn=True, pickable=False)
Initialize Agent.
- Parameters:
body_id (
int) – PyBullet body IDurdf_path (
Optional[str]) – Path to robot URDF file (if URDF-based)motion_mode (
Union[MotionMode,str]) –MotionMode.OMNIDIRECTIONAL or MotionMode.DIFFERENTIAL drive. Used as the default controller selector when
controllerhas no"type"key. Ifcontroller={"type": ...}is given and disagrees withmotion_mode, a warning is logged andcontroller.typewins.Deprecated since version Prefer:
controller="omni"/controller="differential"(or a fullcontroller={...}dict).motion_modeis retained for backward compatibility and as a coarse “2D mobile base shape” hint for batched controllers.use_fixed_base (
bool) – If True, robot base is fixed and doesn’t movecollision_mode (
CollisionMode) – Collision detection mode (default: NORMAL_3D)sim_core – Reference to simulation core (optional)
ik_params (
Optional[IKParams]) – IK solver configuration (default:IKParams()).joint_tolerance (
Union[float,list,dict,None]) – Default joint tolerance for convergence checks. Acceptsfloat(all joints),list(per-joint), ordict({joint_name: tol}). IfNone, uses the class default (0.01). For mixed prismatic / revolute chains, a dict is recommended so prismatic joints (metres) can use a tighter tolerance than revolute joints (radians).controller (
Union[str,Dict[str,Any],ControllerParams,Controller,None]) –Controller selector / configuration. Accepts:
None— framework defaults;motion_modeselectsOmniControllerorDifferentialController.str— registry name, e.g."omni","differential","patrol". Equivalent to{"type": <str>}.dict—{"type": "...", "max_linear_vel": 1.5, "wheel_separation": 0.3, ...}.ControllerParamsfields populateControllerParams; impl-specific extras (e.g.wheel_separation) flow through to the controller’s__init__. Recommended for YAML / config-file workflows.Controllerinstance — any pre-built controller (built-in or custom). Installed as-is;self.controller_paramsis taken fromcontroller.params. Recommended for Python workflows that need custom controllers or want type-safe construction.ControllerParamsinstance — params only;motion_modestill picks the Omni/Diff class. Use this only when you want to tweak shared params but keep the default class.
Note
For spawning robots from AgentSpawnParams, use Agent.from_params() instead. For mesh robots, use Agent.from_mesh() factory method. For URDF robots, use Agent.from_urdf() factory method.
- path_visualize: bool
- path_visualize_width: float
- controller_params: ControllerParams
- property max_linear_vel: ndarray
- property max_linear_accel: ndarray
- property max_linear_decel: ndarray
Effective deceleration limit; mirrors
max_linear_accelwhen unset.
- property max_angular_vel: ndarray
- property max_angular_accel: ndarray
- property max_angular_decel: ndarray
Effective angular deceleration limit; mirrors
max_angular_accelwhen unset.
- property joint_tolerance: float | list | dict
Default joint tolerance used by convergence checks.
Returns the instance-level tolerance if set, otherwise the class default (
_DEFAULT_JOINT_TOLERANCE = 0.01).For robots with mixed prismatic (metres) and revolute (radians) joints, set this to a
dictso each joint type can have an appropriate tolerance:agent = Agent.from_urdf( ..., joint_tolerance={"rail_joint": 0.005, "elbow_to_wrist": 0.05}, )
- property is_moving: bool
Check if robot is currently moving.
To change movement state, use set_goal_pose(), set_path(), or stop().
- Returns:
True if robot is moving, False otherwise
- Type:
Read-only property
- property battery_soc: float
Current state of charge [0.0, 1.0].
Always returns
1.0when noBatteryPluginis attached.
- property is_charging: bool
Whether the agent is currently charging.
- property battery_plugin
The
BatteryPlugininstance, orNone.
- set_charging(charging)
Start or stop charging.
- property plugins: List[AgentPlugin]
Read-only list of active per-agent plugins.
- add_plugin(plugin)
Attach a per-agent plugin.
- Parameters:
plugin (
AgentPlugin) – AnAgentPlugininstance bound to this agent.- Raises:
ValueError – If plugin is not bound to this agent.
- Return type:
- remove_plugin(plugin_or_cls)
Remove a plugin by instance or class.
When a class is given, the first instance of that class is removed. When an instance is given, that exact instance is removed.
- Parameters:
plugin_or_cls – An
AgentPlugininstance or subclass.- Return type:
- get_plugin(cls)
Return the first plugin matching cls, or
None.
- property motion_mode: MotionMode
Get current motion mode.
To change motion mode, use set_motion_mode() method.
- Returns:
Current MotionMode (OMNIDIRECTIONAL or DIFFERENTIAL)
- Type:
Read-only property
- property velocity: ndarray
Get current velocity vector.
- Returns:
Velocity [vx, vy, vz] in m/s (copy of internal state)
- Type:
Read-only property
- property angular_velocity: float
Get current angular velocity.
- Returns:
Angular velocity in rad/s
- Type:
Read-only property
- property goal_pose: Pose | None
Get current goal pose.
To set a new goal, use set_goal_pose() or set_path().
- Returns:
Current goal Pose, or None if no goal is set
- Type:
Read-only property
- property current_waypoint_index: int
Get current waypoint index in the path.
- Returns:
Current waypoint index (0-based), or 0 if no path is set
- Type:
Read-only property
- property path: List[Pose]
Current waypoint path. Empty when idle.
- Type:
Read-only property
- classmethod from_params(spawn_params, sim_core=None)
Create an Agent from AgentSpawnParams.
This is the recommended way to spawn robots when using AgentSpawnParams. Automatically detects whether to use mesh, URDF, or virtual agent based on spawn_params.
- Parameters:
spawn_params (
AgentSpawnParams) – AgentSpawnParams instance with all robot parameterssim_core – Reference to simulation core (optional)
- Return type:
Agent- Returns:
Agent instance
The recommended way to choose a controller is to set
controller={"type": "omni" | "differential" | ...}explicitly.motion_modestill works as a shortcut and as the default whencontroller.typeis omitted, but if both are given,controller.typewins and a warning is emitted on mismatch.Example (Mesh, omni — recommended explicit form):
params = AgentSpawnParams( visual_shape=ShapeParams( shape_type="mesh", mesh_path="robot.obj", mesh_scale=[1.0, 1.0, 1.0], rgba_color=[0.2, 0.2, 0.2, 1.0] ), collision_shape=ShapeParams( shape_type="box", half_extents=[0.2, 0.1, 0.2] ), initial_pose=Pose.from_xyz(1.0, 2.0, 0.0), controller={"type": "omni", "max_linear_vel": 3.0}, ) robot = Agent.from_params(spawn_params=params)
Example (URDF):
params = AgentSpawnParams( urdf_path="arm_robot.urdf", initial_pose=Pose.from_xyz(0.0, 0.0, 0.0), use_fixed_base=True, ) robot = Agent.from_params(spawn_params=params)
Example (Virtual Agent - invisible, no collision):
params = AgentSpawnParams( initial_pose=Pose.from_xyz(0.0, 0.0, 0.0), controller={"type": "omni", "max_linear_vel": 2.0}, ) virtual_agent = Agent.from_params(spawn_params=params)
- classmethod from_dict(config, sim_core=None)
Create an Agent from a raw config dict.
Combines
AgentSpawnParams.from_dict()andfrom_params()in a single call. Usescls._spawn_params_clsso subclasses (e.g. Door, Elevator) automatically use their own SpawnParams.
- classmethod from_mesh(visual_shape=None, collision_shape=None, pose=None, mass=0.0, motion_mode=MotionMode.DIFFERENTIAL, use_fixed_base=False, collision_mode=CollisionMode.NORMAL_3D, sim_core=None, name=None, user_data=None, controller=None, notify_spawn=True, pickable=False)
Create a mesh-based Agent with flexible shape control.
- Parameters:
visual_shape (
Optional[ShapeParams]) – ShapeParams for visual geometrycollision_shape (
Optional[ShapeParams]) – ShapeParams for collision geometrypose (
Pose) – Initial Pose (position and orientation)mass (
float) – Robot mass (kg), 0.0 for kinematic controlmotion_mode (
Union[MotionMode,str]) – MotionMode.OMNIDIRECTIONAL or MotionMode.DIFFERENTIALuse_fixed_base (
bool) – If True, robot base is fixed and doesn’t movesim_core – Reference to simulation core
controller (
Union[str,Dict[str,Any],ControllerParams,Controller,None]) – Controller selector / config. SeeAgent.__init__()for accepted forms (None/str/dict/ControllerParams).
- Return type:
Agent- Returns:
Agent instance
- classmethod from_urdf(urdf_path, pose=None, mass=None, motion_mode=MotionMode.DIFFERENTIAL, use_fixed_base=False, collision_mode=CollisionMode.NORMAL_3D, sim_core=None, name=None, user_data=None, ik_params=None, joint_tolerance=None, controller=None, notify_spawn=True, global_scaling=1.0, pickable=False)
Create a URDF-based Agent (with joints).
- Parameters:
urdf_path (
str) – Robot model name (e.g."panda") or path to URDF file. Names are resolved viaresolve_model()pose (
Pose) – Initial Pose (position and orientation). Defaults to originmass (
Optional[float]) – Mass override. - None (default): Use URDF file’s mass values as-is - 0.0: Override all links to mass=0 for kinematic control (no physics)motion_mode (
Union[MotionMode,str]) – MotionMode.OMNIDIRECTIONAL or MotionMode.DIFFERENTIALuse_fixed_base (
bool) – If True, robot base is fixed in spaceglobal_scaling (
float) – Uniform scale factor applied when loading.pickable (
bool) – Whether the agent may be attached to another body (default: False – a robot is usually the one doing the picking).attach_object()refuses a non-pickable body.sim_core – Reference to simulation core
ik_params (
Optional[IKParams]) – IK solver configuration (default:IKParams()).joint_tolerance (
Union[float,list,dict,None]) – Default joint tolerance for convergence. Seejoint_toleranceproperty for details.controller (
Union[str,Dict[str,Any],ControllerParams,Controller,None]) – Controller selector / config. SeeAgent.__init__()for accepted forms (None/str/dict/ControllerParams).
- Return type:
Agent- Returns:
Agent instance
Note
mass=None (default): Uses URDF file’s mass values for physics simulation
mass=0.0: Override all links to mass=0 for kinematic control (no physics)
Example:
robot = Agent.from_urdf(urdf_path="arm_robot.urdf") robot = Agent.from_urdf(urdf_path="panda", use_fixed_base=True) robot = Agent.from_urdf(urdf_path="arm_robot.urdf", mass=0.0)
- set_goal_pose(goal, direction=None)
Set goal pose for the robot to move to.
Note: This is ignored if the robot has a fixed base.
- brake()
Come to rest along the current direction of travel at the configured deceleration.
A deceleration-limited counterpart of
stop(), which zeroes the velocity at once (an emergency stop). The agent keeps its heading and its line of motion and stops at the braking point,|v|^2 / (2 * decel)ahead, decelerating at exactly the configured rate along that direction (the same projected limits a trajectory uses). The remaining path and any queued waypoints are dropped; a velocity command (the controller’sset_velocity) is ended the same way.A differential-drive agent brakes straight along its heading (backing up, it brakes backwards). A path set while it brakes is handled like any path set while moving (see
set_path()); a pending path from an earlierbrakeorwait_completereplacement is dropped.The action queue is left alone, but does not run on while the agent brakes. A
MoveActionstill executing endsCANCELLEDon its next update – its request is gone once the braking path replaces it – and the queue waits until the agent is at rest before starting the next action; callclear_actions()first to drop the queued actions too.The agent’s controller does the braking (its
brake()); a custom controller changes how the agent brakes by overridingKinematicController.braking_request, whichgoal_replacement="brake"uses too.- Return type:
- Returns:
Truewhen a braking trajectory was set.Falseat rest, for a fixed-base robot, and for a controller that cannot brake.
- path_rejection(path, direction=None)
Why
set_path()would refusepathright now, orNone.A
PathRejection:reasonsays why,temporarywhether it lasts only until the current motion ends (a fixed-base robot and an empty path are permanent).Only
goal_replacement="reject"refuses a path that cannot continue the current motion (seeset_path()); the other modes take every path. Asking first lets a caller report a refusal before acting.directionis the oneset_path()would be given.- Return type:
Optional[PathRejection]
- set_motion_mode(mode)
Set motion mode for the robot.
Replaces the active controller with the matching default (OmniController or DifferentialController). Any custom controller previously installed via
controller.typeis lost.Note: Motion mode cannot be changed while the robot is moving.
Deprecated since version Prefer:
agent.set_controller(create_controller(name, cfg))for runtime controller swaps.set_motion_modeis kept for backward compatibility and only handles the built-in Omni / Differential defaults.
- set_path(path, auto_approach=True, final_orientation_align=True, direction=None, _preempt=False)
Set a path (list of waypoints) for the robot to follow.
A path set while the agent is moving continues the motion when it can: the straight-line trajectory to the first waypoint starts from the agent’s current velocity (signed along the line, so a goal behind is reached by slowing and reversing). It cannot for a goal inside the braking distance, where the agent is, off the line of motion, or – differential drive – one that needs a turn in place. Such a path is handled as the controller’s
goal_replacementsetting says (GoalReplacement):brake(the default) brakes at the configured deceleration and then starts it,wait_completefinishes the current path first (it holds every path set while one is in progress, reachable or not),immediatestarts it from rest at once, andrejectrefuses it – nothing changes, the current motion continues, and this returnsFalse(the reason is logged and available frompath_rejection()). At rest every path is taken.- Parameters:
path (
List[Pose]) – List of Pose waypoints to follow in sequenceauto_approach (
bool) – If True, automatically add straight-line approach from current position to first waypoint if distance > threshold (default: True)final_orientation_align (
bool) – If True, add final rotation to match last waypoint’s orientation after reaching the position (default: True)direction (
Union[MovementDirection,str,None]) – Movement direction override, orNoneto use the controller’sdefault_direction. Can be MovementDirection enum or string (“auto”, “forward”, “backward”). Only used in differential drive mode (MotionMode.DIFFERENTIAL). In omnidirectional mode, this parameter is ignored._preempt (
bool) – Internal: start without waiting for the current path underwait_complete(used bybrake()), for every kinematic controller, omnidirectional or differential, per-agent or batched.
- Return type:
- Returns:
Truewhen the path was taken (started or held to start later);Falsefor a fixed-base robot, an empty path, or a path refused undergoal_replacement="reject".
- request_path(request, _preempt=False, _internal=False)
Follow
request: the core ofset_path(), which builds one from its arguments.The same rules as
set_path(): a path set while moving continues the motion when it can, and otherwise the controller’sgoal_replacementdecides.request.auto_approachputs the current pose in front of the path when the agent is at rest and more than 0.5 m from the first waypoint; the request reaches the controller as a copy that keeps its identity, sopath_request_state()can tell what became of it.- Parameters:
- Return type:
- Returns:
Truewhen the path was taken (started or held to start later);Falsefor a fixed-base robot, an empty path, or a path refused undergoal_replacement="reject".
- path_request_state(request)
What became of
request(sent withrequest_path()): being followed, held, followed to its end, or gone – replaced by another request, dropped from the hold, stopped, braked or cancelled.UNKNOWNfor a controller that does not track requests, and for a request aset_pathoverride did not pass on (it sent one of its own instead).- Return type:
PathRequestState
- add_action(action)
Add an action to the execution queue.
Actions are executed sequentially in the order they are added.
- Parameters:
action (
Action) – Action instance to add to queue
Example:
agent.add_action(MoveAction(path=my_path)) agent.add_action(WaitAction(duration=5.0))
- add_action_sequence(actions)
Add multiple actions to the execution queue.
- Parameters:
actions (
List[Action]) – List of Action instances to add
Example:
agent.add_action_sequence([ MoveAction(path=path1), PickAction(target_object_id=obj.body_id), MoveAction(path=path2), DropAction(drop_pose=Pose(position=[10, 5, 0])) ])
- clear_actions()
Clear all actions from the queue and cancel current action.
- get_current_action()
Get the currently executing action.
- Return type:
Optional[Action]- Returns:
Current Action instance, or None if no action is executing
- get_action_queue_size()
Get the number of actions waiting in the queue.
- Return type:
- Returns:
Number of actions in queue
- is_action_queue_empty()
Check if action queue is empty and no action is currently executing.
- Return type:
- Returns:
True if no actions are queued or executing, False otherwise
- set_joint_motion_profile(joint, max_velocity=None, max_accel=None, max_decel=None)
Override how fast a kinematic joint moves, and how it gets there.
Without this, a kinematic joint runs at the URDF’s
<limit velocity="...">and reaches it instantly: the speed is a property of the model file, so changing it means editing or regenerating the URDF, andchangeDynamics(maxJointVelocity=...)does not help becausegetJointInfo()keeps reporting the original.Giving
max_accelturns the motion into a trapezoid – ramp up, cruise, ramp down – which is what a real lift, hoist or linear axis does. A 0.6 m travel at 0.4 m/s takes 1.5 s at a constant speed and 1.9 s with 1.0 m/s ramps, so the difference is not cosmetic when something downstream is timing the move.Both are optional and independent. With neither, nothing changes; with
max_velocityalone the joint still steps instantly to that speed, exactly as before.Every argument left at
Nonekeeps what the joint already has, so this can be called again to change one of them. A ramp cannot be taken off a joint once it has one.Can be called while the joint is moving. The speed it is carrying is kept and the next step re-plans from it under the new limits, so the change is continuous; if the new limits can no longer stop the joint at its target it brakes and comes back, as for any other target it cannot reach.
- Parameters:
joint (
Union[int,str]) – Joint index, or joint name as spelled in the URDF.max_velocity (
Optional[float]) – Speed cap, replacing the URDF limit.Nonekeeps whatever the joint already uses.max_accel (
Optional[float]) – Acceleration, in units/s^2.Nonekeeps the acceleration the joint already has, and means no ramp only when it has none.max_decel (
Optional[float]) – Deceleration.Nonekeeps the current one, or followsmax_accelwhen that is given. On its own it changes the braking rate of a joint that already ramps.
- Raises:
KeyError – If joint names a joint this body does not have.
IndexError – If joint is an index this body does not have.
ValueError – If any value given is not positive, or if
max_decelis given for a joint with no acceleration.
- Return type:
- is_joint_moving(joint)
Whether a ramped joint is still in motion.
An action reports complete once the joint is inside its tolerance, which a ramped joint reaches while still braking through the last fraction of a millimetre. Anything that has to know the joint has actually stopped – a lift releasing its passengers, say – needs this rather than the action’s status.
True while the joint is following a trajectory, while it is braking with none to follow, and while it is between the two: changing a motion profile voids the trajectory it was solved against but not the speed the joint is carrying, and the replacement is not planned until the next step. A joint that is only carrying speed is as much in motion as one with a plan, which is why this asks about the motion rather than about the trajectory.
- Parameters:
joint (
Union[int,str]) – Joint index, or joint name as spelled in the URDF.- Raises:
KeyError – If joint names a joint this body does not have.
IndexError – If joint is an index this body does not have.
- Return type:
- update(dt)
Update robot position towards goal with velocity/acceleration constraints.
Supports two motion modes: - MotionMode.OMNIDIRECTIONAL: Move in any direction without rotating first (smooth trajectories) - MotionMode.DIFFERENTIAL: Rotate to face target, then move forward (smooth trajectories)
Also processes action queue for high-level task execution.
Note: This does nothing if the robot has a fixed base.
- get_velocity()
Get current velocity vector.
- Return type:
- Returns:
Velocity [vx, vy, vz] in m/s
- restore_motion_state(pose, linear_velocity, angular_velocity, *, moving)
Restore Agent-owned motion fields; restore controller execution separately.
- Return type:
- set_controller(controller=None)
Set or replace the base (index-0) movement controller.
When a controller is set,
update()delegates movement tocontroller.compute(agent, dt).A controller that carries its own
ControllerParamsalso becomes this agent’scontroller_params, which is whatAgent.__init__does when the controller is passed at construction. Without that the two diverge silently: the controller moves the agent by its own limits whilecontroller_params– the single source of truth thatmax_linear_veland its siblings delegate to, and that a batch controller builds its trajectory from – still holds whatever was there before, usually the defaults.Note: A default controller is always assigned in
from_params(). SettingNonedisables all movement and leavescontroller_paramsas it is, since there are then no limits to take.
- add_controller(controller)
Append a high-level controller to the chain.
High-level controllers (patrol, random walk) are executed before the base navigation controller in
update().- Parameters:
controller – A
Controllerinstance.- Return type:
- remove_controller(controller_or_cls)
Remove a non-base controller by instance or class.
The base controller (index 0) cannot be removed via this method. Use
set_controller()to replace it.When a class is given, the first instance of that class (excluding the base controller) is removed. When an instance is given, that exact instance is removed.
- Parameters:
controller_or_cls – A Controller instance or subclass.
- Return type:
- get_controller_by_type(cls)
Return the first controller matching cls, or
None.Searches the entire chain (including the base controller).
- property controller
Return the base (index-0) controller, or
Noneif the chain is empty.
- stop()
Stop robot movement and clear goal and path.
- is_urdf_robot()
Check if this robot is URDF-based (has joints).
- Return type:
- get_num_joints()
Get number of joints (0 for mesh robots).
- Return type:
- get_joint_state(joint)
Get joint state (position and velocity).
For kinematic robots (mass=0), returns the cached position and velocity=0.0, avoiding a PyBullet C call. For physics robots the value is read from
p.getJointState().Works for a fixed joint as for any other.
- Parameters:
joint (
Union[int,str]) – Joint index (0-based), or joint name as spelled in the URDF. The old keywordjoint_index=is still accepted.- Return type:
- Returns:
(position, velocity) tuple;
(0.0, 0.0)with a warning for a non-URDF body or an unknown joint name.- Raises:
pybullet.error – If joint is an index this body does not have.
Example:
pos, vel = robot.get_joint_state(0) pos, vel = robot.get_joint_state("elbow_to_wrist")
- get_joint_state_by_name(joint_name)
Get (position, velocity) for a single joint by name. Returns (position, velocity) or (0.0, 0.0) if not found.
Deprecated, removed in 0.10.0: use
get_joint_state(), which also takes a name.- Return type:
- capture_kinematic_joint_execution()
Capture every joint’s position, command, motion limits and execution.
A solved trajectory is represented by its primitive inputs and how long the joint has followed it (as
t0_offset, its negative). Rebuilding it preserves the phase reached at this completed-step boundary without serializing the TPI instance itself.
- restore_kinematic_joint_execution(states)
Restore joint commands and execution at a completed-step boundary.
- Return type:
- get_all_joints_state()
Return a list of (position, velocity) for all joints. Example: [(pos0, vel0), (pos1, vel1), …]
- Return type:
- get_all_joints_state_by_name()
Return a dict of {joint_name: (position, velocity)} for all joints. Example: {joint_name: (pos, vel), …}
- Return type:
- get_joints_state_by_name(joint_names)
Return a dict of {joint_name: (position, velocity)} for the specified joint_names. Example: {joint_name: (pos, vel), …}
- Return type:
- set_joint_target(joint, target_position, max_force=500.0)
Set target position for a joint (for URDF robots only).
An unknown joint name or an index out of range is ignored with a warning; a fixed joint is ignored silently.
- Parameters:
Example:
robot.set_joint_target(0, 1.57) # Move first joint to 90 degrees robot.set_joint_target("base_to_shoulder", 1.57)
- set_joint_position(joint, position, max_force=500.0)
Put a joint at
positionat once, without moving it there.The joint counterpart of
set_pose(): what a simulator’s “set entity state” asks of a fixed-base mechanism such as a lift cabin, where placing the base would carry the whole mechanism away.positionalso becomes the joint’s target, so the step loop keeps it there instead of resuming a motion towards an older target, and any speed or plan from a motion profile is dropped. Objects attached to the robot’s links follow at once, and the body counts as moved for the next collision check. An action still driving this joint is not cancelled; cancel it first if it should not move the joint again.A position outside the joint’s URDF limits is applied, with a warning.
- Parameters:
- Return type:
- Returns:
True if the joint was set; False for a non-URDF body, an unknown or fixed joint.
- set_joints_positions(positions, max_force=500.0)
Put several joints at their positions at once, as
set_joint_position()does for one.Accepts what
set_joints_targets()accepts: a list with a position for every joint, in joint-index order (a fixed joint’s entry is ignored), or a dict{joint name or index: position}for some of them. Attached objects follow once, after every joint is placed.- Return type:
- Returns:
True if every given joint was set; False for a non-URDF body, a list of the wrong length (nothing is set), or a dict naming an unknown or fixed joint (the others are still set).
- set_joint_target_by_name(joint_name, target_position, max_force=500.0)
Set target position for a joint by joint name.
Deprecated, removed in 0.10.0: use
set_joint_target(), which also takes a name.
- set_all_joints_targets(target_positions, max_force=500.0)
Set target positions for all joints at once.
- Parameters:
Example:
robot.set_all_joints_targets([0.0, 1.57, -1.57, 0.0])
- set_joints_targets_by_name(joint_targets, max_force=500.0)
Set multiple joint targets by dict {joint_name: target_position} (partial update allowed).
- set_joints_targets(targets, max_force=500.0)
Set joint targets (accepts both list and dict).
- Parameters:
Example:
# Using list robot.set_joints_targets([0.0, 1.57, -1.57, 0.0]) # Using dict robot.set_joints_targets({"joint1": 1.57, "joint2": -1.57})
- is_joint_at_target(joint, target, tolerance=None)
Check if a single joint is within tolerance of the target position.
- Parameters:
joint (
Union[int,str]) – Joint index (0-based), or joint name as spelled in the URDF. The old keywordjoint_index=is still accepted.target (
float) – Target position (radians for revolute, metres for prismatic).tolerance (
Union[float,list,dict,None]) – Position tolerance —float,list,dict, orNone(→self.joint_tolerance). Resolved via_resolve_joint_tolerance()using the joint’s index.
- Return type:
- Returns:
True if the joint is within tolerance; False, with a warning, for a non-URDF body, an unknown joint name or an index out of range.
- is_joint_at_target_by_name(joint_name, target, tolerance=None)
Check if a single joint (by name) is within tolerance of the target position.
- Parameters:
joint_name (
str) – Joint name string.target (
float) – Target position (radians for revolute, metres for prismatic).tolerance (
Union[float,list,dict,None]) – Position tolerance —float,list,dict, orNone(→self.joint_tolerance). Resolved via_resolve_joint_tolerance()using the joint’s index.
- Return type:
Deprecated, removed in 0.10.0: use
is_joint_at_target(), which also takes a name.
- are_all_joints_at_targets(target_positions=None, tolerance=None)
Check if joints are at target positions.
- Parameters:
target_positions (
Optional[list]) – List of target positions for each joint. If None, uses the last commanded targets.tolerance (
Union[float,list,dict,None]) –float,list,dict, orNone. If None, usesself.joint_tolerance. Passed through to_resolve_joint_tolerance()per joint.Note
A scalar tolerance applies the same value to all joints. For mixed prismatic (metres) / revolute (radians) robots, consider a
dictkeyed by joint name or setself.joint_toleranceto a dict.
- Return type:
- Returns:
True if all joints are within tolerance of their targets.
- are_joints_at_targets_by_name(joint_targets, tolerance=None)
Check if all specified joints (by name) are within tolerance.
- Parameters:
joint_targets (
dict) –{joint_name: target}tolerance (
Union[float,list,dict,None]) –float(all),dict({joint_name: tol}), orNone(→self.joint_tolerance).A
listis also accepted but is resolved by absolute joint index (not by iteration order of joint_targets). For named-joint subsets, prefer adictto avoid unexpected index-based fallback.For mixed prismatic / revolute chains, use a
dictso prismatic joints (metres) can have a tighter tolerance than revolute joints (radians).
- Return type:
- Returns:
True if all joints are within tolerance, False otherwise.
- are_joints_at_targets(targets=None, tolerance=None)
Check if joints are at target positions.
- Parameters:
targets (
Union[list,dict,None]) – List of target positions for all joints, dict{joint_name: position}, or None to use the last commanded targets.tolerance (
Union[float,list,dict,None]) –Tolerance value(s) —
float,list,dict, or None (→self.joint_tolerance).For mixed prismatic / revolute chains, use a
dictso prismatic joints (metres) can have a tighter tolerance than revolute joints (radians):agent.are_joints_at_targets( targets, tolerance={"rail_joint": 0.005, "elbow_to_wrist": 0.05}, )
- Return type:
- Returns:
True if all joints are within tolerance, False otherwise.
Example:
# No args — check last commanded targets with agent's default tolerance if robot.are_joints_at_targets(): print("All joints settled") # Using list if robot.are_joints_at_targets([0.0, 1.57, -1.57, 0.0], tolerance=0.01): print("Reached target") # Using dict if robot.are_joints_at_targets({"joint1": 1.57, "joint2": -1.57}, tolerance=0.01): print("Reached target")
- property ik_params: IKParams
Read-only access to the IK solver configuration.
- move_end_effector(target_position, target_orientation=None, end_effector_link=None, max_force=500.0, tolerance=None)
Set end-effector target position via inverse kinematics.
Solves IK, checks reachability, and calls
set_all_joints_targets()internally. Actual movement happens inupdate()(fire-and-forget, likeset_joint_target()).When the solver returns an IK candidate, its joint targets are set even when the target is unreachable (best-effort). If no candidate is available, no new joint target is issued. The return value tells the caller whether the IK solution actually reaches the desired position.
- Parameters:
target_position (
List[float]) – Target EE position [x, y, z] in world frame.target_orientation (
Optional[Tuple[float,float,float,float]]) – Target EE orientation as quaternion [qx, qy, qz, qw].end_effector_link (
Union[int,str,None]) – End-effector link (int, str, or None for auto-detect).max_force (
float) – Maximum force for motor control (physics mode).tolerance (
Optional[float]) – Euclidean distance (m) for reachability check. If None, usesik_params.reachability_tolerance.
- Return type:
- Returns:
True if the IK solution places the EE within tolerance of the target (reachable). False otherwise. A best-effort candidate, when available, is still commanded.
Example:
reachable = arm.move_end_effector([0.3, 0.0, 0.5]) if not reachable: print("Target may not be fully reachable")
- are_ee_at_target(target_position, target_orientation=None, end_effector_link=None, tolerance=0.02, orientation_tolerance=0.15)
Check whether the end-effector is near the target pose.
Resolves the EE link and delegates to
_check_ee_pose().- Parameters:
target_position (
List[float]) – Target EE position [x, y, z] in world frame.target_orientation (
Optional[Tuple[float,float,float,float]]) – Target EE orientation as quaternion [qx, qy, qz, qw]. If None, only position is checked.end_effector_link (
Union[int,str,None]) – Link index, name, or None (auto-detect).tolerance (
float) – Maximum Euclidean distance (m) to consider reached.orientation_tolerance (
float) – Maximum1 - |dot|between actual and target quaternions (default 0.15).
- Return type:
- Returns:
True if the EE is within tolerance of the target.
- update_attached_objects_kinematics()
For URDF robots: update attached objects’ pose to follow the parent link (kinematics attach). This is called every step for kinematic (mass=0) attached objects.
- class pybullet_fleet.AgentSpawnParams(visual_shape=None, collision_shape=None, initial_pose=<factory>, mass=0.0, pickable=False, name=None, visual_frame_pose=None, collision_frame_pose=None, collision_mode=CollisionMode.NORMAL_3D, user_data=<factory>, urdf_path=None, motion_mode=MotionMode.DIFFERENTIAL, use_fixed_base=False, ik_params=None, controller=None, plugins=None, global_scaling=1.0, joint_tolerance=None)
Bases:
SimObjectSpawnParamsAgent spawn parameters extending SimObjectSpawnParams.
These parameters define the physical properties, appearance, and initial state of an agent. They are used by Agent.from_params() and AgentManager.spawn_agents_grid().
Supports three types of robots: 1. Mesh robots: Specify visual_shape (and optionally collision_shape) 2. URDF robots: Specify urdf_path (for robots with joints) 3. Virtual agents: Specify neither (invisible, no collision, useful for tracking/planning)
- urdf_path
Path to robot URDF file (for URDF-based robots with joints)
- motion_mode
MotionMode.OMNIDIRECTIONAL (move in any direction) or MotionMode.DIFFERENTIAL (rotate then move forward)
- use_fixed_base
If True, robot base is fixed and doesn’t move (default: False)
- plugins
List of plugin config dicts for per-agent plugins. Each entry is
{"type": "battery", "config": {...}}or{"class": "my.Module", "config": {...}}.
- controller
Movement controller selector / configuration. Accepts a registry-name string (
"omni"), a flat dict, a list of dicts, aControllerParams, or a pre-builtController. Each dict entry uses eithertype:(registry name) orclass:(dotted import path), plus controller-specific config inline. KinematicController entries (omni, differential) replace the base controller; high-level entries (patrol, random_walk) are appended on top of it. A lone high-level entry auto-creates the base frommotion_mode. Example single:{"type": "patrol", "waypoints": [...], "loop": True}Example custom:{"class": "my_pkg.MyController", "max_linear_vel": 1.5}Example list:[{"type": "differential", ...}, {"type": "patrol", ...}]
See
Agent.__init__for thecontrollerargument (selector / configuration for the Agent’s movement controller; supports str / dict / list / Controller / ControllerParams).- Inherited from SimObjectSpawnParams:
- name: Optional string name for human-readable identification.
Duplicates allowed - use for debugging/filtering, not unique lookup. For unique identification, use object_id after spawning.
Note
AgentManager.spawn_agents_grid() calculates positions automatically and may override initial_pose.
- pickable: bool = False
Agents are not pickable by default – a robot is usually the one doing the picking – which narrows SimObjectSpawnParams’ default of True. Redeclared rather than set elsewhere so the value a caller passes is the value the agent gets; Agent.__init__ used to overwrite it unconditionally, which made the field inert.
- motion_mode: MotionMode | str = 'differential'
- use_fixed_base: bool = False
- ik_params: IKParams | None = None
- controller: str | Dict[str, Any] | List[Dict[str, Any]] | ControllerParams | Controller | None = None
- global_scaling: float = 1.0
- classmethod from_dict(config)
Create AgentSpawnParams from configuration dictionary.
- Parameters:
Dictionary with robot parameters including:
visual_shape/collision_shapeorurdf_pathinitial_pose:Poseobject (optional)controller: dict / str /None— seecontrollerand the Controller Configuration how-touse_fixed_base,motion_mode,ik_params(optional)
- Returns:
AgentSpawnParams instance
Example:
config = { 'visual_shape': ShapeParams( shape_type='mesh', mesh_path='robot.obj', mesh_scale=[1.0, 1.0, 1.0], rgba_color=[0.2, 0.2, 0.2, 1.0] ), 'collision_shape': ShapeParams( shape_type='box', half_extents=[0.2, 0.1, 0.2] ), 'initial_pose': Pose.from_xyz(1.0, 2.0, 0.0), 'controller': {'max_linear_vel': 2.0, 'max_linear_accel': 5.0}, 'use_fixed_base': False } params = AgentSpawnParams.from_dict(config) # Or for URDF: config = { 'urdf_path': 'robots/mobile_robot.urdf', 'initial_pose': Pose.from_xyz(1.0, 2.0, 0.0), 'use_fixed_base': False } params = AgentSpawnParams.from_dict(config)
- class pybullet_fleet.IKParams(max_outer_iterations=5, convergence_threshold=0.01, max_inner_iterations=200, residual_threshold=0.0001, reachability_tolerance=0.02, seed_quartiles=(0.25, 0.5, 0.75), ik_joint_names=None)
Bases:
objectInverse kinematics solver configuration.
Controls the multi-seed iterative IK solver used by
Agent._solve_ik()andAgent.move_end_effector().- max_outer_iterations
Maximum refinement iterations per seed.
- convergence_threshold
EE-to-target distance (m) below which the IK solution is accepted early.
- max_inner_iterations
maxNumIterationspassed topybullet.calculateInverseKinematics.
- residual_threshold
residualThresholdpassed topybullet.calculateInverseKinematics.
- reachability_tolerance
Maximum EE distance (m) for
Agent.move_end_effector()to report reachable.
- seed_quartiles
Tuple of joint-range fractions (0–1) used to build diversified rest-pose seeds. Each value
qproduces a seed atlower + q * rangefor every joint.
- ik_joint_names
Explicit tuple of joint names that the IK solver is allowed to move. All other movable joints are locked at their current position. When
None(default), the solver falls back to the automatic heuristic (continuous joints are locked, everything else is free).
Example:
cfg = IKParams(max_outer_iterations=10, seed_quartiles=(0.1, 0.5, 0.9)) arm = Agent.from_urdf("arm.urdf", ik_params=cfg) # Mobile manipulator — solve only for arm joints cfg = IKParams(ik_joint_names=( "mount_to_shoulder", "shoulder_to_elbow", "elbow_to_wrist", "wrist_to_end", )) robot = Agent.from_urdf("mobile_manipulator.urdf", ik_params=cfg)
- max_outer_iterations: int = 5
- convergence_threshold: float = 0.01
- max_inner_iterations: int = 200
- residual_threshold: float = 0.0001
- reachability_tolerance: float = 0.02
- class pybullet_fleet.AgentManager(sim_core=None, name=None, update_frequency=10.0, object_class=<class 'pybullet_fleet.agent.Agent'>, enable_profiling=False, fleet_controller=None)
Bases:
SimObjectManager[Agent]Extended manager class for agents with update callback system.
This class extends SimObjectManager with agent-specific features: - Grid-based agent spawning with AgentSpawnParams - Pose goal assignment to individual agents - Callback system for custom update logic (goals, state tracking, etc.) - Query moving/stopped agents - Optional batch controller for vectorized kinematic updates (
fleet_controller={"type": ...}orenable_batch())Key Features: - Auto-registers update callback to simulation loop - Callback receives (agents, manager, dt) for easy agent operations - Configurable update frequency - Direct access to manager methods within callback
Note: - Agent.update() is automatically called by MultiRobotSimulationCore every step - AgentManager callbacks are for high-level logic (goals, coordination, etc.) - Agent-specific state can be stored in each Agent.user_data dict
- __init__(sim_core=None, name=None, update_frequency=10.0, object_class=<class 'pybullet_fleet.agent.Agent'>, enable_profiling=False, fleet_controller=None)
Initialize AgentManager.
- Parameters:
sim_core – Reference to simulation core (optional)
name (
Optional[str]) – Optional name for this manager. When set, the manager can be retrieved later viaget_manager().update_frequency (
float) – Default update callback frequency in Hz (default: 10.0)object_class (
type) – Class to instantiate when spawning (default: Agent). Pass an Agent subclass to manage custom agent types.enable_profiling (
bool) – IfTrue, spawn methods log elapsed time. DefaultFalse.fleet_controller (
Optional[Dict[str,Any]]) – Manager controller configuration.typemay be"batch_omni"or"batch_differential"to enable vectorized movement for every managed agent; omit it for per-agent execution. The remaining keys are sharedControllerParamsdefaults applied only where an agent did not set that field in its owncontroller:config.
- property agents: List[Agent]
The agents this manager holds, skipping anything that is not one.
spawn_from_config()dispatches on each entry’stype, so a config may mixagentandsim_objectandobjectscan hold both. Everything on this class that commands movement, reads motion state or queues actions is agent-only, and reads this rather thanobjects.
- enable_batch(mode)
Create and attach a batch controller for mode, replacing any existing one.
Any agents already managed by this instance that are not yet batch-controlled are registered immediately. Agents spawned afterwards are registered automatically via
add_object().- Parameters:
mode (
str) – Batch controller registry name (e.g."batch_omni","batch_differential") or a dotted import path to a customBatchKinematicControllersubclass (e.g."my_pkg.MyBatchController").- Return type:
- Returns:
The newly-created
BatchKinematicController.- Raises:
ValueError – If mode is not recognised.
- disable_batch()
Unregister all managed agents from the batch controller and detach it.
- Return type:
- add_object(obj)
Add an object, wiring up the agent-only parts only for agents.
An
AgentManagercan legitimately hold a plainSimObject:spawn_from_config()dispatches on each entry’stypeand a config may mixagentandsim_object. Everything below is agent-only, though – the fleet-controller defaults readcontroller_paramsand the batch controller reads_batch_controller, neither of which aSimObjecthas – so a mixed manager used to raiseAttributeErrorfrom inside this method as soon as either controller was attached. That could be long after the object was added, and it read as a fault inenable_batch()rather than in the mix.- Return type:
- remove_object(obj)
Remove an object from the manager’s tracking lists.
This only removes the object from the manager’s bookkeeping (
objects,body_ids,object_ids). It does not touchsim_coreor PyBullet — that is handled byMultiRobotSimulationCore.remove_object().Called automatically by
sim_core.remove_object()when this manager is registered viasim_core.register_manager().- Parameters:
obj (
Agent) – The object to remove.- Return type:
- Returns:
True if the object was found and removed, False otherwise.
- spawn_agents_grid(num_agents, grid_params, spawn_params, *, name_prefix=None)
Spawn agents in a grid. Alias for
spawn_objects_grid().- Return type:
List[Agent]
- spawn_agents_grid_mixed(num_agents, grid_params, spawn_params_list, *, name_prefix=None)
Spawn mixed agent types. Alias for
spawn_grid_mixed().- Return type:
List[Agent]
- spawn_agent_grid_counts(grid_params, spawn_params_count_list, *, name_prefix=None)
Spawn exact counts per type. Alias for
spawn_grid_counts().- Return type:
List[Agent]
- set_goal_pose(agent_index, goal)
Set goal pose for a specific agent.
- set_goal_pose_by_body_id(body_id, goal)
Set goal pose for an agent by its PyBullet body ID.
Note
This method uses PyBullet’s internal body_id for compatibility with direct PyBullet API usage. For manager-level operations, prefer using set_goal_pose_by_object_id() instead.
- set_goal_pose_by_object_id(object_id, goal)
Set goal pose for an agent by its simulation object ID.
This is the preferred method for manager-level operations, as it uses the simulation’s unique object_id rather than PyBullet’s internal body_id.
- stop_all()
Stop all agents and clear their goals.
- set_goal_pose_all(goal_factory)
Set goal pose for all agents using a factory function.
This helper method simplifies bulk goal assignment by applying a factory function to each agent. The factory can use agent-specific data (current pose, user_data, etc.) to create customized goals.
- Parameters:
goal_factory (
Callable[[Agent],Pose]) – Function that takes an Agent and returns a Pose- Return type:
Example:
# Set all agents to move to their designated home positions def get_home_goal(robot): return robot.user_data['home_position'] manager.set_goal_pose_all(get_home_goal) # Move all agents 5 meters forward from their current position def move_forward(robot): current_pos = robot.get_pose().position return Pose.from_xyz(current_pos[0] + 5, current_pos[1], current_pos[2]) manager.set_goal_pose_all(move_forward)
Note
This is a convenience wrapper around individual set_goal_pose calls. No performance benefit over explicit loops, but improves code clarity.
- set_joints_targets_all(targets_factory, max_force=500.0)
Set joint targets for all agents using a factory function.
This helper method simplifies bulk joint control by applying a factory function to each agent. Useful for coordinated multi-robot arm movements.
- Parameters:
- Return type:
Example:
# Set all robot arms to neutral position def get_neutral_joints(robot): return [0.0, 0.0, 0.0, 0.0] manager.set_joints_targets_all(get_neutral_joints) # Set custom positions based on robot index def get_custom_joints(robot): idx = robot.user_data.get('index', 0) return [idx * 0.1, 0.0, 0.0, 0.0] manager.set_joints_targets_all(get_custom_joints, max_force=1000.0)
Note
Only applicable to agents with controllable joints (robot arms, etc.). Mobile robots without arm joints will ignore this command.
- get_moving_count()
Get number of agents currently moving.
- Return type:
- add_action_sequence_all(action_factory)
Apply action sequence to all agents using a factory function.
This helper method simplifies bulk action assignment by applying a factory function to each agent. The factory can use agent-specific data (pose, user_data, etc.) to create customized action sequences.
- Parameters:
action_factory (
Callable[[Agent],List[Any]]) – Function that takes an Agent and returns a list of Actions- Return type:
Example:
def create_pick_drop_sequence(robot): target = robot.user_data['target_object'] return [ PickAction(target_object_id=target.body_id), MoveAction(path=Path.from_positions([[10, 10, 0]])), DropAction(drop_pose=Pose(position=[10, 10, 0])) ] # Apply to all agents at once manager.add_action_sequence_all(create_pick_drop_sequence)
Note
This is a convenience wrapper. Internally it still loops through agents, so there’s no performance benefit over explicit loops. The main advantage is code clarity and reduced boilerplate.
- add_action_all(action_factory)
Add a single action to all agents using a factory function.
Similar to add_action_sequence_all, but adds a single action instead of a sequence.
- Parameters:
action_factory (
Callable[[Agent],Any]) – Function that takes an Agent and returns a single Action- Return type:
Example:
def create_move_action(robot): goal_pos = robot.user_data['next_position'] return MoveAction(path=Path.from_positions([goal_pos])) manager.add_action_all(create_move_action)
- register_callback(callback, frequency=None)
Register a callback for custom agent update logic.
Multiple callbacks can be registered, each with their own frequency. This method automatically registers with sim_core if available.
The callback provides access to the AgentManager instance, making it easy to: - Access all agents via manager.objects - Use manager methods (set_goal_pose, query states, etc.) - Store manager-level state in agent.user_data
- The callback should have signature:
callback(manager: AgentManager, dt: float) -> None
- Parameters:
Example (Goal management):
def goal_update_logic(manager, dt): for agent in manager.objects: if not agent.is_moving: # Set new goal for stopped agents new_goal = calculate_next_goal(agent) agent.set_goal_pose(new_goal) manager.register_callback(goal_update_logic, frequency=4.0)
Example (State tracking):
def state_tracker(manager, dt): for agent in manager.objects: # Track agent statistics if 'total_distance' not in agent.user_data: agent.user_data['total_distance'] = 0.0 agent.user_data['total_distance'] += np.linalg.norm(agent.velocity) * dt manager.register_callback(state_tracker, frequency=10.0)
Comparison with sim_core.register_callback():
AgentManager callback: Provides manager reference and filtered agent list
sim_core callback: Provides sim_core reference for all objects
Use AgentManager for agent-specific operations
Use sim_core for general simulation-wide operations
- setup_camera(camera_config=None)
Setup camera to view all managed objects in the simulation.
This method automatically extracts positions from all managed objects and configures the camera to fit them in the view.
- Parameters:
camera_config (
Optional[Dict]) – Dictionary with camera settings (from yaml config). If None, uses default settings.- Return type:
Example:
# Basic usage with default settings agent_manager.setup_camera() # With custom camera config camera_config = { 'camera_mode': 'auto', 'camera_view_type': 'top_down', 'camera_auto_scale': 0.8 } agent_manager.setup_camera(camera_config)
Note
Requires sim_core to be set during AgentManager initialization. Only works when GUI is enabled.
- class pybullet_fleet.GridSpawnParams(x_min, x_max, y_min, y_max, spacing, offset, z_min=0, z_max=0)
Bases:
objectGrid parameters for object spawning in 3D space.
- x_min
Minimum X grid index
- x_max
Maximum X grid index
- y_min
Minimum Y grid index
- y_max
Maximum Y grid index
- spacing
Grid spacing [spacing_x, spacing_y, spacing_z] in meters
- offset
Grid offset [offset_x, offset_y, offset_z] in meters
- z_min
Minimum Z grid index (defaults to 0)
- z_max
Maximum Z grid index (defaults to 0 for 2D grids)
Note
Objects spawn in X → Y → Z order. For 2D grids, set z_min=z_max=0 (default). For 3D grids, set z_max > z_min to enable vertical layers.
- x_min: int
- x_max: int
- y_min: int
- y_max: int
- z_min: int = 0
- z_max: int = 0
- property total_cells: int
(x range) * (y range) * (z range).
- Type:
Total number of grid cells
- classmethod from_dict(config)
Create GridSpawnParams from a configuration dictionary.
Supports two formats:
Explicit ranges (original) — requires
x_min,x_max,y_min,y_max,spacing,offset:grid: x_min: 0 x_max: 9 y_min: 0 y_max: 4 spacing: [3.0, 3.0, 0.0] offset: [0, 0, 0.05]
Count-based (convenience) — requires
countandspacing;columnsandoffsetare optional:grid: count: 50 spacing: [3.0, 3.0] offset: [0, 0, 0.05] columns: 10
When
countis present,from_count()is used to compute the grid ranges.
- classmethod from_count(count, columns=None, spacing=None, offset=None)
Create GridSpawnParams from a total entity count.
Computes
x_maxandy_maxfrom count and columns so that the grid has exactly enough cells. Useful when you know “I want 50 robots” rather than “x_max=9, y_max=4”.- Parameters:
count (
int) – Total number of entities to place.columns (
Optional[int]) – Grid width (X cells) before wrapping to the next row. Defaults toceil(sqrt(count)).spacing (
Optional[List[float]]) –[sx, sy, sz]in metres. Default[1,1,0].offset (
Optional[List[float]]) –[ox, oy, oz]origin offset. Default[0,0,0].
- Return type:
GridSpawnParams- Returns:
GridSpawnParams with
x_min=0,y_min=0,x_max=columns-1,y_max=ceil(count/columns)-1.
- class pybullet_fleet.Controller(params=None)
Bases:
ABCAgent movement control interface (Strategy pattern).
Pure base class: only
compute()+ lifecycle hooks. All built-in controllers are kinematic: they update agent pose directly viaagent.set_pose(). No physics forces or torques are applied.Subclasses with a
_registry_nameclass attribute are auto-registered via_registry_nameclass attribute (e.g._registry_name = "omni").- abstractmethod compute(agent, dt)
Compute one step of control.
- Return type:
- Returns:
Trueif the agent moved,Falseotherwise.
- params: ControllerParams
- path_rejection(agent, path, direction=None)
Why
pathwould be refused now, orNoneif it would be taken.The default takes every path. The kinematic controllers refuse one only under
goal_replacement="reject".
- brake(agent)
Bring
agentto rest within the deceleration limits; seeAgent.brake, which delegates here.- Return type:
- Returns:
Truewhen a braking motion was started. The default cannot brake and returnsFalse;Agent.stopis then the way to stop.
- request_path(agent, request, preempt=False)
Follow
request;Falseif refused. The core ofset_path().The kinematic controllers implement it. A controller written against
set_path()alone keeps working: itsset_pathis called with the request’s fields.Agent.request_pathgoes through an overriddenset_pathtoo, on any controller (seesend_request()).- Return type:
- set_path(agent, path, final_orientation_align=True, direction=None, preempt=False)
Follow
path:request_path()with aPathRequestof these fields.- Parameters:
agent (
Agent) – Agent to navigate.path (
List[Pose]) – Non-empty list of waypoint Poses.final_orientation_align (
bool) – Rotate to match the last waypoint’s orientation after reaching its position.direction (
Optional[MovementDirection]) –None(usedefault_direction),FORWARD,AUTO, orBACKWARD(differential only).preempt (
bool) – Do not hold the path for the current one underwait_complete(Agent.brakeuses it).
- Return type:
- request_state(agent, request)
What became of
request(seePathRequestState).UNKNOWNby default: a controller that does not track requests.- Return type:
PathRequestState
- classmethod from_config(config)
Create from a config dict.
The dict may contain:
Any field of
ControllerParams(e.g.max_linear_vel,navigation_2d, …). Unknown keys are dropped silently byControllerParams.from_dict.Subclass-specific keys that match the subclass
__init__signature (e.g.wheel_separationforDifferentialController).A
typekey naming the controller; ignored here (consumed bycreate_controller()).
- Return type:
TypeVar(_ControllerT, bound= Controller)
- on_stop(agent)
Called when
stop()is invoked on the agent.- Return type:
- reset()
Reset internal controller state.
- Return type:
- class pybullet_fleet.ControllerMode(value)
-
Internal mode for KinematicController state machine.
- IDLE
No active command — zero velocity, no pose target.
- VELOCITY
Processing cmd_vel input (body-frame velocity).
- POSE
Processing goal_pose / path via TPI trajectory.
- IDLE = 'idle'
- VELOCITY = 'velocity'
- POSE = 'pose'
- class pybullet_fleet.KinematicController(params=None)
Bases:
GoalReplacementPolicy,ControllerUnified base for kinematic controllers handling both velocity and pose.
- Internal mode state machine:
IDLE — no active command VELOCITY — processing velocity input (body-frame) POSE — processing goal pose via TPI trajectory
- Input-based mode switching with interruption (B3):
set_velocity()→ switch to VELOCITY (cancels POSE if active)set_goal_pose()/set_path()→ switch to POSE (cancels VELOCITY)Watchdog timeout → IDLE
Trajectory complete → IDLE
- property default_direction: MovementDirection
Default movement direction used when
set_pathis called without explicit direction.
- property mode: ControllerMode
Current controller mode.
- property goal_pose: Pose | None
Current goal pose (active waypoint).
- property current_waypoint_index: int
Current waypoint index in the path (0-based).
- property path: List[Pose]
Current path (list of waypoints). Empty when idle.
- compute(agent, dt)
Template: dispatch to velocity or pose handler based on mode.
- Return type:
- on_stop(agent)
Zero all velocity commands, cancel pose, and clear path state.
- Return type:
- reset()
Reset all internal state.
- Return type:
- set_velocity(vx=0.0, vy=0.0, vz=0.0, wx=0.0, wy=0.0, wz=0.0)
Set velocity command (body frame, 6-DoF). Override in subclasses for clamping.
- Return type:
- cancel_pose()
Cancel active pose navigation and switch to IDLE.
- Return type:
- continuation_velocity(agent)
World-frame velocity a new path would continue from, or
None.The agent’s velocity while it is under way (a translation or a velocity command), else
None. A controller that does not continue motion into a new path returnsNone. Used byAgent.brake()and byGoalReplacement.BRAKE.
- pending_path()
The accepted path waiting for the agent to stop, or
None.- Return type:
Optional[PathRequest]
- request_path(agent, request, preempt=False)
Follow
request’s waypoints (set_path()builds one from its arguments).What happens depends on
goal_replacement(seeGoalReplacement).wait_completeholds the path while the current one is in progress and starts it once that one is finished. In the other modes a path that can continue the current motion (or any path at rest) starts at once, from the current velocity; otherwisebrakebrakes along the current motion and starts the path once stopped,immediatestarts it from rest at once, andrejectrefuses it, leaving the current motion and path untouched. Only the latest held path is kept: a newer request, a stop or a cancel drops it, with a log line.The controller owns all path-navigation state: waypoint index, movement direction, final-orientation alignment.
Agent.set_path()handles validation, auto-approach, and visualisation, then delegates here.- Parameters:
agent (
Agent) – Agent to navigate.request (
PathRequest) – The waypoints (non-empty), whether to align to the last one’s orientation, and the direction (None:default_direction; differential only).preempt (
bool) – Do not hold the path for the current one underwait_complete(Agent.brakeuses it); the other rules still apply.
- Return type:
- Returns:
Falsewhen the path is refused (rejectonly);Trueonce it is set or held to start later.
- braking_request(agent)
The path request that brings the moving
agentto rest, orNoneat rest.The one place that decides how this controller brakes:
brake()(and soAgent.brake) sets it, andgoal_replacement="brake"runs it before a path the agent cannot continue into. The default stops at the braking point,|v|^2 / (2 * decel)ahead along the motion, at the configured deceleration (seebraking_request()). A subclass overrides it to brake differently. The request must continue the current motion (the controller’s_replacement_obstaclerule); one that does not is not started – a warning, and the default braking point instead.- Return type:
Optional[PathRequest]
- brake(agent)
Set
braking_request()throughAgent.set_path, never held for the current path.A pending path from an earlier
brakeorwait_completereplacement is dropped. ReturnsFalseat rest.- Return type:
- request_state(agent, request)
What became of
request: being followed, held, followed to its end, or gone (replaced, dropped, stopped, braked or cancelled).- Return type:
PathRequestState
- capture_navigation_state()
Capture the active kinematic pose path, including waypoint and turn phases.
- Return type:
- restore_navigation_state(state, orientation, owner='')
Restore a kinematic pose path without reissuing its navigation command.
ownernames the agent in the log line if the restored pending path is later dropped.- Return type:
- class pybullet_fleet.OmniController(params=None)
Bases:
KinematicControllerUnified omnidirectional controller: velocity commands + TPI pose navigation.
- Velocity mode (VELOCITY):
6-DoF body-frame velocity (vx, vy, vz, wx, wy, wz) → quaternion-based world-frame integration. Linear and angular magnitudes are clamped.
- Pose mode (POSE):
Per-axis TPI with distance-ratio velocity scaling for straight-line motion from start to goal.
- set_velocity(vx=0.0, vy=0.0, vz=0.0, wx=0.0, wy=0.0, wz=0.0)
Set velocity in body frame (6-DoF) with kinematic clamping.
Scalar limits ⇒ magnitude clamp (preserves direction). Per-axis limits ⇒ per-component clamp.
- Return type:
- class pybullet_fleet.DifferentialController(params=None, wheel_separation=0.0)
Bases:
KinematicControllerUnified differential-drive controller: velocity commands + TPI pose.
- Velocity mode (VELOCITY):
Unicycle model — only forward (
vx) and yaw rate (wz). Lateral velocity and other DoF are ignored.- Pose mode (POSE):
Two-phase TPI: ROTATE to face target, then FORWARD to reach it. Uses TPI + quaternion slerp for smooth rotation.
- capture_navigation_state()
Capture the common pose path plus differential heading and direction.
- Return type:
- restore_navigation_state(state, orientation, owner='')
Restore a turn or straight segment without issuing another command.
- Return type:
- set_velocity(vx=0.0, vy=0.0, vz=0.0, wx=0.0, wy=0.0, wz=0.0)
Set velocity (body frame). Only
vxandwzare used.Per-axis limits are reduced to scalars via X (forward) / yaw axes.
- Return type:
- pybullet_fleet.create_controller(name, config=None)
Create a controller by registered name, optionally passing config.
Convenience wrapper around
create_controller_from_entry().- Raises:
KeyError – If name is not registered.
- Return type:
Controller
- pybullet_fleet.register_controller(name, cls)
Register a controller class under name.
- Return type:
- pybullet_fleet.body_to_world_velocity_2d(vx_body, vy_body, yaw)
Rotate 2-D body-frame velocity to world frame using yaw only.
- Parameters:
- Return type:
- Returns:
(vx, vy)in world frame.
Example:
>>> body_to_world_velocity_2d(1.0, 0.0, yaw=math.pi / 2) (0.0, 1.0) # facing +Y, forward maps to +Y
- pybullet_fleet.body_to_world_velocity_3d(vx_body, vy_body, vz_body, orientation)
Rotate 3-D body-frame velocity to world frame using full quaternion.
Uses the same quaternion convention as PyBullet:
(x, y, z, w).- Parameters:
- Return type:
- Returns:
(vx, vy, vz)in world frame.
Example:
>>> from scipy.spatial.transform import Rotation >>> q = Rotation.from_euler("z", 90, degrees=True).as_quat() # xyzw >>> body_to_world_velocity_3d(1.0, 0.0, 0.0, tuple(q)) (0.0, 1.0, 0.0)
- pybullet_fleet.grid_to_world(grid, spacing, offset=None)
Convert grid indices to world coordinates (always 3D), with offset.
- Parameters:
- Return type:
- Returns:
[x, y, z] world coordinates
- pybullet_fleet.world_to_grid(pos, spacing, offset=None)
Convert world coordinates to grid indices (always 3D), with offset.
- Parameters:
- Return type:
- Returns:
[ix, iy, iz] grid indices
- pybullet_fleet.normalize_vector_param(value, param_name, dim=3)
Normalize a parameter to a numpy array of specified dimension.
This is a utility function for handling parameters that can be either: - A single float (applied to all dimensions) - A list of floats (one per dimension)
Commonly used for velocity/acceleration limits that can be uniform or per-axis.
- Parameters:
- Return type:
- Returns:
Numpy array of shape (dim,)
- Raises:
ValueError – If list length doesn’t match dimension
Example:
>>> normalize_vector_param(2.0, "max_vel", 3) array([2., 2., 2.]) >>> normalize_vector_param([1.0, 2.0, 3.0], "max_vel", 3) array([1., 2., 3.])
- pybullet_fleet.quat_to_rot_matrix(quat)
Convert a quaternion
(x, y, z, w)to a 3×3 rotation matrix.Returns the matrix as a flat 9-element tuple in row-major order:
(r00, r01, r02, r10, r11, r12, r20, r21, r22)
This is allocation-free and suitable for hot-path use.
- Parameters:
quat (
Tuple[float,float,float,float]) – Quaternion(x, y, z, w)— same convention as PyBullet. Automatically normalized if not already unit-length.- Return type:
Tuple[float,float,float,float,float,float,float,float,float]- Returns:
9-element tuple representing the 3×3 rotation matrix (row-major).
- Raises:
ValueError – If the quaternion has zero norm.
- pybullet_fleet.quat_angle_between(q0, q1)
Compute the rotation angle (radians) between two quaternions.
Equivalent to
(Rotation.from_quat(q1) * Rotation.from_quat(q0).inv()).magnitude(). Handles the double-cover:qand-qrepresent the same rotation. Inputs are normalized internally, so non-unit quaternions are accepted.
- pybullet_fleet.quat_from_rotvec(rotvec)
Convert a rotation vector (axis × angle) to a quaternion
(x, y, z, w).Equivalent to
scipy.spatial.transform.Rotation.from_rotvec(rotvec).as_quat().
- pybullet_fleet.quat_multiply(q1, q2)
Hamilton product of two quaternions in
(x, y, z, w)convention.Equivalent to
(Rotation.from_quat(q1) * Rotation.from_quat(q2)).as_quat(). For active rotations this corresponds to applying q2 first, then q1.
- pybullet_fleet.quat_slerp_batch(q0, q1, t, dot, theta0, sin_theta0)
Vectorised SLERP for N quaternion pairs.
Evaluates slerp simultaneously for all N agents using NumPy — the hot path for
BatchDifferentialControllerandBatchOmniController.The caller is responsible for shortest-path correction:
q1must already have had its sign flipped wheredot(q0, q1) < 0, anddotmust be the corrected (non-negative) dot product.- Parameters:
q0 (
ndarray) –(N, 4)start quaternions.q1 (
ndarray) –(N, 4)end quaternions (sign-corrected for shortest path).t (
ndarray) –(N,)interpolation parameters in[0, 1].dot (
ndarray) –(N,)dot productsdot(q0, q1) >= 0.theta0 (
ndarray) –(N,)half-anglesacos(dot).sin_theta0 (
ndarray) –(N,)sin(theta0).
- Return type:
- Returns:
(N, 4)interpolated unit quaternions.
- pybullet_fleet.rotate_vector(vec, quat)
Rotate a 3-D vector by a quaternion.
Equivalent to
scipy.spatial.transform.Rotation.from_quat(quat).apply(vec)but avoids SciPy object allocation, making it suitable for per-tick hot paths.
- pybullet_fleet.load_yaml_config(config_path)
Load a YAML config file and return parsed contents.
General-purpose YAML loader. Works for any YAML config file (simulation, bridge, spawn definitions, etc.).
- Parameters:
config_path (
str) – Path to YAML config file.- Return type:
- Returns:
Parsed config dict.
- Raises:
FileNotFoundError – If config_path does not exist.
- pybullet_fleet.register_entity_class(name, cls)
Register an entity class under name.
- class pybullet_fleet.SimPlugin(sim_core)
Bases:
objectBase class for simulation plugins.
Plugins receive lifecycle callbacks and can access the full simulation API via
self.sim_core.All lifecycle hooks are optional no-ops by default — override only what your plugin needs. Step-based plugins override
on_step(); event-driven plugins subscribe toself.sim_core.eventsinon_init()and leaveon_stepalone.Lifecycle:
__init__(sim_core) # construction (typed kwargs in subclasses) on_init() # after world/robots are spawned on_step(dt) # each simulation step (frequency-controlled) on_reset() # when simulation is reset on_shutdown() # before PyBullet disconnects
Subclasses with a
_registry_nameclass attribute are auto-registered via_registry_nameclass attribute (e.g._registry_name = "workcell").- default_step_phase: CallbackPhase | str = 'step'
a
CallbackPhaseor its value. A subclass may set"pre_step"or"post_step";register_plugin(phase=...)and the YAMLphasefield override it per instance. Namedstep_phase, notphase, so that a plugin’s own state can keep that common name.- Type:
When in the step
on_step()runs, by default for this class
- property step_phase: CallbackPhase
When in the step
on_step()runs, as forregister_callback(phase=...).PRE_STEP: at the start of the step, before the clock advances and before anything moves (sim_timeis the previous state’s).STEP(default): after the objects have been updated, before the poses are written and the collision check.POST_STEP: at the end of the step, after the collision check.
Read when the plugin is registered: set it before, through
register_plugin(phase=...), the YAMLphasefield ordefault_step_phase. Setting it once the plugin is registered raisesRuntimeError.
- property frequency: float | None
Step frequency in Hz;
Nonecallson_step()every step.Changing it starts a fresh schedule on the new rate.
- classmethod from_config(sim_core, config=None)
Create from config dict, matching keys to
__init__parameters.Works like
Controller.from_config(): inspects the subclass__init__signature and passes matching keys as kwargs. The raw config dict is stored asconfig.
- on_init()
Called after world and robots are spawned.
Override to query
self.sim_core.agents, subscribe to events, or perform one-time setup. No-op by default.- Return type:
- on_step(dt)
Called each simulation step (subject to frequency control).
Override for step-based logic. Event-driven plugins can leave this as a no-op and react via
self.sim_core.eventsinstead.
- on_reset()
Called when the simulation is reset. Override to clear plugin state.
- Return type:
- on_shutdown()
Called before PyBullet disconnects. Override to release resources.
- Return type:
- class pybullet_fleet.AgentPlugin(agent)
Bases:
objectBase class for per-agent plugins.
Lifecycle:
__init__(agent) # construction (typed kwargs in subclasses) on_init() # after agent is fully constructed on_update(dt) # each simulation step on_reset() # when agent state is reset on_destroy() # when agent is removed / sim shuts down
Subclasses override the hooks they need. All hooks are no-ops by default.
Subclasses with a
_registry_nameclass attribute are auto-registered inAGENT_PLUGIN_REGISTRY(e.g._registry_name = "battery").- agent
The owning
Agentinstance.
- config
Raw configuration dict (populated by
from_config()).
- classmethod from_config(agent, config=None)
Create from config dict, matching keys to
__init__parameters.Works like
Controller.from_config(): inspects the subclass__init__signature and passes matching keys as kwargs. The raw config dict is stored asconfig.
- on_init()
Called after the agent is fully constructed.
Override to perform one-time setup that depends on the agent being registered with sim_core. No-op by default.
- Return type:
- on_update(dt)
Called each simulation step from
Agent.update().Override in subclasses. Default is a no-op.
- on_reset()
Called when the agent’s state is reset.
Override to reinitialise plugin state. No-op by default.
- Return type:
- on_destroy()
Called when the agent is removed or the simulation shuts down.
Override to release resources. No-op by default.
- Return type:
- class pybullet_fleet.BatteryPlugin(agent, initial_soc=1.0, discharge_rate=0.001, charge_rate=0.005, idle_rate=0.0)
Bases:
AgentPluginDefault linear battery drain/charge plugin.
Owns all battery state as plain attributes:
discharge_rate— SOC drain per second while movingcharge_rate— SOC gain per second while chargingidle_rate— SOC drain per second while idlesoc— current state of charge [0.0, 1.0]is_charging— whether the agent is charging
Update logic:
charging →
soc += charge_rate * dtmoving →
soc -= discharge_rate * dtidle →
soc -= idle_rate * dt
SOC is clamped to
[0.0, 1.0].- set_charging(charging)
Start or stop charging.
- on_update(dt)
Update battery SOC based on agent’s current state.
- Return type:
- pybullet_fleet.create_agent_plugin(name, agent, config=None)
Create a plugin by registered name.
Convenience wrapper around
create_agent_plugin_from_entry()for use in Python code where building an entry dict is verbose.
- pybullet_fleet.list_agent_plugins()
Return a copy of the agent plugin registry for inspection.
- pybullet_fleet.register_agent_plugin(name, cls)
Register a plugin class under name.
- Return type:
- class pybullet_fleet.Door(body_id, urdf_path=None, motion_mode=MotionMode.DIFFERENTIAL, use_fixed_base=False, collision_mode=CollisionMode.NORMAL_3D, sim_core=None, name=None, user_data=None, mass=None, ik_params=None, joint_tolerance=None, controller=None, notify_spawn=True, pickable=False)
Bases:
AgentDoor controlled via URDF revolute or prismatic joint.
Uses JointAction for open/close transitions. Door state is derived from the current JointAction status and joint positions.
Config (YAML):
type: door urdf_path: robots/door_hinge.urdf open_positions: {hinge: 1.57} close_positions: {hinge: 0.0}
- classmethod from_params(spawn_params, sim_core=None)
Create a Door from DoorParams.
- Raises:
TypeError – If spawn_params is not a
DoorParamsinstance oropen_positionsis missing.- Return type:
Door
- property door_state: DoorState
Derived door state.
- request_open()
Open the door (enqueue JointAction to open positions).
- Return type:
- request_close()
Close the door (enqueue JointAction to close positions).
- Return type:
- class pybullet_fleet.DoorParams(visual_shape=None, collision_shape=None, initial_pose=<factory>, mass=0.0, pickable=False, name=None, visual_frame_pose=None, collision_frame_pose=None, collision_mode=CollisionMode.NORMAL_3D, user_data=<factory>, urdf_path=None, motion_mode=MotionMode.DIFFERENTIAL, use_fixed_base=False, ik_params=None, controller=None, plugins=None, global_scaling=1.0, joint_tolerance=None, open_positions=None, close_positions=<factory>)
Bases:
AgentSpawnParamsSpawn parameters for a Door device.
Extends AgentSpawnParams with door-specific joint targets.
- open_positions
Joint name → target angle/position for the “open” state. Required —
Noneraises TypeError in__post_init__.
- close_positions
Joint name → target angle/position for the “closed” state.
- classmethod from_dict(config)
Create DoorParams from a config dict.
Delegates base-field parsing to
AgentSpawnParams.from_dictand adds door-specific fields (open_positions,close_positions).- Return type:
DoorParams
- class pybullet_fleet.Elevator(body_id, urdf_path=None, motion_mode=MotionMode.DIFFERENTIAL, use_fixed_base=False, collision_mode=CollisionMode.NORMAL_3D, sim_core=None, name=None, user_data=None, mass=None, ik_params=None, joint_tolerance=None, controller=None, notify_spawn=True, pickable=False)
Bases:
AgentElevator with named floors and automatic passenger attachment.
Uses JointAction for floor transitions. Before movement starts, all sim_objects whose AABB overlaps the platform collision box are attached to the platform link. On arrival they are detached.
Config (YAML):
type: elevator urdf_path: robots/elevator.urdf use_fixed_base: true floors: {L1: 0.0, L2: 8.0, L3: 16.0} initial_floor: L1 joint_name: lift platform_link: platform request_policy: queue # reject (default), replace_next, queue, or redirect boarding_height: 1.0 # metres above the platform that count as on board report_platform_contacts: false # bodies standing on the platform are not collisions
- classmethod from_params(spawn_params, sim_core=None)
Create an Elevator from ElevatorParams.
- Raises:
TypeError – If spawn_params is not an
ElevatorParamsinstance orfloorsis missing.- Return type:
Elevator
- property current_floor: str
Floor where the elevator currently is (or departed from while moving).
While the elevator is in transit this returns the departure floor, not the destination. Use
target_floorfor the destination.
- property target_floor: str
Destination floor (equals
current_floorwhen idle).
- property is_moving: bool
True while elevator is transitioning between floors.
- property state: ElevatorState
Current backend-neutral elevator lifecycle state.
- property request_policy: ElevatorRequestPolicy
Policy applied to requests received while the cabin is moving.
- property passengers: List[SimObject]
Currently attached passengers (read-only copy).
- request_floor(floor_name, instant=False)
Request the elevator to move to the given floor.
Attaches all objects on the platform, then starts the joint action.
- Parameters:
- Return type:
ElevatorRequestResult- Returns:
Whether the request was accepted immediately, queued, replaced, or rejected according to
request_policy.
- update(dt)
Per-step update. Detaches passengers when movement completes.
- Return type:
- begin_motion(target_height, instant=False)
Command the PyBullet lift joint to move to
target_height.With
instantthe joint is put there at once, carrying the attached passengers (Agent.set_joint_position()).- Return type:
- motion_in_progress()
Observe whether the cabin is still moving.
The action alone is not enough once the lift joint has a motion profile.
JointActioncompletes as soon as the joint is inside its tolerance, but a ramped joint is still braking through the last millimetres after that – measured on a 0.6 m ride at 0.4 m/s with 1 m/s^2 ramps, the action finished at 1.78 s with the cabin 7.2 mm short, and the joint settled at 1.88 s. Taking the action’s word for it let the state machine mark the cabin arrived and release its passengers while it was still moving.- Return type:
- attach_platform_passengers()
Attach platform occupants using PyBullet constraints.
- Return type:
- detach_passengers()
Release constrained passengers after a completed lift motion.
- Return type:
- class pybullet_fleet.ElevatorParams(visual_shape=None, collision_shape=None, initial_pose=<factory>, mass=0.0, pickable=False, name=None, visual_frame_pose=None, collision_frame_pose=None, collision_mode=CollisionMode.NORMAL_3D, user_data=<factory>, urdf_path=None, motion_mode=MotionMode.DIFFERENTIAL, use_fixed_base=False, ik_params=None, controller=None, plugins=None, global_scaling=1.0, joint_tolerance=None, floors=None, initial_floor='', joint_name='lift', platform_link='platform', request_policy=ElevatorRequestPolicy.REJECT, boarding_height=1.0, max_speed=None, max_accel=None, max_decel=None, report_platform_contacts=False)
Bases:
AgentSpawnParamsSpawn parameters for an Elevator device.
Extends AgentSpawnParams with elevator-specific floor/joint config.
- floors
Floor name → joint position mapping. Required —
Noneraises TypeError in__post_init__.
- initial_floor
Name of the floor the elevator starts at.
- joint_name
Name of the prismatic joint that moves the platform.
- platform_link
Name of the link with the platform collision box.
- request_policy
Handling for floor requests received while moving.
- boarding_height
Metres above the platform’s top within which an object counts as on board when the cabin starts moving. Keep it below the distance between two floors: an object waiting on the floor above the cabin would otherwise ride along, and arrive at the height it had above the platform.
- max_speed
Cabin speed in m/s.
Noneuses the URDF’s<limit velocity="...">onjoint_name, which is where the speed otherwise has to be set – so without this, two installations that differ only in how fast the cabin travels need two URDFs.
- max_accel
Cabin acceleration in m/s^2.
Nonekeeps the cabin at full speed from the first step, as before. Giving it makes the travel a trapezoid, which is what a real cabin does: 0.6 m at 0.4 m/s takes 1.5 s flat and 1.9 s with 1.0 m/s^2 ramps.
- max_decel
Cabin deceleration. Defaults to
max_accel.
- report_platform_contacts
Report a body standing on the platform as in collision with the elevator. Off by default: a robot waiting on the platform before departure, or left there on arrival, rests on it, which is not a collision. A body counts as standing on the platform when it is over the platform’s footprint and its lowest point is not below the platform’s mid-height; a body touching the platform from below (the cabin coming down onto it) is still reported. Passengers attached for a ride are not affected: they follow
SimulationParams.ignore_attached_collision. The rule leaves the body out of contact with the whole elevator, so it only applies when the platform link is the elevator’s one collider: an elevator URDF with collider walls, a ceiling or doors reports bodies on the platform as if this were on (and logs a warning at spawn), so that driving into a wall is seen.
- initial_floor: str = ''
- joint_name: str = 'lift'
- platform_link: str = 'platform'
- request_policy: ElevatorRequestPolicy | str = 'reject'
- boarding_height: float = 1.0
- report_platform_contacts: bool = False
- classmethod from_dict(config)
Create ElevatorParams from a config dict.
Delegates base-field parsing to
AgentSpawnParams.from_dictand adds elevator-specific fields (floors,initial_floor,joint_name,platform_link, …).- Return type:
ElevatorParams
- class pybullet_fleet.PatrolController(params=None, waypoints=None, wait_time=0.0, loop=True)
Bases:
ControllerCycle through waypoints. Delegates actual movement to the base controller by calling
agent.set_goal_pose().- Parameters:
- compute(agent, dt)
Compute one step of control.
- Return type:
- Returns:
Trueif the agent moved,Falseotherwise.
- class pybullet_fleet.RandomWalkController(params=None, radius=5.0, wait_range=(1.0, 5.0))
Bases:
ControllerMove to random nearby positions within a radius of the starting point.
- Parameters:
- compute(agent, dt)
Compute one step of control.
- Return type:
- Returns:
Trueif the agent moved,Falseotherwise.
- pybullet_fleet.resolve_model(name_or_path)
Resolve a model name or file path to an absolute URDF/SDF path.
Resolution order:
If
name_or_pathcontains a path separator (os.sepor/) or ends with.urdf/.sdf, treat as a direct file path: absolute paths and paths that exist relative to the CWD are returned as-is; a bundled relative path (e.g."robots/mobile_robot.urdf") otherwise resolves to the packaged asset (absolute), falling back to the raw value if not found.Search user-registered directories (see
add_search_path()).Look up in
KNOWN_MODELSregistry and resolve by tier.Auto-discovery fallback: scan
pybullet_datafiles androbot_descriptionsmodules for a matching name.Raise
FileNotFoundErrorwith install instructions.
Auto-discovery does not modify
KNOWN_MODELS.- Parameters:
name_or_path (
str) – Model name (e.g."panda","kiva_shelf") or file path.- Return type:
- Returns:
Absolute path to the model file (URDF or SDF).
- Raises:
FileNotFoundError – If the model cannot be resolved.
- pybullet_fleet.resolve_urdf(name_or_path)
Backward-compatible alias for
resolve_model().Deprecated since version Use:
resolve_model()instead.resolve_urdfwill be removed in a future release.- Return type:
- pybullet_fleet.list_all_models()
Check availability of all known models.
- class pybullet_fleet.ModelEntry(rel_path, tier, install_hint='', xacro_args='')
Bases:
objectRegistry entry for a known robot model.
- rel_path: str
- tier: str
- install_hint: str = ''
- xacro_args: str = ''
- class pybullet_fleet.RobotProfile(urdf_path, robot_type='unknown', ee_link_name=None, movable_joint_names=<factory>, joint_lower_limits=<factory>, joint_upper_limits=<factory>, joint_max_velocities=<factory>, num_joints=0, _movable_joint_indices=<factory>, arm_reach=None, ee_link_index=-1)
Bases:
objectAuto-detected robot profile from URDF introspection.
This is a pre-spawn, read-only snapshot intended for external tooling (GUIs, catalog browsers, spawn helpers). It is not used by
Agentat runtime — the Agent maintains its own joint info, IK state, and velocity limits independently. Modifying aRobotProfileinstance has no effect on a running simulation.All fields can be overridden after detection or via
auto_detect_profile(..., **overrides).- urdf_path: str
- robot_type: str = 'unknown'
- num_joints: int = 0
- ee_link_index: int = -1
- make_joint_targets(fractions, agent)
Build a full joint-target list from per-movable-joint fractions.
Each fraction in
[-1, 1]is mapped to the joint’s limit range:target = mid + fraction * half_range
Fixed joints and unmapped joints keep their current position.
- Parameters:
- Return type:
- Returns:
A list with one target per joint (
len(agent.joint_info)), suitable foragent.set_all_joints_targets().
- pybullet_fleet.auto_detect_profile(urdf_path_or_body_id, physics_client, **overrides)
Introspect a URDF/SDF or an already-loaded PyBullet body.
When urdf_path_or_body_id is a string, the URDF/SDF is loaded temporarily and removed after introspection. When it is an int (PyBullet body ID), the already-loaded body is introspected in place — no load or remove occurs. Use the
intform in GUI mode to avoid GPU resource corruption fromremoveBody.Robot type detection is heuristic-based (see
detect_robot_type()for known limitations). Passrobot_type=in overrides to correct any mis-detection.- Parameters:
- Return type:
RobotProfile- Returns:
RobotProfile with detected (or overridden) values.
- pybullet_fleet.detect_robot_type(body_id, physics_client)
Detect robot type from an already-loaded PyBullet body.
Unlike
auto_detect_profile(), this does not load or remove any bodies — it introspects a body that is already in the simulation. This makes it safe to call in GUI mode without corrupting GPU resources.Note
Best-effort heuristic. The classification relies on joint types and link-name keywords, which does not cover all robot designs. Known limitations:
A differential-drive robot with a passive caster (bounded revolute) is mis-classified as
"mobile_manipulator".Humanoids and hexapods do not match the quadruped keyword set and fall back to
"arm"or"unknown".Grippers with only bounded joints are classified as
"arm".
Use
auto_detect_profile(..., robot_type="mobile")or the**overridesparameter to correct mis-detections.
- pybullet_fleet.register_model(name, path_or_entry, *, force=False)
Register a custom model so it can be resolved by name.
This is the recommended way to make any URDF/SDF loadable via
resolve_model(name)— including models frompybullet_data, ROS packages, orrobot_descriptionsthat are not in the built-inKNOWN_MODELSregistry.Example:
from pybullet_fleet.robot_models import register_model, resolve_model # Simple: register an absolute path register_model("my_agv", "/opt/robots/my_agv.urdf") # Or register a pybullet_data model by relative path + tier register_model("sphere", ModelEntry("sphere2.urdf", "pybullet_data")) path = resolve_model("my_agv")
- Parameters:
name (
str) – Short model name (e.g."my_agv").path_or_entry (
Union[str,ModelEntry]) – Either an absolute path to a URDF/SDF file, or aModelEntryfor full tier metadata.force (
bool) – IfTrue, overwrite an existing entry. By default, raisesValueErrorto prevent accidental overwrites.
- Raises:
ValueError – If name is already registered and force is
False.- Return type:
- pybullet_fleet.unregister_model(name)
Remove a model from
KNOWN_MODELS.No-op if the name is not registered.
- pybullet_fleet.discover_models(tier)
Scan a tier and return all discoverable models.
Unlike
KNOWN_MODELS(curated subset), this scans the actual installed package and returns every model found.- Parameters:
tier (
str) –"pybullet_data"or"robot_descriptions".- Return type:
- Returns:
Dict mapping short model name → absolute URDF/SDF path.
- Raises:
ValueError – If tier is not a supported scan target.
- pybullet_fleet.add_search_path(directory)
Register a directory to search for URDF/SDF files by name.
User search paths are checked before the
KNOWN_MODELSregistry, allowing users to shadow built-in models with custom versions.Example:
from pybullet_fleet.robot_models import add_search_path, resolve_model add_search_path("/opt/company_robots") path = resolve_model("my_agv") # → /opt/company_robots/my_agv.urdf
- Parameters:
directory (
str) – Absolute or relative path to a directory containing.urdfor.sdffiles.- Raises:
ValueError – If the directory does not exist.
- Return type:
- pybullet_fleet.remove_search_path(directory)
Remove a previously registered search directory.
No-op if the directory was not registered.