-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1289 lines (1064 loc) · 41.8 KB
/
main.py
File metadata and controls
1289 lines (1064 loc) · 41.8 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
"""
SYNAPSCAPE FSD Simulator - Main Orchestrator
=============================================
"Mapping the Neural Road" - Central orchestration module for the SYNAPSCAPE
Full Self-Driving Simulator. Manages all 13 autonomous agents, game loop,
training mode, and system coordination.
This module provides:
- SynapscapeOrchestrator: Central management class for all simulator components
- Game loop with delta time calculation and event handling
- Keyboard controls for manual and autonomous driving
- Training mode with PPO updates
- Performance monitoring and graceful shutdown
Author: SYNAPSCAPE Team
Version: 2.0.0
License: MIT
Python: >=3.11
PyTorch: >=2.0
PyGame: >=2.0
"""
import sys
import time
import argparse
import logging
from typing import Optional, Dict, Any, List, Tuple, Callable
from dataclasses import dataclass, field
from enum import Enum, auto
from pathlib import Path
import signal
import threading
from collections import deque
import numpy as np
import pygame
from pygame.locals import *
# Configure logging before other imports
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('logs/synapscape.log', mode='a')
]
)
logger = logging.getLogger("SYNAPSCAPE")
# Import configuration
try:
from config import (
PROJECT_NAME, PROJECT_VERSION, PROJECT_TAGLINE, VERSION_INFO,
SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_SIZE, TARGET_FPS, TARGET_DT,
DisplayMode, DEFAULT_COLORS, DEFAULT_DEBUG, Paths, DEFAULT_RANDOM_SEED,
KM_H_TO_M_S, M_S_TO_KM_H, DEG_TO_RAD, RAD_TO_DEG
)
except ImportError as e:
logger.error(f"Failed to import configuration: {e}")
raise
# =============================================================================
# TYPE DEFINITIONS
# =============================================================================
class SimulationState(Enum):
"""Simulation runtime states."""
INITIALIZING = auto()
READY = auto()
RUNNING = auto()
PAUSED = auto()
TRAINING = auto()
SHUTTING_DOWN = auto()
ERROR = auto()
class ControlMode(Enum):
"""Vehicle control modes."""
MANUAL = auto() # Human driver
AUTONOMOUS = auto() # AI driver
TRAINING = auto() # Training mode with PPO
class CameraView(Enum):
"""Available camera views."""
DRIVER = auto() # Driver's perspective
CHASE = auto() # Chase camera behind vehicle
TOP_DOWN = auto() # Top-down view
FRONT = auto() # Front bumper camera
BIRD_EYE = auto() # Bird's eye view
SENSOR = auto() # Sensor visualization view
@dataclass
class PerformanceMetrics:
"""Real-time performance metrics."""
fps: float = 0.0
frame_time_ms: float = 0.0
physics_time_ms: float = 0.0
render_time_ms: float = 0.0
ai_time_ms: float = 0.0
memory_mb: float = 0.0
step_count: int = 0
episode_count: int = 0
total_steps: int = 0
# History for averaging
_fps_history: deque = field(default_factory=lambda: deque(maxlen=60))
_frame_time_history: deque = field(default_factory=lambda: deque(maxlen=60))
def update(self, fps: float, frame_time: float):
"""Update metrics with new values."""
self._fps_history.append(fps)
self._frame_time_history.append(frame_time)
self.fps = np.mean(self._fps_history)
self.frame_time_ms = np.mean(self._frame_time_history) * 1000
self.step_count += 1
self.total_steps += 1
@dataclass
class InputState:
"""Current input state."""
throttle: float = 0.0 # -1.0 to 1.0
steering: float = 0.0 # -1.0 to 1.0 (left to right)
brake: float = 0.0 # 0.0 to 1.0
handbrake: bool = False
# Action flags
reset_requested: bool = False
camera_cycle: bool = False
inspector_toggle: bool = False
emergency_brake: bool = False
training_toggle: bool = False
pause_toggle: bool = False
# =============================================================================
# AGENT INTERFACES (Stubs for compilation)
# =============================================================================
class AgentInterface:
"""Base interface for all simulator agents."""
def __init__(self, name: str, config: Optional[Dict[str, Any]] = None):
self.name = name
self.config = config or {}
self.enabled = True
self.initialized = False
self.logger = logging.getLogger(f"SYNAPSCAPE.{name}")
def initialize(self) -> bool:
"""Initialize the agent. Returns True on success."""
self.initialized = True
return True
def update(self, dt: float, **kwargs) -> Dict[str, Any]:
"""Update agent state. Returns output data."""
return {}
def shutdown(self):
"""Clean shutdown of the agent."""
self.initialized = False
def reset(self):
"""Reset agent state."""
pass
class WorldBuilderAgent(AgentInterface):
"""Agent responsible for world/scene construction."""
def __init__(self, config: Optional[Dict[str, Any]] = None):
super().__init__("WorldBuilder", config)
self.map_data: Optional[Any] = None
self.road_network: Optional[Any] = None
def load_map(self, map_path: str) -> bool:
"""Load a map from file."""
self.logger.info(f"Loading map: {map_path}")
return True
def spawn_vehicle(self, position: Tuple[float, float, float]) -> Any:
"""Spawn ego vehicle at position."""
return None
class PhysicsEngineAgent(AgentInterface):
"""Agent responsible for physics simulation."""
def __init__(self, config: Optional[Dict[str, Any]] = None):
super().__init__("PhysicsEngine", config)
self.vehicle_state: Optional[Dict[str, Any]] = None
self.gravity: float = 9.81
def step(self, dt: float, controls: InputState) -> Dict[str, Any]:
"""Execute physics step."""
return {"position": (0.0, 0.0, 0.0), "velocity": (0.0, 0.0, 0.0)}
def get_vehicle_state(self) -> Dict[str, Any]:
"""Get current vehicle state."""
return self.vehicle_state or {}
class SensorFusionAgent(AgentInterface):
"""Agent responsible for sensor data fusion."""
def __init__(self, config: Optional[Dict[str, Any]] = None):
super().__init__("SensorFusion", config)
self.camera_data: List[np.ndarray] = []
self.lidar_data: Optional[np.ndarray] = None
self.radar_data: Optional[np.ndarray] = None
self.imu_data: Optional[Dict[str, float]] = None
def get_fused_perception(self) -> Dict[str, Any]:
"""Get fused sensor perception output."""
return {
"camera": self.camera_data,
"lidar": self.lidar_data,
"radar": self.radar_data,
"imu": self.imu_data
}
class PerceptionAgent(AgentInterface):
"""Agent responsible for neural perception."""
def __init__(self, config: Optional[Dict[str, Any]] = None):
super().__init__("Perception", config)
self.detected_objects: List[Dict[str, Any]] = []
self.lane_detection: Optional[Dict[str, Any]] = None
self.traffic_signs: List[Dict[str, Any]] = []
def process(self, sensor_data: Dict[str, Any]) -> Dict[str, Any]:
"""Process sensor data through neural networks."""
return {
"objects": self.detected_objects,
"lanes": self.lane_detection,
"signs": self.traffic_signs
}
class PredictionAgent(AgentInterface):
"""Agent responsible for trajectory prediction."""
def __init__(self, config: Optional[Dict[str, Any]] = None):
super().__init__("Prediction", config)
self.predicted_trajectories: Dict[int, List[Tuple[float, float]]] = {}
self.prediction_horizon: float = 3.0 # seconds
def predict(self, detected_objects: List[Dict[str, Any]],
dt: float) -> Dict[int, List[Tuple[float, float]]]:
"""Predict future trajectories for detected objects."""
return self.predicted_trajectories
class DecisionAgent(AgentInterface):
"""Agent responsible for high-level decision making."""
def __init__(self, config: Optional[Dict[str, Any]] = None):
super().__init__("Decision", config)
self.current_action: str = "cruise"
self.target_speed: float = 0.0
self.target_lane: int = 0
def decide(self, perception: Dict[str, Any],
predictions: Dict[int, Any]) -> Dict[str, Any]:
"""Make driving decisions based on perception and predictions."""
return {
"action": self.current_action,
"target_speed": self.target_speed,
"target_lane": self.target_lane
}
class ADASAgent(AgentInterface):
"""Agent responsible for ADAS features."""
def __init__(self, config: Optional[Dict[str, Any]] = None):
super().__init__("ADAS", config)
self.tacc_enabled: bool = False
self.aeb_enabled: bool = True
self.lka_enabled: bool = True
self.ttc: float = float('inf')
def update_adas(self, vehicle_state: Dict[str, Any],
perception: Dict[str, Any]) -> Dict[str, Any]:
"""Update ADAS systems."""
interventions = {}
if self.aeb_enabled and self.ttc < 1.0:
interventions["emergency_brake"] = True
return interventions
class SafetyMonitorAgent(AgentInterface):
"""Agent responsible for safety monitoring."""
def __init__(self, config: Optional[Dict[str, Any]] = None):
super().__init__("SafetyMonitor", config)
self.safety_score: float = 100.0
self.violations: List[Dict[str, Any]] = []
self.is_safe: bool = True
def check_safety(self, state: Dict[str, Any],
controls: InputState) -> Dict[str, Any]:
"""Check safety conditions."""
return {
"safe": self.is_safe,
"score": self.safety_score,
"violations": self.violations
}
class RewardShapingAgent(AgentInterface):
"""Agent responsible for reward shaping in RL."""
def __init__(self, config: Optional[Dict[str, Any]] = None):
super().__init__("RewardShaping", config)
self.current_reward: float = 0.0
self.episode_reward: float = 0.0
self.reward_history: deque = deque(maxlen=100)
def calculate_reward(self, state: Dict[str, Any],
action: InputState,
next_state: Dict[str, Any]) -> float:
"""Calculate reward for RL."""
reward = 0.0
self.current_reward = reward
self.episode_reward += reward
return reward
def get_episode_reward(self) -> float:
"""Get total episode reward."""
return self.episode_reward
def reset_episode(self):
"""Reset episode reward tracking."""
self.reward_history.append(self.episode_reward)
self.episode_reward = 0.0
class LearningOrchestratorAgent(AgentInterface):
"""Agent responsible for RL training orchestration."""
def __init__(self, config: Optional[Dict[str, Any]] = None):
super().__init__("LearningOrchestrator", config)
self.is_training: bool = False
self.episode_count: int = 0
self.step_count: int = 0
self.model_path: str = Paths.CHECKPOINTS_DIR
def start_training(self):
"""Start training mode."""
self.is_training = True
self.logger.info("Training mode activated")
def stop_training(self):
"""Stop training mode."""
self.is_training = False
self.logger.info("Training mode deactivated")
def update_policy(self, batch_data: Dict[str, Any]) -> Dict[str, float]:
"""Update policy with PPO."""
return {"loss": 0.0, "value_loss": 0.0, "entropy": 0.0}
def save_model(self, path: str) -> bool:
"""Save model checkpoint."""
self.logger.info(f"Saving model to {path}")
return True
def load_model(self, path: str) -> bool:
"""Load model checkpoint."""
self.logger.info(f"Loading model from {path}")
return True
class VisualizerAgent(AgentInterface):
"""Agent responsible for visualization and rendering."""
def __init__(self, config: Optional[Dict[str, Any]] = None):
super().__init__("Visualizer", config)
self.screen: Optional[pygame.Surface] = None
self.camera_view: CameraView = CameraView.DRIVER
self.show_hud: bool = True
self.show_sensor_overlay: bool = False
def initialize_display(self, width: int, height: int) -> bool:
"""Initialize display surface."""
pygame.display.init()
self.screen = pygame.display.set_mode(
(width, height),
pygame.DOUBLEBUF | pygame.HWSURFACE
)
pygame.display.set_caption(VERSION_INFO)
return True
def render(self, world_state: Dict[str, Any],
perception: Dict[str, Any],
metrics: PerformanceMetrics) -> pygame.Surface:
"""Render the scene."""
if self.screen:
self.screen.fill(DEFAULT_COLORS.background_dark)
return self.screen
def cycle_camera(self):
"""Cycle through camera views."""
views = list(CameraView)
current_idx = views.index(self.camera_view)
self.camera_view = views[(current_idx + 1) % len(views)]
self.logger.info(f"Camera view: {self.camera_view.name}")
class InspectorConsoleAgent(AgentInterface):
"""Agent responsible for debug inspector console."""
def __init__(self, config: Optional[Dict[str, Any]] = None):
super().__init__("InspectorConsole", config)
self.visible: bool = False
self.width: int = 400
self.log_messages: deque = deque(maxlen=100)
self.metrics_display: Dict[str, Any] = {}
def toggle(self):
"""Toggle inspector visibility."""
self.visible = not self.visible
def log(self, message: str, level: str = "INFO"):
"""Log message to inspector."""
self.log_messages.append({"time": time.time(), "level": level, "msg": message})
def render(self, screen: pygame.Surface,
metrics: PerformanceMetrics,
agents: Dict[str, AgentInterface]) -> pygame.Surface:
"""Render inspector overlay."""
if not self.visible:
return screen
# Render inspector panel
return screen
# =============================================================================
# MAIN ORCHESTRATOR
# =============================================================================
class SynapscapeOrchestrator:
"""
Central orchestrator for the SYNAPSCAPE FSD Simulator.
Manages all 13 autonomous agents, coordinates the game loop,
handles input, training mode, and system lifecycle.
Attributes:
state: Current simulation state
control_mode: Current vehicle control mode
agents: Dictionary of all managed agents
metrics: Performance metrics tracking
running: Flag indicating if main loop is running
"""
def __init__(self, config: Optional[Dict[str, Any]] = None):
"""
Initialize the orchestrator.
Args:
config: Optional configuration dictionary
"""
self.config = config or {}
self.state = SimulationState.INITIALIZING
self.control_mode = ControlMode.MANUAL
self.camera_view = CameraView.DRIVER
# Performance tracking
self.metrics = PerformanceMetrics()
self.input_state = InputState()
# Timing
self.clock = pygame.time.Clock()
self.last_frame_time = time.time()
self.delta_time = TARGET_DT
self.time_scale = 1.0
# Agent registry
self.agents: Dict[str, AgentInterface] = {}
# Shutdown flag
self._shutdown_requested = False
self._shutdown_complete = False
# Training state
self.training_enabled = False
self.episode_in_progress = False
self.episode_start_time = 0.0
# Setup signal handlers
self._setup_signal_handlers()
logger.info(f"{PROJECT_NAME} Orchestrator initialized")
def _setup_signal_handlers(self):
"""Setup OS signal handlers for graceful shutdown."""
def signal_handler(signum, frame):
logger.info(f"Received signal {signum}, initiating shutdown...")
self.request_shutdown()
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# Windows doesn't have SIGQUIT
if hasattr(signal, 'SIGQUIT'):
signal.signal(signal.SIGQUIT, signal_handler)
# =====================================================================
# AGENT INITIALIZATION
# =====================================================================
def initialize_agents(self) -> bool:
"""
Initialize all 13 agents in the correct sequence.
Initialization order:
1. WorldBuilder - Scene construction
2. PhysicsEngine - Physics simulation
3. SensorFusion - Sensor data integration
4. Perception - Neural perception
5. Prediction - Trajectory prediction
6. Decision - High-level decisions
7. ADAS - Advanced driver assistance
8. SafetyMonitor - Safety monitoring
9. RewardShaping - RL reward calculation
10. LearningOrchestrator - Training management
11. Visualizer - Rendering
12. InspectorConsole - Debug console
Returns:
True if all agents initialized successfully
"""
logger.info("Initializing agents...")
try:
# 1. WorldBuilder - Scene construction
self.agents["world_builder"] = WorldBuilderAgent(
self.config.get("world_builder")
)
# 2. PhysicsEngine - Physics simulation
self.agents["physics_engine"] = PhysicsEngineAgent(
self.config.get("physics_engine")
)
# 3. SensorFusion - Sensor data integration
self.agents["sensor_fusion"] = SensorFusionAgent(
self.config.get("sensor_fusion")
)
# 4. Perception - Neural perception
self.agents["perception"] = PerceptionAgent(
self.config.get("perception")
)
# 5. Prediction - Trajectory prediction
self.agents["prediction"] = PredictionAgent(
self.config.get("prediction")
)
# 6. Decision - High-level decisions
self.agents["decision"] = DecisionAgent(
self.config.get("decision")
)
# 7. ADAS - Advanced driver assistance
self.agents["adas"] = ADASAgent(
self.config.get("adas")
)
# 8. SafetyMonitor - Safety monitoring
self.agents["safety_monitor"] = SafetyMonitorAgent(
self.config.get("safety_monitor")
)
# 9. RewardShaping - RL reward calculation
self.agents["reward_shaping"] = RewardShapingAgent(
self.config.get("reward_shaping")
)
# 10. LearningOrchestrator - Training management
self.agents["learning_orchestrator"] = LearningOrchestratorAgent(
self.config.get("learning_orchestrator")
)
# 11. Visualizer - Rendering
self.agents["visualizer"] = VisualizerAgent(
self.config.get("visualizer")
)
# 12. InspectorConsole - Debug console
self.agents["inspector_console"] = InspectorConsoleAgent(
self.config.get("inspector_console")
)
# Initialize each agent in sequence
for name, agent in self.agents.items():
logger.info(f"Initializing {name}...")
if not agent.initialize():
logger.error(f"Failed to initialize {name}")
return False
logger.info(f"{name} initialized successfully")
# Initialize display
visualizer = self.agents.get("visualizer")
if visualizer:
visualizer.initialize_display(SCREEN_WIDTH, SCREEN_HEIGHT)
self.state = SimulationState.READY
logger.info("All agents initialized successfully")
return True
except Exception as e:
logger.error(f"Agent initialization failed: {e}")
self.state = SimulationState.ERROR
return False
# =====================================================================
# GAME LOOP
# =====================================================================
def run(self):
"""Main game loop."""
if self.state != SimulationState.READY:
logger.error("Orchestrator not ready. Call initialize_agents() first.")
return
logger.info("Starting main loop...")
self.state = SimulationState.RUNNING
self.last_frame_time = time.time()
try:
while not self._shutdown_requested:
# Calculate delta time
current_time = time.time()
self.delta_time = min(current_time - self.last_frame_time, 0.1) # Cap at 100ms
self.last_frame_time = current_time
# Handle events
self._handle_events()
# Update simulation
if self.state == SimulationState.RUNNING:
self._update(self.delta_time)
# Render
self._render()
# Update metrics
fps = self.clock.get_fps()
self.metrics.update(fps, self.delta_time)
# Cap frame rate
self.clock.tick(TARGET_FPS)
except Exception as e:
logger.error(f"Main loop error: {e}")
self.state = SimulationState.ERROR
raise
finally:
self.shutdown()
def _handle_events(self):
"""Process pygame events and keyboard input."""
# Reset per-frame input flags
self.input_state.reset_requested = False
self.input_state.camera_cycle = False
self.input_state.inspector_toggle = False
self.input_state.emergency_brake = False
self.input_state.training_toggle = False
self.input_state.pause_toggle = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.request_shutdown()
return
elif event.type == pygame.KEYDOWN:
# Training mode toggle (T)
if event.key == pygame.K_t:
self.input_state.training_toggle = True
self._toggle_training_mode()
# Reset (R)
elif event.key == pygame.K_r:
self.input_state.reset_requested = True
self._reset_simulation()
# Camera cycle (C)
elif event.key == pygame.K_c:
self.input_state.camera_cycle = True
self._cycle_camera()
# Inspector toggle (I)
elif event.key == pygame.K_i:
self.input_state.inspector_toggle = True
self._toggle_inspector()
# Emergency brake (SPACE)
elif event.key == pygame.K_SPACE:
self.input_state.emergency_brake = True
self._emergency_brake()
# Pause (P)
elif event.key == pygame.K_p:
self.input_state.pause_toggle = True
self._toggle_pause()
# Escape to quit
elif event.key == pygame.K_ESCAPE:
self.request_shutdown()
return
# Get continuous key states for driving controls
keys = pygame.key.get_pressed()
# WASD / Arrow key controls
self.input_state.throttle = 0.0
self.input_state.brake = 0.0
self.input_state.steering = 0.0
# Throttle (W or UP)
if keys[pygame.K_w] or keys[pygame.K_UP]:
self.input_state.throttle = 1.0
# Brake (S or DOWN)
if keys[pygame.K_s] or keys[pygame.K_DOWN]:
self.input_state.brake = 1.0
# Steering (A/D or LEFT/RIGHT)
if keys[pygame.K_a] or keys[pygame.K_LEFT]:
self.input_state.steering = -1.0
elif keys[pygame.K_d] or keys[pygame.K_RIGHT]:
self.input_state.steering = 1.0
# Handbrake (LSHIFT)
self.input_state.handbrake = keys[pygame.K_LSHIFT]
def _update(self, dt: float):
"""
Update simulation state.
Args:
dt: Delta time in seconds
"""
update_start = time.time()
# Apply time scale
scaled_dt = dt * self.time_scale
# Get agent references for efficiency
physics = self.agents.get("physics_engine")
sensor_fusion = self.agents.get("sensor_fusion")
perception = self.agents.get("perception")
prediction = self.agents.get("prediction")
decision = self.agents.get("decision")
adas = self.agents.get("adas")
safety = self.agents.get("safety_monitor")
reward_shaping = self.agents.get("reward_shaping")
learning = self.agents.get("learning_orchestrator")
# 1. Update physics
physics_start = time.time()
if physics:
vehicle_state = physics.step(scaled_dt, self.input_state)
else:
vehicle_state = {}
self.metrics.physics_time_ms = (time.time() - physics_start) * 1000
# 2. Update sensors
if sensor_fusion:
sensor_data = sensor_fusion.get_fused_perception()
else:
sensor_data = {}
# 3. Run perception
ai_start = time.time()
if perception:
perception_output = perception.process(sensor_data)
else:
perception_output = {}
# 4. Run prediction
if prediction:
predicted_trajectories = prediction.predict(
perception_output.get("objects", []),
scaled_dt
)
else:
predicted_trajectories = {}
# 5. Make decisions
if decision:
decision_output = decision.decide(perception_output, predicted_trajectories)
else:
decision_output = {}
# 6. Update ADAS
if adas:
adas_interventions = adas.update_adas(vehicle_state, perception_output)
# Apply ADAS interventions
if adas_interventions.get("emergency_brake"):
self.input_state.brake = 1.0
# 7. Check safety
if safety:
safety_status = safety.check_safety(vehicle_state, self.input_state)
# 8. Calculate rewards (if training)
if self.training_enabled and reward_shaping:
reward = reward_shaping.calculate_reward(
vehicle_state,
self.input_state,
vehicle_state # Next state (same for now)
)
# 9. Update learning (if training)
if self.training_enabled and learning and learning.is_training:
if self.metrics.step_count % 2048 == 0:
learning.update_policy({})
self.metrics.ai_time_ms = (time.time() - ai_start) * 1000
# Update all agents
for agent in self.agents.values():
if agent.enabled and agent.initialized:
agent.update(scaled_dt)
def _render(self):
"""Render the simulation."""
render_start = time.time()
visualizer = self.agents.get("visualizer")
inspector = self.agents.get("inspector_console")
if visualizer:
# Get data for rendering
perception = self.agents.get("perception")
perception_data = perception.process({}) if perception else {}
# Render main view
screen = visualizer.render(
{}, # world_state
perception_data,
self.metrics
)
# Render inspector if visible
if inspector and inspector.visible:
inspector.render(screen, self.metrics, self.agents)
# Update display
pygame.display.flip()
self.metrics.render_time_ms = (time.time() - render_start) * 1000
# =====================================================================
# CONTROL ACTIONS
# =====================================================================
def _toggle_training_mode(self):
"""Toggle training mode on/off."""
learning = self.agents.get("learning_orchestrator")
if not self.training_enabled:
self.training_enabled = True
self.control_mode = ControlMode.TRAINING
self.state = SimulationState.TRAINING
if learning:
learning.start_training()
logger.info("Training mode ENABLED")
else:
self.training_enabled = False
self.control_mode = ControlMode.AUTONOMOUS
self.state = SimulationState.RUNNING
if learning:
learning.stop_training()
logger.info("Training mode DISABLED")
def _reset_simulation(self):
"""Reset the simulation state."""
logger.info("Resetting simulation...")
# Reset all agents
for agent in self.agents.values():
agent.reset()
# Reset metrics
reward_shaping = self.agents.get("reward_shaping")
if reward_shaping:
reward_shaping.reset_episode()
# Increment episode count
self.metrics.episode_count += 1
self.episode_start_time = time.time()
logger.info("Simulation reset complete")
def _cycle_camera(self):
"""Cycle through camera views."""
visualizer = self.agents.get("visualizer")
if visualizer:
visualizer.cycle_camera()
def _toggle_inspector(self):
"""Toggle inspector console visibility."""
inspector = self.agents.get("inspector_console")
if inspector:
inspector.toggle()
logger.info(f"Inspector {'visible' if inspector.visible else 'hidden'}")
def _emergency_brake(self):
"""Trigger emergency brake."""
logger.warning("EMERGENCY BRAKE ACTIVATED")
self.input_state.brake = 1.0
self.input_state.throttle = 0.0
def _toggle_pause(self):
"""Toggle simulation pause."""
if self.state == SimulationState.RUNNING:
self.state = SimulationState.PAUSED
logger.info("Simulation PAUSED")
elif self.state == SimulationState.PAUSED:
self.state = SimulationState.RUNNING
logger.info("Simulation RESUMED")
# =====================================================================
# SHUTDOWN
# =====================================================================
def request_shutdown(self):
"""Request graceful shutdown."""
logger.info("Shutdown requested")
self._shutdown_requested = True
self.state = SimulationState.SHUTTING_DOWN
def shutdown(self):
"""Perform graceful shutdown."""
if self._shutdown_complete:
return
logger.info("Shutting down...")
self.state = SimulationState.SHUTTING_DOWN
# Save models if training
if self.training_enabled:
learning = self.agents.get("learning_orchestrator")
if learning:
timestamp = time.strftime("%Y%m%d_%H%M%S")
save_path = f"{Paths.CHECKPOINTS_DIR}/model_{timestamp}.pth"
learning.save_model(save_path)
# Shutdown all agents in reverse order
agent_order = [
"inspector_console",
"visualizer",
"learning_orchestrator",
"reward_shaping",
"safety_monitor",
"adas",
"decision",
"prediction",
"perception",
"sensor_fusion",
"physics_engine",
"world_builder",
]
for name in agent_order:
agent = self.agents.get(name)
if agent:
logger.info(f"Shutting down {name}...")
try:
agent.shutdown()
except Exception as e:
logger.error(f"Error shutting down {name}: {e}")
# Quit pygame
pygame.quit()
self._shutdown_complete = True
logger.info("Shutdown complete")
# =====================================================================
# UTILITY METHODS
# =====================================================================
def get_agent(self, name: str) -> Optional[AgentInterface]:
"""
Get an agent by name.
Args:
name: Agent name
Returns:
Agent instance or None
"""
return self.agents.get(name)
def get_all_agents(self) -> Dict[str, AgentInterface]:
"""
Get all registered agents.
Returns:
Dictionary of agent name to agent instance
"""