本文整理匯總了Python中carla.Client方法的典型用法代碼示例。如果您正苦於以下問題:Python carla.Client方法的具體用法?Python carla.Client怎麽用?Python carla.Client使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類carla
的用法示例。
在下文中一共展示了carla.Client方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _get_data_from_carla
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def _get_data_from_carla(self):
try:
self.client = carla.Client(self.args.host, self.args.port)
self.client.set_timeout(self.timeout)
if self.args.map is None:
world = self.client.get_world()
else:
world = self.client.load_world(self.args.map)
town_map = world.get_map()
return (world, town_map)
except RuntimeError as ex:
logging.error(ex)
exit_game()
示例2: __init__
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def __init__(self,
n_sim_steps=500,
display_dim=(1280,720),
carla_host='127.0.0.1',
carla_port=2000,
carla_timeout=4.0,
world_map='Town03',
cam_transform=0):
self.n_sim_steps = n_sim_steps
self.display_dim = display_dim
self.client = carla.Client(carla_host, carla_port)
self.client.set_timeout(carla_timeout)
self.clock = pygame.time.Clock()
self.world_map = world_map
self.timestep = 0
self.cam_transform = cam_transform
print("[carla_task] Finished initializing carla task.")
示例3: get_world
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def get_world(host="localhost", port=2000, timeout=10):
"""Get a handle to the world running inside the simulation.
Args:
host (:obj:`str`): The host where the simulator is running.
port (:obj:`int`): The port to connect to at the given host.
timeout (:obj:`int`): The timeout of the connection (in seconds).
Returns:
A tuple of `(client, world)` where the `client` is a connection to the
simulator and `world` is a handle to the world running inside the
simulation at the host:port.
"""
client, world = None, None
try:
client = carla.Client(host, port)
client.set_timeout(timeout)
world = client.get_world()
except RuntimeError as r:
client, world = None, None
raise Exception("Received an error while connecting to the "
"simulator: {}".format(r))
return (client, world)
示例4: main
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def main():
global world
# Connect to the CARLA instance.
client = carla.Client('localhost', 2000)
world = client.get_world()
settings = world.get_settings()
settings.synchronous_mode = True
settings.fixed_delta_seconds = 1.0 / 10
world.apply_settings(settings)
# Spawn the vehicle.
vehicle = spawn_driving_vehicle(client, world)
# Spawn the camera and register a function to listen to the images.
camera = spawn_rgb_camera(world, carla.Location(x=2.0, y=0.0, z=1.8),
carla.Rotation(roll=0, pitch=0, yaw=0), vehicle)
camera.listen(process_images)
world.tick()
return vehicle, camera, world
示例5: run
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def run(self):
"""
main loop
"""
# wait for ros-bridge to set up CARLA world
rospy.loginfo("Waiting for CARLA world (topic: /carla/world_info)...")
try:
rospy.wait_for_message("/carla/world_info", CarlaWorldInfo, timeout=10.0)
except rospy.ROSException as e:
rospy.logerr("Timeout while waiting for world info!")
raise e
rospy.loginfo("CARLA world available. Spawn infrastructure...")
client = carla.Client(self.host, self.port)
client.set_timeout(self.timeout)
self.world = client.get_world()
self.restart()
try:
rospy.spin()
except rospy.ROSInterruptException:
pass
# ==============================================================================
# -- main() --------------------------------------------------------------------
# ==============================================================================
示例6: __init__
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def __init__(self, args):
"""
Setup CARLA client and world
Setup ScenarioManager
"""
self._args = args
if args.timeout:
self.client_timeout = float(args.timeout)
# First of all, we need to create the client that will send the requests
# to the simulator. Here we'll assume the simulator is accepting
# requests in the localhost at port 2000.
self.client = carla.Client(args.host, int(args.port))
self.client.set_timeout(self.client_timeout)
dist = pkg_resources.get_distribution("carla")
if LooseVersion(dist.version) < LooseVersion('0.9.8'):
raise ImportError("CARLA version 0.9.8 or newer required. CARLA version found: {}".format(dist))
# Load agent if requested via command line args
# If something goes wrong an exception will be thrown by importlib (ok here)
if self._args.agent is not None:
module_name = os.path.basename(args.agent).split('.')[0]
sys.path.insert(0, os.path.dirname(args.agent))
self.module_agent = importlib.import_module(module_name)
# Create the ScenarioManager
self.manager = ScenarioManager(self._args.debug, self._args.sync, self._args.timeout)
# Create signal handler for SIGINT
self._shutdown_requested = False
if sys.platform != 'win32':
signal.signal(signal.SIGHUP, self._signal_handler)
signal.signal(signal.SIGINT, self._signal_handler)
signal.signal(signal.SIGTERM, self._signal_handler)
self._start_wall_time = datetime.now()
示例7: game_loop
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def game_loop(args):
pygame.init()
pygame.font.init()
world = None
try:
client = carla.Client(args.host, args.port)
client.set_timeout(2.0)
display = pygame.display.set_mode(
(args.width, args.height),
pygame.HWSURFACE | pygame.DOUBLEBUF)
hud = HUD(args.width, args.height)
world = WorldSR(client.get_world(), hud, args)
controller = KeyboardControl(world, args.autopilot)
clock = pygame.time.Clock()
while True:
clock.tick_busy_loop(60)
if controller.parse_events(client, world, clock):
return
if not world.tick(clock):
return
world.render(display)
pygame.display.flip()
finally:
if (world and world.recording_enabled):
client.stop_recorder()
if world is not None:
world.destroy()
pygame.quit()
# ==============================================================================
# -- main() --------------------------------------------------------------------
# ==============================================================================
示例8: __init__
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def __init__(self, width=400, height=300, render=False, state_processor=None, autopilot=True,
buffer_size=5, num_of_cars=1, npc_cars=10, fps=60, world='Town01', camera='rgb'):
self.should_render = render
self.actor_list = []
self.width = width
self.height = height
self.processor = state_processor
self.buffer_size = buffer_size
self.buffer = deque(maxlen=buffer_size)
self.time_steps = 0
self.num_of_agents = num_of_cars
self.npc_cars = npc_cars
self.num_frames = 0
self.fps = fps
self.current_state = None
self.npc_cars = npc_cars
self.world = world
self.camera_name = camera
self.fines = deque(maxlen=100)
self.client = carla.Client('localhost', 2000)
self.client.set_timeout(2.0)
self.world = self.client.load_world(world)
self.terminate_state = False
self.autopilot = autopilot
settings = self.world.get_settings()
settings.fixed_delta_seconds = 1/self.fps
self.world.apply_settings(settings)
self.initialize()
if self.should_render:
self.__init_pygame_engine()
示例9: get_client
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def get_client(address, port, timeout=2.0) -> carla.Client:
"""Connects to the simulator.
@:returns a carla.Client instance if the CARLA simulator accepts the connection.
"""
client: carla.Client = carla.Client(address, port)
client.set_timeout(timeout)
return client
示例10: __init__
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def __init__(self, carla_instance, seconds_per_episode=None, playing=False):
# Set a client and timeouts
self.client = carla.Client(*settings.CARLA_HOSTS[carla_instance][:2])
self.client.set_timeout(2.0)
# Get currently running world
self.world = self.client.get_world()
# Get list of actor blueprints
blueprint_library = self.world.get_blueprint_library()
# Get Tesla model 3 blueprint
self.model_3 = blueprint_library.filter('model3')[0]
# Sensors and helper lists
self.collision_hist = []
self.actor_list = []
self.front_camera = None
self.preview_camera = None
# Used to determine if Carla simulator is still working as it crashes quite often
self.last_cam_update = time.time()
# Updated by agents for statistics
self.seconds_per_episode = seconds_per_episode
# A flag indicating that we are just going to play
self.playing = playing
# Used with additional preview feature
self.preview_camera_enabled = False
# Sets actually configured actions
self.actions = [getattr(ACTIONS, action) for action in settings.ACTIONS]
# Resets environment for new episode
示例11: start
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def start(playing=False):
# Kill Carla processes if there are any and start simulator
if settings.CARLA_HOSTS_TYPE == 'local':
print('Starting Carla...')
kill_processes()
for process_no in range(1 if playing else settings.CARLA_HOSTS_NO):
subprocess.Popen(get_exec_command()[1] + f' -carla-rpc-port={settings.CARLA_HOSTS[process_no][1]}', cwd=settings.CARLA_PATH, shell=True)
time.sleep(2)
# Else just wait for it to be ready
else:
print('Waiting for Carla...')
# Wait for Carla Simulator to be ready
for process_no in range(1 if playing else settings.CARLA_HOSTS_NO):
while True:
try:
client = carla.Client(*settings.CARLA_HOSTS[process_no][:2])
map_name = client.get_world().get_map().name
if len(settings.CARLA_HOSTS[process_no]) == 2 or not settings.CARLA_HOSTS[process_no][2]:
break
if isinstance(settings.CARLA_HOSTS[process_no][2], int):
map_choice = random.choice([map.split('/')[-1] for map in client.get_available_maps()])
else:
map_choice = settings.CARLA_HOSTS[process_no][2]
if map_name != map_choice:
carla.Client(*settings.CARLA_HOSTS[process_no][:2]).load_world(map_choice)
while True:
try:
while carla.Client(*settings.CARLA_HOSTS[process_no][:2]).get_world().get_map().name != map_choice:
time.sleep(0.1)
break
except:
pass
break
except Exception as e:
#print(str(e))
time.sleep(0.1)
# Retarts Carla simulator
示例12: main
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def main():
client = carla.Client('localhost', 2000)
client.set_timeout(2.0)
world = client.get_world()
spectator = world.get_spectator()
vehicle_blueprints = world.get_blueprint_library().filter('vehicle')
location = random.choice(world.get_map().get_spawn_points()).location
for blueprint in vehicle_blueprints:
transform = carla.Transform(location, carla.Rotation(yaw=-45.0))
vehicle = world.spawn_actor(blueprint, transform)
try:
print(vehicle.type_id)
angle = 0
while angle < 356:
timestamp = world.wait_for_tick()
angle += timestamp.delta_seconds * 60.0
spectator.set_transform(get_transform(vehicle.get_location(), angle - 90))
finally:
vehicle.destroy()
示例13: game_loop
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def game_loop(args):
pygame.init()
pygame.font.init()
world = None
try:
client = carla.Client(args.host, args.port)
client.set_timeout(2.0)
display = pygame.display.set_mode(
(args.width, args.height),
pygame.HWSURFACE | pygame.DOUBLEBUF)
hud = HUD(args.width, args.height)
world = World(client.get_world(), hud)
controller = KeyboardControl(world, args.autopilot)
clock = pygame.time.Clock()
while True:
clock.tick_busy_loop(60)
if controller.parse_events(world, clock):
return
world.tick(clock)
world.render(display)
pygame.display.flip()
finally:
if world is not None:
world.destroy()
pygame.quit()
# ==============================================================================
# -- main() --------------------------------------------------------------------
# ==============================================================================
示例14: test_client_version
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def test_client_version(self):
c = carla.Client('localhost', 8080)
v = c.get_client_version()
out = check_output(['git', 'describe', '--tags', '--dirty', '--always', ])
if sys.version_info > (3, 0):
out = out.decode('utf8')
self.assertEqual(str(v), str(out.strip()))
示例15: spawn_driving_vehicle
# 需要導入模塊: import carla [as 別名]
# 或者: from carla import Client [as 別名]
def spawn_driving_vehicle(client, world):
""" This function spawns the driving vehicle and puts it into
an autopilot mode.
Args:
client: The carla.Client instance representing the simulation to
connect to.
world: The world inside the current simulation.
Returns:
A carla.Actor instance representing the vehicle that was just spawned.
"""
# Get the blueprint of the vehicle and set it to AutoPilot.
vehicle_bp = random.choice(
world.get_blueprint_library().filter('vehicle.*'))
while not vehicle_bp.has_attribute('number_of_wheels') or not int(
vehicle_bp.get_attribute('number_of_wheels')) == 4:
vehicle_bp = random.choice(
world.get_blueprint_library().filter('vehicle.*'))
vehicle_bp.set_attribute('role_name', 'autopilot')
# Get the spawn point of the vehicle.
start_pose = random.choice(world.get_map().get_spawn_points())
# Spawn the vehicle.
batch = [
carla.command.SpawnActor(vehicle_bp, start_pose).then(
carla.command.SetAutopilot(carla.command.FutureActor, True))
]
vehicle_id = client.apply_batch_sync(batch)[0].actor_id
# Find the vehicle and return the carla.Actor instance.
time.sleep(
0.5) # This is so that the vehicle gets registered in the actors.
return world.get_actors().find(vehicle_id)