-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath_plan_carla.py
More file actions
190 lines (160 loc) · 6.25 KB
/
path_plan_carla.py
File metadata and controls
190 lines (160 loc) · 6.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import carla
import math
import heapq
import time
import random
import itertools
import matplotlib.pyplot as plt
# --- Utility Functions ---
def distance(loc1, loc2):
"""Euclidean distance in the XY plane."""
return math.hypot(loc1.x - loc2.x, loc1.y - loc2.y)
def heuristic(a, b):
"""Straight-line distance heuristic for A*."""
return distance(a, b)
# --- Global Planner (Waypoint-based A*) ---
def astar(world, start_wp, goal_wp, resolution=3.0):
"""
A* search over CARLA waypoints, respecting lane direction.
:param world: carla.World
:param start_wp: carla.Waypoint
:param goal_wp: carla.Waypoint
:param resolution: distance step for neighbor waypoints
:return: List[carla.Waypoint] representing the path
"""
counter = itertools.count()
open_set = [] # heap of (f_score, count, key, waypoint)
came_from = {}
g_score = {}
f_score = {}
def wp_key(wp):
loc = wp.transform.location
return (round(loc.x,1), round(loc.y,1), wp.road_id, wp.lane_id)
start_key = wp_key(start_wp)
goal_loc = goal_wp.transform.location
g_score[start_key] = 0.0
f_score[start_key] = heuristic(start_wp.transform.location, goal_loc)
heapq.heappush(open_set, (f_score[start_key], next(counter), start_key, start_wp))
visited = set()
while open_set:
_, _, current_key, current_wp = heapq.heappop(open_set)
if current_key in visited:
continue
visited.add(current_key)
# goal test
if distance(current_wp.transform.location, goal_loc) < resolution:
path = [current_wp]
key = current_key
while key in came_from:
wp = came_from[key]
path.append(wp)
key = wp_key(wp)
path.reverse()
return path
# neighbors along lane direction
for nbr in current_wp.next(resolution):
nbr_key = wp_key(nbr)
if nbr_key in visited:
continue
tentative_g = g_score[current_key] + distance(current_wp.transform.location,
nbr.transform.location)
if tentative_g < g_score.get(nbr_key, float('inf')):
came_from[nbr_key] = current_wp
g_score[nbr_key] = tentative_g
f_score[nbr_key] = tentative_g + heuristic(nbr.transform.location, goal_loc)
heapq.heappush(open_set, (f_score[nbr_key], next(counter), nbr_key, nbr))
return [] # no path found
# --- Local Controller (Pure Pursuit) ---
def compute_control(vehicle, target, throttle_gain=0.5, steering_gain=1.0):
"""
Compute throttle and steering to drive towards a target point.
:param vehicle: carla.Vehicle
:param target: carla.Location
:return: (carla.VehicleControl, reached_boolean)
"""
transform = vehicle.get_transform()
loc = transform.location
yaw = math.radians(transform.rotation.yaw)
dx = target.x - loc.x
dy = target.y - loc.y
desired_yaw = math.atan2(dy, dx)
yaw_error = (desired_yaw - yaw + math.pi) % (2 * math.pi) - math.pi
steer = max(-1.0, min(1.0, steering_gain * yaw_error / (math.pi/4)))
dist = distance(loc, target)
throttle = throttle_gain if dist > 1.0 else 0.0
control = carla.VehicleControl(throttle=throttle, steer=steer, brake=0.0)
done = dist < 0.5
return control, done
# --- Main Execution ---
def main():
client = carla.Client('localhost', 2000)
client.set_timeout(10.0)
world = client.get_world()
# Define start transform
start_transform = carla.Transform(
carla.Location(x=10.0, y=20.0, z=0.0),
carla.Rotation(pitch=0.0, yaw=0.0, roll=0.0)
)
start_loc = start_transform.location
# Random goal from spawn points
spawn_points = world.get_map().get_spawn_points()
goal_transform = random.choice(spawn_points)
goal_loc = goal_transform.location
print(f"Randomly selected goal at ({goal_loc.x:.1f}, {goal_loc.y:.1f}, {goal_loc.z:.1f})")
# Spawn vehicle safely
blueprint = world.get_blueprint_library().filter('vehicle.*')[0]
vehicle = world.try_spawn_actor(blueprint, start_transform)
if vehicle is None:
for sp in spawn_points:
vehicle = world.try_spawn_actor(blueprint, sp)
if vehicle:
start_transform = sp
start_loc = sp.location
print(f"Spawned at alternative start {start_loc}")
break
else:
print("Failed to spawn vehicle.")
return
# Convert start/goal to waypoints
start_wp = world.get_map().get_waypoint(start_loc,
project_to_road=True,
lane_type=carla.LaneType.Driving)
goal_wp = world.get_map().get_waypoint(goal_loc,
project_to_road=True,
lane_type=carla.LaneType.Driving)
# Plan global path
wp_path = astar(world, start_wp, goal_wp, resolution=3.0)
if not wp_path:
print("No path found!")
return
# Extract locations
path = [wp.transform.location for wp in wp_path]
# Plot path
xs = [loc.x for loc in path]
ys = [loc.y for loc in path]
plt.figure()
plt.plot(xs, ys, marker='o', linestyle='-')
plt.title('Global Lane-Aware Path')
plt.xlabel('X (m)')
plt.ylabel('Y (m)')
plt.grid(True)
plt.show()
# Visualize in CARLA
for loc in path:
world.debug.draw_point(loc + carla.Location(z=1.0),
size=0.2,
color=carla.Color(0, 255, 0),
life_time=120.0)
print(f"Planned {len(path)} lane-aware waypoints.")
# Follow path
idx = 0
while idx < len(path):
target = path[idx]
control, reached = compute_control(vehicle, target)
vehicle.apply_control(control)
if reached:
idx += 1
world.wait_for_tick()
print("Arrived at goal!")
if __name__ == '__main__':
main()