-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_collection.py
More file actions
2219 lines (1922 loc) · 96.1 KB
/
data_collection.py
File metadata and controls
2219 lines (1922 loc) · 96.1 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright (c) 2019 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
# Allows controlling a vehicle with a keyboard. For a simpler and more
# documented example, please take a look at tutorial.py.
"""
Welcome to CARLA manual control.
Use ARROWS or WASD keys for control.
W : throttle
S : brake
A/D : steer left/right
Q : toggle reverse
Space : hand-brake
P : toggle autopilot
M : toggle manual transmission
,/. : gear up/down
CTRL + W : toggle constant velocity mode at 60 km/h
L : toggle next light type
SHIFT + L : toggle high beam
Z/X : toggle right/left blinker
I : toggle interior light
TAB : change sensor position
` or N : next sensor
[1-9] : change to sensor [1-9]
G : toggle radar visualization
C : change weather (Shift+C reverse)
Backspace : change vehicle
O : open/close all doors of vehicle
T : toggle vehicle's telemetry
V : Select next map layer (Shift+V reverse)
B : Load current selected map layer (Shift+B to unload)
R : toggle recording images to disk
CTRL + R : toggle recording of simulation (replacing any previous)
CTRL + P : start replaying last recorded simulation
CTRL + + : increments the start time of the replay by 1 second (+SHIFT = 10 seconds)
CTRL + - : decrements the start time of the replay by 1 second (+SHIFT = 10 seconds)
F1 : toggle HUD
H/? : toggle help
ESC : quit
"""
from __future__ import print_function
# ==============================================================================
# -- find carla module ---------------------------------------------------------
# ==============================================================================
import glob
import os
import sys
import csv
import datetime
import networkx as nx
from pathlib import Path
try:
sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
pass
# ==============================================================================
# -- imports -------------------------------------------------------------------
# ==============================================================================
import carla
from carla import ColorConverter as cc
import argparse
import collections
import logging
import math
import random
import re
import weakref
import time
try:
import pygame
from pygame.locals import KMOD_CTRL
from pygame.locals import KMOD_SHIFT
from pygame.locals import K_0
from pygame.locals import K_9
from pygame.locals import K_BACKQUOTE
from pygame.locals import K_BACKSPACE
from pygame.locals import K_COMMA
from pygame.locals import K_DOWN
from pygame.locals import K_ESCAPE
from pygame.locals import K_F1
from pygame.locals import K_LEFT
from pygame.locals import K_PERIOD
from pygame.locals import K_RIGHT
from pygame.locals import K_SLASH
from pygame.locals import K_SPACE
from pygame.locals import K_TAB
from pygame.locals import K_UP
from pygame.locals import K_a
from pygame.locals import K_b
from pygame.locals import K_c
from pygame.locals import K_d
from pygame.locals import K_f
from pygame.locals import K_g
from pygame.locals import K_h
from pygame.locals import K_i
from pygame.locals import K_l
from pygame.locals import K_m
from pygame.locals import K_n
from pygame.locals import K_o
from pygame.locals import K_p
from pygame.locals import K_q
from pygame.locals import K_r
from pygame.locals import K_s
from pygame.locals import K_t
from pygame.locals import K_v
from pygame.locals import K_w
from pygame.locals import K_x
from pygame.locals import K_z
from pygame.locals import K_MINUS
from pygame.locals import K_EQUALS
except ImportError:
raise RuntimeError('cannot import pygame, make sure pygame package is installed')
try:
import numpy as np
except ImportError:
raise RuntimeError('cannot import numpy, make sure numpy package is installed')
import cv2
# ==============================================================================
# -- Global functions ----------------------------------------------------------
# ==============================================================================
def get_lane_metrics(vehicle, world):
"""Calculate lane metrics matching record.py implementation"""
# Get vehicle's current waypoint
vehicle_transform = vehicle.get_transform()
vehicle_location = vehicle_transform.location
waypoint = world.get_map().get_waypoint(vehicle_location, project_to_road=True)
# Initialize info dictionary matching record.py structure
info = {
'angle': 0.0,
'in_lane': {
'toMarking_LL': None,
'toMarking_ML': None,
'toMarking_MR': None,
'toMarking_RR': None,
'dist_LL': float('inf'),
'dist_MM': float('inf'),
'dist_RR': float('inf')
},
'on_marking': {
'toMarking_L': None,
'toMarking_M': None,
'toMarking_R': None,
'dist_L': float('inf'),
'dist_R': float('inf')
}
}
# Calculate angle between road and vehicle direction
road_dir = waypoint.transform.get_forward_vector()
vehicle_dir = vehicle_transform.get_forward_vector()
dot = road_dir.x * vehicle_dir.x + road_dir.y * vehicle_dir.y
cross = road_dir.x * vehicle_dir.y - road_dir.y * vehicle_dir.x
info['angle'] = math.degrees(math.atan2(cross, dot))
# Get lane width
lane_width = waypoint.lane_width
# Set lane markings distances
if waypoint.lane_type == carla.LaneType.Driving:
info['in_lane']['toMarking_ML'] = lane_width/2
info['in_lane']['toMarking_MR'] = lane_width/2
# Get adjacent lanes
left_lane = waypoint.get_left_lane()
right_lane = waypoint.get_right_lane()
if left_lane:
info['in_lane']['toMarking_LL'] = lane_width
if right_lane:
info['in_lane']['toMarking_RR'] = lane_width
# Find distances to other vehicles
vehicle_list = world.get_actors().filter('vehicle.*')
for other_vehicle in vehicle_list:
if other_vehicle.id == vehicle.id:
continue
other_location = other_vehicle.get_location()
other_waypoint = world.get_map().get_waypoint(other_location)
# Check if vehicle is in front
to_other = other_location - vehicle_location
forward = vehicle_transform.get_forward_vector()
if forward.dot(to_other) > 0:
distance = vehicle_location.distance(other_location)
# Check which lane the other vehicle is in
if other_waypoint.lane_id == waypoint.lane_id:
info['in_lane']['dist_MM'] = min(info['in_lane']['dist_MM'], distance)
elif other_waypoint.lane_id == waypoint.lane_id - 1: # Left lane
info['in_lane']['dist_LL'] = min(info['in_lane']['dist_LL'], distance)
elif other_waypoint.lane_id == waypoint.lane_id + 1: # Right lane
info['in_lane']['dist_RR'] = min(info['in_lane']['dist_RR'], distance)
# Set on-marking measurements
if waypoint.lane_type == carla.LaneType.Driving:
info['on_marking']['toMarking_L'] = lane_width
info['on_marking']['toMarking_M'] = lane_width/2
info['on_marking']['toMarking_R'] = lane_width
info['on_marking']['dist_L'] = info['in_lane']['dist_LL']
info['on_marking']['dist_R'] = info['in_lane']['dist_RR']
return info
def find_weather_presets():
rgx = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)')
name = lambda x: ' '.join(m.group(0) for m in rgx.finditer(x))
presets = [x for x in dir(carla.WeatherParameters) if re.match('[A-Z].+', x)]
return [(getattr(carla.WeatherParameters, x), name(x)) for x in presets]
def get_actor_display_name(actor, truncate=250):
name = ' '.join(actor.type_id.replace('_', '.').title().split('.')[1:])
return (name[:truncate - 1] + u'\u2026') if len(name) > truncate else name
def get_actor_blueprints(world, filter, generation):
bps = world.get_blueprint_library().filter(filter)
if generation.lower() == "all":
return bps
# If the filter returns only one bp, we assume that this one needed
# and therefore, we ignore the generation
if len(bps) == 1:
return bps
try:
int_generation = int(generation)
# Check if generation is in available generations
if int_generation in [1, 2, 3]:
bps = [x for x in bps if int(x.get_attribute('generation')) == int_generation]
return bps
else:
print(" Warning! Actor Generation is not valid. No actor will be spawned.")
return []
except:
print(" Warning! Actor Generation is not valid. No actor will be spawned.")
return []
def generate_full_map_route(world):
"""Generate a route that covers the entire map"""
# Get the map
carla_map = world.get_map()
# Get all waypoints with a fixed distance
waypoint_list = carla_map.generate_waypoints(2.0) # Generate waypoints every 2 meters
# Filter waypoints to keep only one per road segment
filtered_waypoints = []
road_segments = set()
for wp in waypoint_list:
road_lane = (wp.road_id, wp.lane_id)
if road_lane not in road_segments:
road_segments.add(road_lane)
filtered_waypoints.append(wp)
return filtered_waypoints
def setup_full_map_navigation(world, vehicle):
"""Set up navigation to cover the entire map"""
# Set up the traffic manager with careful driving parameters
client = carla.Client('localhost', 2000) # Create a client to get traffic manager
traffic_manager = client.get_trafficmanager(8000) # Get traffic manager on port 8000
traffic_manager.set_global_distance_to_leading_vehicle(4.0) # Safer following distance
traffic_manager.global_percentage_speed_difference(-20) # Drive 20% slower than speed limit
traffic_manager.set_synchronous_mode(True)
# Set vehicle under traffic manager control
vehicle.set_autopilot(True, traffic_manager.get_port())
# Configure vehicle-specific behavior
traffic_manager.auto_lane_change(vehicle, True) # Enable automatic lane changes
traffic_manager.distance_to_leading_vehicle(vehicle, 5) # Vehicle-specific following distance
traffic_manager.vehicle_percentage_speed_difference(vehicle, -20) # Vehicle-specific speed
traffic_manager.ignore_lights_percentage(vehicle, 0) # Always obey traffic lights
traffic_manager.ignore_signs_percentage(vehicle, 0) # Always obey traffic signs
traffic_manager.ignore_vehicles_percentage(vehicle, 0) # Don't ignore other vehicles
traffic_manager.ignore_walkers_percentage(vehicle, 0) # Don't ignore pedestrians
# Let the traffic manager handle the navigation
# It will automatically explore the map while following traffic rules
print("Vehicle is now set to explore the map autonomously while following traffic rules")
return traffic_manager
# ==============================================================================
# -- World ---------------------------------------------------------------------
# ==============================================================================
class World(object):
def __init__(self, carla_world, hud, args):
self.world = carla_world
self.sync = args.sync
self.actor_role_name = args.rolename
self.recording_timer = args.timer
self.timer_quit = args.timer_quit
self.traverse_map = args.traverse_map
self.recording_start_time = None
self.coverage_threshold = args.coverage if hasattr(args, 'coverage') else 85.0 # Default 85% coverage
# Initialize map coverage tracking
self.visited_cells = set()
self.total_cells = 0
self.cell_size = 10 # Size of each grid cell in meters
self.coverage_percentage = 0.0
self.last_coverage_update = 0
try:
self.map = self.world.get_map()
# Initialize the coverage grid
self._init_coverage_grid()
except RuntimeError as error:
print('RuntimeError: {}'.format(error))
print(' The server could not send the OpenDRIVE (.xodr) file:')
print(' Make sure it exists, has the same name of your town, and is correct.')
sys.exit(1)
self.hud = hud
self.player = None
self.collision_sensor = None
self.lane_invasion_sensor = None
self.gnss_sensor = None
self.imu_sensor = None
self.radar_sensor = None
self.camera_manager = None
self._weather_presets = find_weather_presets()
self._weather_index = 0
self._actor_filter = args.filter
self._actor_generation = args.generation
self._gamma = args.gamma
self.restart()
self.world.on_tick(hud.on_world_tick)
self.recording_enabled = False
self.constant_velocity_enabled = False
self.show_vehicle_telemetry = False
self.doors_are_open = False
self.current_map_layer = 0
self.map_layer_names = [
carla.MapLayer.NONE,
carla.MapLayer.Buildings,
carla.MapLayer.Decals,
carla.MapLayer.Foliage,
carla.MapLayer.Ground,
carla.MapLayer.ParkedVehicles,
carla.MapLayer.Particles,
carla.MapLayer.Props,
carla.MapLayer.StreetLights,
carla.MapLayer.Walls,
carla.MapLayer.All
]
# Initialize traffic manager for map traversal if needed
if self.traverse_map:
self.traffic_manager = setup_full_map_navigation(self.world, self.player)
print("Full map traversal mode activated - Vehicle will systematically explore the entire map")
def _init_coverage_grid(self):
"""Initialize the grid for tracking map coverage."""
# Get map bounds
waypoints = self.map.generate_waypoints(2.0)
if not waypoints:
return
# Calculate map boundaries from waypoints
locations = [w.transform.location for w in waypoints]
min_x = min(loc.x for loc in locations)
max_x = max(loc.x for loc in locations)
min_y = min(loc.y for loc in locations)
max_y = max(loc.y for loc in locations)
# Add padding
padding = 50
min_x -= padding
max_x += padding
min_y -= padding
max_y += padding
# Calculate grid dimensions
self.grid_min_x = min_x
self.grid_min_y = min_y
self.grid_width = max_x - min_x
self.grid_height = max_y - min_y
# Calculate total cells (only count cells that contain roads)
road_cells = set()
for wp in waypoints:
cell_x = int((wp.transform.location.x - self.grid_min_x) / self.cell_size)
cell_y = int((wp.transform.location.y - self.grid_min_y) / self.cell_size)
road_cells.add((cell_x, cell_y))
self.total_cells = len(road_cells)
print(f"Map grid initialized with {self.total_cells} road cells")
def update_coverage(self):
"""Update the map coverage based on vehicle position."""
if not self.player or self.total_cells == 0:
return 0.0
# Get current position
location = self.player.get_location()
# Convert to grid cell
cell_x = int((location.x - self.grid_min_x) / self.cell_size)
cell_y = int((location.y - self.grid_min_y) / self.cell_size)
# Add to visited cells
self.visited_cells.add((cell_x, cell_y))
# Calculate coverage percentage
self.coverage_percentage = (len(self.visited_cells) / self.total_cells) * 100
# Update coverage less frequently to avoid spam
current_time = time.time()
if current_time - self.last_coverage_update >= 5: # Update every 5 seconds
print(f"\rMap Coverage: {self.coverage_percentage:.2f}%", end="")
self.last_coverage_update = current_time
# Write coverage to file
with open("current_coverage.txt", "w") as f:
f.write(f"{self.coverage_percentage:.2f}")
return self.coverage_percentage
def restart(self):
self.player_max_speed = 1.589
self.player_max_speed_fast = 3.713
# Keep same camera config if the camera manager exists.
cam_index = self.camera_manager.index if self.camera_manager is not None else 0
cam_pos_index = 1 # Force cockpit view
# Get a random blueprint.
blueprint_list = get_actor_blueprints(self.world, self._actor_filter, self._actor_generation)
if not blueprint_list:
raise ValueError("Couldn't find any blueprints with the specified filters")
blueprint = random.choice(blueprint_list)
blueprint.set_attribute('role_name', self.actor_role_name)
if blueprint.has_attribute('terramechanics'):
blueprint.set_attribute('terramechanics', 'true')
if blueprint.has_attribute('color'):
color = random.choice(blueprint.get_attribute('color').recommended_values)
blueprint.set_attribute('color', color)
if blueprint.has_attribute('driver_id'):
driver_id = random.choice(blueprint.get_attribute('driver_id').recommended_values)
blueprint.set_attribute('driver_id', driver_id)
if blueprint.has_attribute('is_invincible'):
blueprint.set_attribute('is_invincible', 'true')
# set the max speed
if blueprint.has_attribute('speed'):
self.player_max_speed = float(blueprint.get_attribute('speed').recommended_values[1])
self.player_max_speed_fast = float(blueprint.get_attribute('speed').recommended_values[2])
# Spawn the player.
if self.player is not None:
spawn_point = self.player.get_transform()
spawn_point.location.z += 2.0
spawn_point.rotation.roll = 0.0
spawn_point.rotation.pitch = 0.0
self.destroy()
self.player = self.world.try_spawn_actor(blueprint, spawn_point)
self.show_vehicle_telemetry = False
self.modify_vehicle_physics(self.player)
while self.player is None:
if not self.map.get_spawn_points():
print('There are no spawn points available in your map/town.')
print('Please add some Vehicle Spawn Point to your UE4 scene.')
sys.exit(1)
spawn_points = self.map.get_spawn_points()
spawn_point = random.choice(spawn_points) if spawn_points else carla.Transform()
self.player = self.world.try_spawn_actor(blueprint, spawn_point)
self.show_vehicle_telemetry = False
self.modify_vehicle_physics(self.player)
# Initialize traffic manager for map traversal if needed
if hasattr(self, 'traverse_map') and self.traverse_map:
self.traffic_manager = setup_full_map_navigation(self.world, self.player)
print("Full map traversal mode activated - Vehicle will systematically explore the entire map")
# Set up the sensors.
self.collision_sensor = CollisionSensor(self.player, self.hud)
self.lane_invasion_sensor = LaneInvasionSensor(self.player, self.hud)
self.gnss_sensor = GnssSensor(self.player)
self.imu_sensor = IMUSensor(self.player)
self.camera_manager = CameraManager(self.player, self.hud, self._gamma)
self.camera_manager.transform_index = cam_pos_index
self.camera_manager.set_sensor(cam_index, notify=False)
actor_type = get_actor_display_name(self.player)
self.hud.notification(actor_type)
if self.sync:
self.world.tick()
else:
self.world.wait_for_tick()
def next_weather(self, reverse=False):
self._weather_index += -1 if reverse else 1
self._weather_index %= len(self._weather_presets)
preset = self._weather_presets[self._weather_index]
self.hud.notification('Weather: %s' % preset[1])
self.player.get_world().set_weather(preset[0])
def next_map_layer(self, reverse=False):
self.current_map_layer += -1 if reverse else 1
self.current_map_layer %= len(self.map_layer_names)
selected = self.map_layer_names[self.current_map_layer]
self.hud.notification('LayerMap selected: %s' % selected)
def load_map_layer(self, unload=False):
selected = self.map_layer_names[self.current_map_layer]
if unload:
self.hud.notification('Unloading map layer: %s' % selected)
self.world.unload_map_layer(selected)
else:
self.hud.notification('Loading map layer: %s' % selected)
self.world.load_map_layer(selected)
def toggle_radar(self):
if self.radar_sensor is None:
self.radar_sensor = RadarSensor(self.player)
elif self.radar_sensor.sensor is not None:
self.radar_sensor.sensor.destroy()
self.radar_sensor = None
def modify_vehicle_physics(self, actor):
#If actor is not a vehicle, we cannot use the physics control
try:
physics_control = actor.get_physics_control()
physics_control.use_sweep_wheel_collision = True
actor.apply_physics_control(physics_control)
except Exception:
pass
def tick(self, clock):
self.hud.tick(self, clock)
# Update map coverage
coverage = self.update_coverage()
# Check if coverage threshold is met
if coverage >= self.coverage_threshold:
print(f"\nMap coverage threshold ({self.coverage_threshold}%) reached!")
if self.timer_quit:
return True
# Handle recording timer if active
if self.recording_timer > 0:
# Initialize recording start time when recording begins
if self.camera_manager.recording and self.recording_start_time is None:
self.recording_start_time = time.time()
print(f"\nRecording started - Timer set for {self.recording_timer}s")
# Check if recording is active and timer has expired
if self.camera_manager.recording and self.recording_start_time is not None:
elapsed = time.time() - self.recording_start_time
if elapsed >= self.recording_timer:
print(f"\nRecording timer ({self.recording_timer}s) expired!")
self.camera_manager.toggle_recording()
self.recording_start_time = None
if self.timer_quit:
print("Timer quit enabled - exiting...")
return True
return False # Continue running
def render(self, display):
self.camera_manager.render(display)
self.hud.render(display)
def destroy_sensors(self):
self.camera_manager.sensor.destroy()
self.camera_manager.sensor = None
self.camera_manager.index = None
def destroy(self):
try:
if self.radar_sensor is not None:
self.toggle_radar()
sensors = [
self.camera_manager.sensor,
self.collision_sensor.sensor,
self.lane_invasion_sensor.sensor,
self.gnss_sensor.sensor,
self.imu_sensor.sensor]
for sensor in sensors:
if sensor is not None and sensor.is_alive:
sensor.stop()
sensor.destroy()
# Destroy camera manager sensors separately
if self.camera_manager is not None:
self.camera_manager.destroy_sensors()
if self.player is not None and self.player.is_alive:
self.player.destroy()
# Clear references
self.radar_sensor = None
self.camera_manager = None
self.collision_sensor = None
self.lane_invasion_sensor = None
self.gnss_sensor = None
self.imu_sensor = None
self.player = None
except Exception as e:
print(f"Warning: Error during world cleanup: {e}")
# ==============================================================================
# -- KeyboardControl -----------------------------------------------------------
# ==============================================================================
class KeyboardControl(object):
"""Class that handles keyboard input."""
def __init__(self, world, start_in_autopilot):
self._autopilot_enabled = start_in_autopilot
self._ackermann_enabled = False
self._ackermann_reverse = 1
if isinstance(world.player, carla.Vehicle):
self._control = carla.VehicleControl()
self._ackermann_control = carla.VehicleAckermannControl()
self._lights = carla.VehicleLightState.NONE
world.player.set_autopilot(self._autopilot_enabled)
world.player.set_light_state(self._lights)
elif isinstance(world.player, carla.Walker):
self._control = carla.WalkerControl()
self._autopilot_enabled = False
self._rotation = world.player.get_transform().rotation
else:
raise NotImplementedError("Actor type not supported")
self._steer_cache = 0.0
world.hud.notification("Press 'H' or '?' for help.", seconds=4.0)
def parse_events(self, client, world, clock, sync_mode):
if isinstance(self._control, carla.VehicleControl):
current_lights = self._lights
for event in pygame.event.get():
if event.type == pygame.QUIT:
return True
elif event.type == pygame.KEYUP:
if self._is_quit_shortcut(event.key):
return True
elif event.key == K_BACKSPACE:
if self._autopilot_enabled:
world.player.set_autopilot(False)
world.restart()
world.player.set_autopilot(True)
else:
world.restart()
elif event.key == K_F1:
world.hud.toggle_info()
elif event.key == K_v and pygame.key.get_mods() & KMOD_SHIFT:
world.next_map_layer(reverse=True)
elif event.key == K_v:
world.next_map_layer()
elif event.key == K_b and pygame.key.get_mods() & KMOD_SHIFT:
world.load_map_layer(unload=True)
elif event.key == K_b:
world.load_map_layer()
elif event.key == K_TAB:
world.camera_manager.toggle_camera()
elif event.key == K_h or (event.key == K_SLASH and pygame.key.get_mods() & KMOD_SHIFT):
world.hud.help.toggle()
elif event.key == K_c and pygame.key.get_mods() & KMOD_SHIFT:
world.next_weather(reverse=True)
elif event.key == K_c:
world.next_weather()
elif event.key == K_g:
world.toggle_radar()
elif event.key == K_BACKQUOTE:
world.camera_manager.next_sensor()
elif event.key == K_n:
world.camera_manager.next_sensor()
elif event.key == K_w and (pygame.key.get_mods() & KMOD_CTRL):
if world.constant_velocity_enabled:
world.player.disable_constant_velocity()
world.constant_velocity_enabled = False
world.hud.notification("Disabled Constant Velocity Mode")
else:
world.player.enable_constant_velocity(carla.Vector3D(17, 0, 0))
world.constant_velocity_enabled = True
world.hud.notification("Enabled Constant Velocity Mode at 60 km/h")
elif event.key == K_o:
try:
if world.doors_are_open:
world.hud.notification("Closing Doors")
world.doors_are_open = False
world.player.close_door(carla.VehicleDoor.All)
else:
world.hud.notification("Opening doors")
world.doors_are_open = True
world.player.open_door(carla.VehicleDoor.All)
except Exception:
pass
elif event.key == K_t:
if world.show_vehicle_telemetry:
world.player.show_debug_telemetry(False)
world.show_vehicle_telemetry = False
world.hud.notification("Disabled Vehicle Telemetry")
else:
try:
world.player.show_debug_telemetry(True)
world.show_vehicle_telemetry = True
world.hud.notification("Enabled Vehicle Telemetry")
except Exception:
pass
elif event.key > K_0 and event.key <= K_9:
index_ctrl = 0
if pygame.key.get_mods() & KMOD_CTRL:
index_ctrl = 9
world.camera_manager.set_sensor(event.key - 1 - K_0 + index_ctrl)
elif event.key == K_r and not (pygame.key.get_mods() & KMOD_CTRL):
world.camera_manager.toggle_recording()
elif event.key == K_r and (pygame.key.get_mods() & KMOD_CTRL):
if (world.recording_enabled):
client.stop_recorder()
world.recording_enabled = False
world.hud.notification("Recorder is OFF")
else:
client.start_recorder("manual_recording.rec")
world.recording_enabled = True
world.hud.notification("Recorder is ON")
elif event.key == K_p and (pygame.key.get_mods() & KMOD_CTRL):
# stop recorder
client.stop_recorder()
world.recording_enabled = False
# work around to fix camera at start of replaying
current_index = world.camera_manager.index
world.destroy_sensors()
# disable autopilot
self._autopilot_enabled = False
world.player.set_autopilot(self._autopilot_enabled)
world.hud.notification("Replaying file 'manual_recording.rec'")
# replayer
client.replay_file("manual_recording.rec", world.recording_start, 0, 0)
world.camera_manager.set_sensor(current_index)
elif event.key == K_MINUS and (pygame.key.get_mods() & KMOD_CTRL):
if pygame.key.get_mods() & KMOD_SHIFT:
world.recording_start -= 10
else:
world.recording_start -= 1
world.hud.notification("Recording start time is %d" % (world.recording_start))
elif event.key == K_EQUALS and (pygame.key.get_mods() & KMOD_CTRL):
if pygame.key.get_mods() & KMOD_SHIFT:
world.recording_start += 10
else:
world.recording_start += 1
world.hud.notification("Recording start time is %d" % (world.recording_start))
if isinstance(self._control, carla.VehicleControl):
if event.key == K_f:
# Toggle ackermann controller
self._ackermann_enabled = not self._ackermann_enabled
world.hud.show_ackermann_info(self._ackermann_enabled)
world.hud.notification("Ackermann Controller %s" %
("Enabled" if self._ackermann_enabled else "Disabled"))
if event.key == K_q:
if not self._ackermann_enabled:
self._control.gear = 1 if self._control.reverse else -1
else:
self._ackermann_reverse *= -1
# Reset ackermann control
self._ackermann_control = carla.VehicleAckermannControl()
elif event.key == K_m:
self._control.manual_gear_shift = not self._control.manual_gear_shift
self._control.gear = world.player.get_control().gear
world.hud.notification('%s Transmission' %
('Manual' if self._control.manual_gear_shift else 'Automatic'))
elif self._control.manual_gear_shift and event.key == K_COMMA:
self._control.gear = max(-1, self._control.gear - 1)
elif self._control.manual_gear_shift and event.key == K_PERIOD:
self._control.gear = self._control.gear + 1
elif event.key == K_p and not pygame.key.get_mods() & KMOD_CTRL:
if not self._autopilot_enabled and not sync_mode:
print("WARNING: You are currently in asynchronous mode and could "
"experience some issues with the traffic simulation")
self._autopilot_enabled = not self._autopilot_enabled
world.player.set_autopilot(self._autopilot_enabled)
world.hud.notification(
'Autopilot %s' % ('On' if self._autopilot_enabled else 'Off'))
elif event.key == K_l and pygame.key.get_mods() & KMOD_CTRL:
current_lights ^= carla.VehicleLightState.Special1
elif event.key == K_l and pygame.key.get_mods() & KMOD_SHIFT:
current_lights ^= carla.VehicleLightState.HighBeam
elif event.key == K_l:
# Use 'L' key to switch between lights:
# closed -> position -> low beam -> fog
if not self._lights & carla.VehicleLightState.Position:
world.hud.notification("Position lights")
current_lights |= carla.VehicleLightState.Position
else:
world.hud.notification("Low beam lights")
current_lights |= carla.VehicleLightState.LowBeam
if self._lights & carla.VehicleLightState.LowBeam:
world.hud.notification("Fog lights")
current_lights |= carla.VehicleLightState.Fog
if self._lights & carla.VehicleLightState.Fog:
world.hud.notification("Lights off")
current_lights ^= carla.VehicleLightState.Position
current_lights ^= carla.VehicleLightState.LowBeam
current_lights ^= carla.VehicleLightState.Fog
elif event.key == K_i:
current_lights ^= carla.VehicleLightState.Interior
elif event.key == K_z:
current_lights ^= carla.VehicleLightState.LeftBlinker
elif event.key == K_x:
current_lights ^= carla.VehicleLightState.RightBlinker
if not self._autopilot_enabled:
if isinstance(self._control, carla.VehicleControl):
self._parse_vehicle_keys(pygame.key.get_pressed(), clock.get_time())
self._control.reverse = self._control.gear < 0
# Set automatic control-related vehicle lights
if self._control.brake:
current_lights |= carla.VehicleLightState.Brake
else: # Remove the Brake flag
current_lights &= ~carla.VehicleLightState.Brake
if self._control.reverse:
current_lights |= carla.VehicleLightState.Reverse
else: # Remove the Reverse flag
current_lights &= ~carla.VehicleLightState.Reverse
if current_lights != self._lights: # Change the light state only if necessary
self._lights = current_lights
world.player.set_light_state(carla.VehicleLightState(self._lights))
# Apply control
if not self._ackermann_enabled:
world.player.apply_control(self._control)
else:
world.player.apply_ackermann_control(self._ackermann_control)
# Update control to the last one applied by the ackermann controller.
self._control = world.player.get_control()
# Update hud with the newest ackermann control
world.hud.update_ackermann_control(self._ackermann_control)
elif isinstance(self._control, carla.WalkerControl):
self._parse_walker_keys(pygame.key.get_pressed(), clock.get_time(), world)
world.player.apply_control(self._control)
def _parse_vehicle_keys(self, keys, milliseconds):
if keys[K_UP] or keys[K_w]:
if not self._ackermann_enabled:
self._control.throttle = min(self._control.throttle + 0.1, 1.00)
else:
self._ackermann_control.speed += round(milliseconds * 0.005, 2) * self._ackermann_reverse
else:
if not self._ackermann_enabled:
self._control.throttle = 0.0
if keys[K_DOWN] or keys[K_s]:
if not self._ackermann_enabled:
self._control.brake = min(self._control.brake + 0.2, 1)
else:
self._ackermann_control.speed -= min(abs(self._ackermann_control.speed), round(milliseconds * 0.005, 2)) * self._ackermann_reverse
self._ackermann_control.speed = max(0, abs(self._ackermann_control.speed)) * self._ackermann_reverse
else:
if not self._ackermann_enabled:
self._control.brake = 0
steer_increment = 5e-4 * milliseconds
if keys[K_LEFT] or keys[K_a]:
if self._steer_cache > 0:
self._steer_cache = 0
else:
self._steer_cache -= steer_increment
elif keys[K_RIGHT] or keys[K_d]:
if self._steer_cache < 0:
self._steer_cache = 0
else:
self._steer_cache += steer_increment
else:
self._steer_cache = 0.0
self._steer_cache = min(0.7, max(-0.7, self._steer_cache))
if not self._ackermann_enabled:
self._control.steer = round(self._steer_cache, 1)
self._control.hand_brake = keys[K_SPACE]
else:
self._ackermann_control.steer = round(self._steer_cache, 1)
def _parse_walker_keys(self, keys, milliseconds, world):
self._control.speed = 0.0
if keys[K_DOWN] or keys[K_s]:
self._control.speed = 0.0
if keys[K_LEFT] or keys[K_a]:
self._control.speed = .01
self._rotation.yaw -= 0.08 * milliseconds
if keys[K_RIGHT] or keys[K_d]:
self._control.speed = .01
self._rotation.yaw += 0.08 * milliseconds
if keys[K_UP] or keys[K_w]:
self._control.speed = world.player_max_speed_fast if pygame.key.get_mods() & KMOD_SHIFT else world.player_max_speed
self._control.jump = keys[K_SPACE]
self._rotation.yaw = round(self._rotation.yaw, 1)
self._control.direction = self._rotation.get_forward_vector()
@staticmethod
def _is_quit_shortcut(key):
return (key == K_ESCAPE) or (key == K_q and pygame.key.get_mods() & KMOD_CTRL)
# ==============================================================================
# -- HUD -----------------------------------------------------------------------
# ==============================================================================
class HUD(object):
def __init__(self, width, height):
self.dim = (width, height)
font = pygame.font.Font(pygame.font.get_default_font(), 20)
font_name = 'courier' if os.name == 'nt' else 'mono'
fonts = [x for x in pygame.font.get_fonts() if font_name in x]
default_font = 'ubuntumono'
mono = default_font if default_font in fonts else fonts[0]
mono = pygame.font.match_font(mono)
self._font_mono = pygame.font.Font(mono, 12 if os.name == 'nt' else 14)
self._notifications = FadingText(font, (width, 40), (0, height - 40))
self.help = HelpText(pygame.font.Font(mono, 16), width, height)
self.server_fps = 0
self.frame = 0
self.simulation_time = 0
self._show_info = True
self._info_text = []
self._server_clock = pygame.time.Clock()
self._show_ackermann_info = False
self._ackermann_control = carla.VehicleAckermannControl()
# Timer display attributes
self._timer_font = pygame.font.Font(mono, 48) # Larger font for timer
self._timer_surface = None
self._last_recording_state = False
def on_world_tick(self, timestamp):
self._server_clock.tick()
self.server_fps = self._server_clock.get_fps()
self.frame = timestamp.frame
self.simulation_time = timestamp.elapsed_seconds
def tick(self, world, clock):
self._notifications.tick(world, clock)
if not self._show_info:
return
# Update timer display if recording with timer
timer_text = None
if world.camera_manager.recording and world.recording_timer > 0:
if world.recording_start_time is not None:
elapsed = time.time() - world.recording_start_time
remaining = max(0, world.recording_timer - elapsed)
minutes = int(remaining // 60)
seconds = int(remaining % 60)
timer_text = f"{minutes:02d}:{seconds:02d}"
# Create timer surface with red background if less than 10 seconds remaining
color = (255, 0, 0) if remaining < 10 else (255, 255, 255)
self._timer_surface = self._timer_font.render(timer_text, True, color)
# Handle recording state change
if not self._last_recording_state:
self.notification(f'Recording started - Timer set for {world.recording_timer}s')
self._last_recording_state = True
else:
self._timer_surface = None
if self._last_recording_state: