| | 1 | | using System.Collections; |
| | 2 | | using System.Collections.Generic; |
| | 3 | | using System.Linq; |
| | 4 | | using UnityEngine; |
| | 5 | |
|
| | 6 | | // Manages the simulation by handling missiles, targets, and their assignments. |
| | 7 | | // Implements the Singleton pattern to ensure only one instance exists. |
| | 8 | | public class SimManager : MonoBehaviour { |
| | 9 | | // Map from the agent type to the prefab class name. |
| | 10 | | // The prefab class must exist in the Resources/Prefabs directory. |
| 0 | 11 | | private static readonly Dictionary<Configs.AgentType, string> AgentTypePrefabMap = new() { |
| | 12 | | { Configs.AgentType.CarrierInterceptor, "CarrierInterceptor" }, |
| | 13 | | { Configs.AgentType.MissileInterceptor, "MissileInterceptor" }, |
| | 14 | | { Configs.AgentType.FixedWingThreat, "FixedWingThreat" }, |
| | 15 | | { Configs.AgentType.RotaryWingThreat, "RotaryWingThreat" }, |
| | 16 | | }; |
| | 17 | |
|
| | 18 | | // Singleton instance of SimManager. |
| 48 | 19 | | public static SimManager Instance { get; set; } |
| | 20 | |
|
| | 21 | | // Simulation configuration. |
| | 22 | | [SerializeField] |
| | 23 | | public Configs.SimulationConfig SimulationConfig; |
| | 24 | |
|
| | 25 | | // Simulator configuration. |
| | 26 | | public Configs.SimulatorConfig SimulatorConfig; |
| | 27 | |
|
| | 28 | | private const string _defaultConfig = "7_quadcopters.pbtxt"; |
| | 29 | |
|
| 11 | 30 | | private List<Interceptor> _activeInterceptors = new List<Interceptor>(); |
| 11 | 31 | | private List<Interceptor> _interceptorObjects = new List<Interceptor>(); |
| 11 | 32 | | private List<Threat> _threatObjects = new List<Threat>(); |
| | 33 | |
|
| 11 | 34 | | private List<GameObject> _dummyAgentObjects = new List<GameObject>(); |
| 11 | 35 | | private Dictionary<(Vector3, Vector3), GameObject> _dummyAgentTable = |
| | 36 | | new Dictionary<(Vector3, Vector3), GameObject>(); |
| | 37 | |
|
| | 38 | | // Inclusive of all, including submunitions swarms. |
| | 39 | | // The boolean indicates whether the agent is active (true) or inactive (false). |
| 11 | 40 | | private List<List<(Agent, bool)>> _interceptorSwarms = new List<List<(Agent, bool)>>(); |
| 11 | 41 | | private List<List<(Agent, bool)>> _submunitionsSwarms = new List<List<(Agent, bool)>>(); |
| 11 | 42 | | private List<List<(Agent, bool)>> _threatSwarms = new List<List<(Agent, bool)>>(); |
| | 43 | |
|
| 11 | 44 | | private Dictionary<Agent, List<(Agent, bool)>> _interceptorSwarmMap = |
| | 45 | | new Dictionary<Agent, List<(Agent, bool)>>(); |
| | 46 | |
|
| 11 | 47 | | private Dictionary<Agent, List<(Agent, bool)>> _submunitionsSwarmMap = |
| | 48 | | new Dictionary<Agent, List<(Agent, bool)>>(); |
| 11 | 49 | | private Dictionary<Agent, List<(Agent, bool)>> _threatSwarmMap = |
| | 50 | | new Dictionary<Agent, List<(Agent, bool)>>(); |
| | 51 | |
|
| | 52 | | // Maps a submunition swarm to its corresponding interceptor swarm. |
| 11 | 53 | | private Dictionary<List<(Agent, bool)>, List<(Agent, bool)>> _submunitionInterceptorSwarmMap = |
| | 54 | | new Dictionary<List<(Agent, bool)>, List<(Agent, bool)>>(); |
| | 55 | |
|
| | 56 | | // Events to subscribe to for changes in each of the swarm tables. |
| | 57 | | public delegate void SwarmEventHandler(List<List<(Agent, bool)>> swarm); |
| | 58 | | public event SwarmEventHandler OnInterceptorSwarmChanged; |
| | 59 | | public event SwarmEventHandler OnSubmunitionsSwarmChanged; |
| | 60 | | public event SwarmEventHandler OnThreatSwarmChanged; |
| | 61 | |
|
| 11 | 62 | | private float _elapsedSimulationTime = 0f; |
| 11 | 63 | | private bool _isSimulationPaused = false; |
| | 64 | |
|
| 11 | 65 | | private float _costLaunchedInterceptors = 0f; |
| 11 | 66 | | private float _costDestroyedThreats = 0f; |
| | 67 | |
|
| | 68 | | public delegate void SimulationEventHandler(); |
| | 69 | | public event SimulationEventHandler OnSimulationEnded; |
| | 70 | | public event SimulationEventHandler OnSimulationStarted; |
| | 71 | |
|
| | 72 | | public delegate void NewThreatEventHandler(Threat threat); |
| | 73 | | public event NewThreatEventHandler OnNewThreat; |
| | 74 | |
|
| | 75 | | public delegate void NewInterceptorEventHandler(Interceptor interceptor); |
| | 76 | | public event NewInterceptorEventHandler OnNewInterceptor; |
| | 77 | |
|
| | 78 | | // Returns the elapsed simulation time in seconds. |
| 0 | 79 | | public double GetElapsedSimulationTime() { |
| 0 | 80 | | return _elapsedSimulationTime; |
| 0 | 81 | | } |
| | 82 | |
|
| | 83 | | // Returns the total cost of launched interceptors. |
| 0 | 84 | | public double GetCostLaunchedInterceptors() { |
| 0 | 85 | | return _costLaunchedInterceptors; |
| 0 | 86 | | } |
| | 87 | |
|
| | 88 | | // Returns the total cost of destroyed threats. |
| 0 | 89 | | public double GetCostDestroyedThreats() { |
| 0 | 90 | | return _costDestroyedThreats; |
| 0 | 91 | | } |
| | 92 | |
|
| 0 | 93 | | public List<Interceptor> GetActiveInterceptors() { |
| 0 | 94 | | return _activeInterceptors; |
| 0 | 95 | | } |
| | 96 | |
|
| 0 | 97 | | public List<Threat> GetActiveThreats() { |
| 0 | 98 | | return _threatObjects.Where(threat => !threat.IsTerminated()).ToList(); |
| 0 | 99 | | } |
| | 100 | |
|
| 0 | 101 | | public List<Agent> GetActiveAgents() { |
| 0 | 102 | | return _activeInterceptors.ConvertAll(interceptor => interceptor as Agent) |
| 0 | 103 | | .Concat(GetActiveThreats().ConvertAll(threat => threat as Agent)) |
| | 104 | | .ToList(); |
| 0 | 105 | | } |
| | 106 | |
|
| 0 | 107 | | public string GenerateSwarmTitle(List<(Agent, bool)> swarm, int index) { |
| 0 | 108 | | string swarmTitle = swarm[0].Item1.name; |
| 0 | 109 | | swarmTitle = swarmTitle.Split('_')[0]; |
| 0 | 110 | | swarmTitle += $"_{index}"; |
| 0 | 111 | | return swarmTitle; |
| 0 | 112 | | } |
| | 113 | |
|
| 0 | 114 | | public string GenerateInterceptorSwarmTitle(List<(Agent, bool)> swarm) { |
| 0 | 115 | | return GenerateSwarmTitle(swarm, _interceptorSwarms.IndexOf(swarm)); |
| 0 | 116 | | } |
| | 117 | |
|
| 0 | 118 | | public string GenerateSubmunitionsSwarmTitle(List<(Agent, bool)> swarm) { |
| 0 | 119 | | return GenerateSwarmTitle(swarm, LookupSubmunitionSwarmIndexInInterceptorSwarm(swarm)); |
| 0 | 120 | | } |
| | 121 | |
|
| 0 | 122 | | public string GenerateThreatSwarmTitle(List<(Agent, bool)> swarm) { |
| 0 | 123 | | return GenerateSwarmTitle(swarm, _threatSwarms.IndexOf(swarm)); |
| 0 | 124 | | } |
| | 125 | |
|
| 0 | 126 | | void Awake() { |
| | 127 | | // Ensure that only one instance of SimManager exists. |
| 0 | 128 | | if (Instance == null) { |
| 0 | 129 | | Instance = this; |
| 0 | 130 | | DontDestroyOnLoad(gameObject); |
| 0 | 131 | | } else { |
| 0 | 132 | | Destroy(gameObject); |
| 0 | 133 | | } |
| 0 | 134 | | SimulationConfig = ConfigLoader.LoadSimulationConfig(_defaultConfig); |
| 0 | 135 | | SimulatorConfig = ConfigLoader.LoadSimulatorConfig(); |
| 0 | 136 | | } |
| | 137 | |
|
| 0 | 138 | | void Start() { |
| 0 | 139 | | if (Instance == this) { |
| 0 | 140 | | _isSimulationPaused = false; |
| 0 | 141 | | StartSimulation(); |
| 0 | 142 | | ResumeSimulation(); |
| 0 | 143 | | } |
| 0 | 144 | | } |
| | 145 | |
|
| 0 | 146 | | void Update() {} |
| | 147 | |
|
| 0 | 148 | | public void SetTimeScale(float timeScale) { |
| 0 | 149 | | Time.timeScale = timeScale; |
| | 150 | | // Time.fixedDeltaTime is derived from the simulator configuration. |
| 0 | 151 | | Time.maximumDeltaTime = Time.fixedDeltaTime * 3; |
| 0 | 152 | | } |
| | 153 | |
|
| 0 | 154 | | public void StartSimulation() { |
| 0 | 155 | | InitializeSimulation(); |
| | 156 | |
|
| | 157 | | // Invoke the simulation started event to let listeners know to invoke their own handler |
| | 158 | | // behavior. |
| 0 | 159 | | UIManager.Instance.LogActionMessage("[SIM] Simulation started."); |
| 0 | 160 | | OnSimulationStarted?.Invoke(); |
| 0 | 161 | | } |
| | 162 | |
|
| 0 | 163 | | public void PauseSimulation() { |
| 0 | 164 | | SetTimeScale(0); |
| 0 | 165 | | Time.fixedDeltaTime = 0; |
| 0 | 166 | | _isSimulationPaused = true; |
| 0 | 167 | | } |
| | 168 | |
|
| 0 | 169 | | public void ResumeSimulation() { |
| 0 | 170 | | Time.fixedDeltaTime = (float)(1.0f / SimulatorConfig.PhysicsUpdateRate); |
| 0 | 171 | | SetTimeScale(SimulationConfig.TimeScale); |
| 0 | 172 | | _isSimulationPaused = false; |
| 0 | 173 | | } |
| | 174 | |
|
| 0 | 175 | | public bool IsSimulationPaused() { |
| 0 | 176 | | return _isSimulationPaused; |
| 0 | 177 | | } |
| | 178 | |
|
| 0 | 179 | | private void InitializeSimulation() { |
| 0 | 180 | | if (!IsSimulationPaused()) { |
| | 181 | | // If the simulation was not paused, we need to update the time scale. |
| 0 | 182 | | SetTimeScale(SimulationConfig.TimeScale); |
| 0 | 183 | | Time.fixedDeltaTime = (float)(1.0f / SimulatorConfig.PhysicsUpdateRate); |
| | 184 | | // If the simulation was paused, then ResumeSimulation will handle updating the time scale and |
| | 185 | | // fixed delta time from the newly loaded configuration. |
| 0 | 186 | | } |
| | 187 | |
|
| | 188 | | // Create threats based on the configuration. |
| 0 | 189 | | List<Agent> targets = new List<Agent>(); |
| 0 | 190 | | foreach (var swarmConfig in SimulationConfig.ThreatSwarmConfigs) { |
| 0 | 191 | | List<Agent> swarm = new List<Agent>(); |
| 0 | 192 | | for (int i = 0; i < swarmConfig.NumAgents; ++i) { |
| 0 | 193 | | Threat threat = CreateThreat(swarmConfig.AgentConfig); |
| 0 | 194 | | swarm.Add(threat); |
| 0 | 195 | | } |
| 0 | 196 | | AddThreatSwarm(swarm); |
| 0 | 197 | | } |
| 0 | 198 | | } |
| | 199 | |
|
| 0 | 200 | | public void AddInterceptorSwarm(List<Agent> swarm) { |
| 0 | 201 | | List<(Agent, bool)> swarmTuple = swarm.ConvertAll(agent => (agent, true)); |
| 0 | 202 | | _interceptorSwarms.Add(swarmTuple); |
| 0 | 203 | | foreach (var interceptor in swarm) { |
| 0 | 204 | | _interceptorSwarmMap[interceptor] = swarmTuple; |
| 0 | 205 | | } |
| 0 | 206 | | OnInterceptorSwarmChanged?.Invoke(_interceptorSwarms); |
| 0 | 207 | | } |
| | 208 | |
|
| 0 | 209 | | public void AddSubmunitionsSwarm(List<Agent> swarm) { |
| 0 | 210 | | List<(Agent, bool)> swarmTuple = swarm.ConvertAll(agent => (agent, true)); |
| 0 | 211 | | _submunitionsSwarms.Add(swarmTuple); |
| 0 | 212 | | foreach (var submunition in swarm) { |
| 0 | 213 | | _submunitionsSwarmMap[submunition] = swarmTuple; |
| 0 | 214 | | } |
| 0 | 215 | | AddInterceptorSwarm(swarm); |
| 0 | 216 | | _submunitionInterceptorSwarmMap[swarmTuple] = _interceptorSwarms[_interceptorSwarms.Count - 1]; |
| 0 | 217 | | OnSubmunitionsSwarmChanged?.Invoke(_submunitionsSwarms); |
| 0 | 218 | | } |
| | 219 | |
|
| 0 | 220 | | public int LookupSubmunitionSwarmIndexInInterceptorSwarm(List<(Agent, bool)> swarm) { |
| 0 | 221 | | if (_submunitionInterceptorSwarmMap.TryGetValue(swarm, out var interceptorSwarm)) { |
| 0 | 222 | | return _interceptorSwarms.IndexOf(interceptorSwarm); |
| | 223 | | } |
| | 224 | | // Return -1 if the swarm is not found. |
| 0 | 225 | | return -1; |
| 0 | 226 | | } |
| | 227 | |
|
| 0 | 228 | | public void AddThreatSwarm(List<Agent> swarm) { |
| 0 | 229 | | List<(Agent, bool)> swarmTuple = swarm.ConvertAll(agent => (agent, true)); |
| 0 | 230 | | _threatSwarms.Add(swarmTuple); |
| 0 | 231 | | foreach (var threat in swarm) { |
| 0 | 232 | | _threatSwarmMap[threat] = swarmTuple; |
| 0 | 233 | | } |
| 0 | 234 | | OnThreatSwarmChanged?.Invoke(_threatSwarms); |
| 0 | 235 | | } |
| | 236 | |
|
| 0 | 237 | | public Vector3 GetAllAgentsCenter() { |
| 0 | 238 | | List<Agent> allAgents = _interceptorObjects.ConvertAll(interceptor => interceptor as Agent) |
| 0 | 239 | | .Concat(_threatObjects.ConvertAll(threat => threat as Agent)) |
| | 240 | | .ToList(); |
| 0 | 241 | | return GetSwarmCenter(allAgents); |
| 0 | 242 | | } |
| | 243 | |
|
| 0 | 244 | | public Vector3 GetSwarmCenter(List<Agent> swarm) { |
| 0 | 245 | | if (swarm.Count == 0) { |
| 0 | 246 | | return Vector3.zero; |
| | 247 | | } |
| | 248 | |
|
| 0 | 249 | | Vector3 sum = Vector3.zero; |
| 0 | 250 | | int count = 0; |
| 0 | 251 | | int swarmCount = swarm.Count; |
| | 252 | |
|
| 0 | 253 | | for (int i = 0; i < swarmCount; ++i) { |
| 0 | 254 | | Agent agent = swarm[i]; |
| 0 | 255 | | if (!agent.IsTerminated()) { |
| 0 | 256 | | sum += agent.transform.position; |
| 0 | 257 | | ++count; |
| 0 | 258 | | } |
| 0 | 259 | | } |
| | 260 | |
|
| 0 | 261 | | return count > 0 ? sum / count : Vector3.zero; |
| 0 | 262 | | } |
| | 263 | |
|
| 0 | 264 | | public List<List<(Agent, bool)>> GetInterceptorSwarms() { |
| 0 | 265 | | return _interceptorSwarms; |
| 0 | 266 | | } |
| | 267 | |
|
| 0 | 268 | | public List<List<(Agent, bool)>> GetSubmunitionsSwarms() { |
| 0 | 269 | | return _submunitionsSwarms; |
| 0 | 270 | | } |
| | 271 | |
|
| 0 | 272 | | public List<List<(Agent, bool)>> GetThreatSwarms() { |
| 0 | 273 | | return _threatSwarms; |
| 0 | 274 | | } |
| | 275 | |
|
| 0 | 276 | | public void DestroyInterceptorInSwarm(Interceptor interceptor) { |
| 0 | 277 | | var swarm = _interceptorSwarmMap[interceptor]; |
| 0 | 278 | | int index = swarm.FindIndex(tuple => tuple.Item1 == interceptor); |
| 0 | 279 | | if (index != -1) { |
| 0 | 280 | | swarm[index] = (swarm[index].Item1, false); |
| 0 | 281 | | OnInterceptorSwarmChanged?.Invoke(_interceptorSwarms); |
| 0 | 282 | | } else { |
| 0 | 283 | | Debug.LogError("Interceptor not found in swarm."); |
| 0 | 284 | | } |
| 0 | 285 | | if (swarm.All(tuple => !tuple.Item2)) { |
| | 286 | | // Need to give the camera controller a way to update to the next swarm if it exists. |
| 0 | 287 | | if (CameraController.Instance.cameraMode == CameraMode.FOLLOW_INTERCEPTOR_SWARM) { |
| 0 | 288 | | CameraController.Instance.FollowNextInterceptorSwarm(); |
| 0 | 289 | | } |
| 0 | 290 | | } |
| | 291 | |
|
| | 292 | | // If this also happens to be a submunition, destroy it in the submunition swarm. |
| 0 | 293 | | if (_submunitionsSwarmMap.ContainsKey(interceptor)) { |
| 0 | 294 | | DestroySubmunitionInSwarm(interceptor); |
| 0 | 295 | | } |
| 0 | 296 | | } |
| | 297 | |
|
| 0 | 298 | | public void DestroySubmunitionInSwarm(Interceptor submunition) { |
| 0 | 299 | | var swarm = _submunitionsSwarmMap[submunition]; |
| 0 | 300 | | int index = swarm.FindIndex(tuple => tuple.Item1 == submunition); |
| 0 | 301 | | if (index != -1) { |
| 0 | 302 | | swarm[index] = (swarm[index].Item1, false); |
| 0 | 303 | | OnSubmunitionsSwarmChanged?.Invoke(_submunitionsSwarms); |
| 0 | 304 | | } |
| 0 | 305 | | } |
| | 306 | |
|
| 0 | 307 | | public void DestroyThreatInSwarm(Threat threat) { |
| 0 | 308 | | var swarm = _threatSwarmMap[threat]; |
| 0 | 309 | | int index = swarm.FindIndex(tuple => tuple.Item1 == threat); |
| 0 | 310 | | if (index != -1) { |
| 0 | 311 | | swarm[index] = (swarm[index].Item1, false); |
| 0 | 312 | | OnThreatSwarmChanged?.Invoke(_threatSwarms); |
| 0 | 313 | | } |
| 0 | 314 | | if (swarm.All(tuple => !tuple.Item2)) { |
| 0 | 315 | | _threatSwarms.Remove(swarm); |
| 0 | 316 | | if (CameraController.Instance.cameraMode == CameraMode.FOLLOW_THREAT_SWARM) { |
| 0 | 317 | | CameraController.Instance.FollowNextThreatSwarm(); |
| 0 | 318 | | } |
| 0 | 319 | | } |
| 0 | 320 | | } |
| | 321 | |
|
| 0 | 322 | | public void RegisterInterceptorHit(Interceptor interceptor, Threat threat) { |
| 0 | 323 | | _costDestroyedThreats += threat.staticConfig.Cost; |
| 0 | 324 | | if (interceptor is Interceptor missileComponent) { |
| 0 | 325 | | _activeInterceptors.Remove(missileComponent); |
| 0 | 326 | | } |
| 0 | 327 | | DestroyInterceptorInSwarm(interceptor); |
| 0 | 328 | | DestroyThreatInSwarm(threat); |
| 0 | 329 | | } |
| | 330 | |
|
| 0 | 331 | | public void RegisterInterceptorMiss(Interceptor interceptor, Threat threat) { |
| 0 | 332 | | if (interceptor is Interceptor missileComponent) { |
| 0 | 333 | | _activeInterceptors.Remove(missileComponent); |
| 0 | 334 | | } |
| 0 | 335 | | DestroyInterceptorInSwarm(interceptor); |
| 0 | 336 | | } |
| | 337 | |
|
| 0 | 338 | | public void RegisterThreatHit(Threat threat) { |
| 0 | 339 | | DestroyThreatInSwarm(threat); |
| 0 | 340 | | } |
| | 341 | |
|
| 0 | 342 | | public void RegisterThreatMiss(Threat threat) { |
| 0 | 343 | | DestroyThreatInSwarm(threat); |
| 0 | 344 | | } |
| | 345 | |
|
| 15 | 346 | | private AttackBehavior LoadAttackBehavior(Configs.AgentConfig config) { |
| 15 | 347 | | string attackBehaviorConfigFile = config.AttackBehaviorConfigFile; |
| 15 | 348 | | if (string.IsNullOrEmpty(attackBehaviorConfigFile)) { |
| 0 | 349 | | return null; |
| | 350 | | } |
| 15 | 351 | | Configs.AttackBehaviorConfig attackBehaviorConfig = |
| | 352 | | ConfigLoader.LoadAttackBehaviorConfig(attackBehaviorConfigFile); |
| 15 | 353 | | return AttackBehaviorFactory.Create(attackBehaviorConfig); |
| 15 | 354 | | } |
| | 355 | |
|
| 17 | 356 | | public Agent CreateDummyAgent(Vector3 position, Vector3 velocity) { |
| 26 | 357 | | if (_dummyAgentTable.ContainsKey((position, velocity))) { |
| 9 | 358 | | return _dummyAgentTable[(position, velocity)].GetComponent<Agent>(); |
| | 359 | | } |
| 8 | 360 | | GameObject dummyAgentPrefab = Resources.Load<GameObject>($"Prefabs/DummyAgent"); |
| 8 | 361 | | GameObject dummyAgentObject = Instantiate(dummyAgentPrefab, position, Quaternion.identity); |
| 16 | 362 | | if (!dummyAgentObject.TryGetComponent<Agent>(out _)) { |
| 8 | 363 | | dummyAgentObject.AddComponent<DummyAgent>(); |
| 8 | 364 | | } |
| 8 | 365 | | Rigidbody dummyRigidbody = dummyAgentObject.GetComponent<Rigidbody>(); |
| 8 | 366 | | dummyRigidbody.linearVelocity = velocity; |
| 8 | 367 | | _dummyAgentObjects.Add(dummyAgentObject); |
| 8 | 368 | | _dummyAgentTable[(position, velocity)] = dummyAgentObject; |
| 8 | 369 | | return dummyAgentObject.GetComponent<Agent>(); |
| 17 | 370 | | } |
| | 371 | |
|
| | 372 | | // Creates a interceptor based on the provided configuration. |
| | 373 | | // Returns the created interceptor instance, or null if creation failed. |
| 1 | 374 | | public Interceptor CreateInterceptor(Configs.AgentConfig config, Simulation.State initialState) { |
| 1 | 375 | | if (config == null) { |
| 0 | 376 | | return null; |
| | 377 | | } |
| | 378 | |
|
| | 379 | | // Load the static configuration for the interceptor. |
| 1 | 380 | | Configs.StaticConfig staticConfig = ConfigLoader.LoadStaticConfig(config.ConfigFile); |
| 1 | 381 | | if (staticConfig == null) { |
| 0 | 382 | | return null; |
| | 383 | | } |
| | 384 | |
|
| | 385 | | // Create an agent corresponding to the interceptor. |
| 1 | 386 | | GameObject interceptorObject = null; |
| 2 | 387 | | if (AgentTypePrefabMap.TryGetValue(staticConfig.AgentType, out var prefab)) { |
| 1 | 388 | | interceptorObject = CreateAgent(config, initialState, prefab); |
| 1 | 389 | | } |
| 1 | 390 | | if (interceptorObject == null) { |
| 0 | 391 | | return null; |
| | 392 | | } |
| | 393 | |
|
| | 394 | | // Create a sensor for the interceptor. |
| 1 | 395 | | switch (config.DynamicConfig.SensorConfig.Type) { |
| 1 | 396 | | case Simulation.SensorType.Ideal: { |
| 1 | 397 | | interceptorObject.AddComponent<IdealSensor>(); |
| 1 | 398 | | break; |
| | 399 | | } |
| 0 | 400 | | default: { |
| 0 | 401 | | Debug.LogError($"Sensor type {config.DynamicConfig.SensorConfig.Type} not found."); |
| 0 | 402 | | break; |
| | 403 | | } |
| | 404 | | } |
| | 405 | |
|
| 1 | 406 | | Interceptor interceptor = interceptorObject.GetComponent<Interceptor>(); |
| 1 | 407 | | _interceptorObjects.Add(interceptor); |
| 1 | 408 | | _activeInterceptors.Add(interceptor); |
| | 409 | |
|
| | 410 | | // Set the static configuration. |
| 1 | 411 | | interceptor.SetStaticConfig(staticConfig); |
| | 412 | |
|
| | 413 | | // Subscribe events. |
| 1 | 414 | | interceptor.OnInterceptHit += RegisterInterceptorHit; |
| 1 | 415 | | interceptor.OnInterceptMiss += RegisterInterceptorMiss; |
| | 416 | |
|
| | 417 | | // Assign a unique and simple ID. |
| 1 | 418 | | int interceptorId = _interceptorObjects.Count; |
| 1 | 419 | | interceptorObject.name = $"{staticConfig.Name}_Interceptor_{interceptorId}"; |
| | 420 | |
|
| | 421 | | // Add the interceptor's unit cost to the total cost. |
| 1 | 422 | | _costLaunchedInterceptors += staticConfig.Cost; |
| | 423 | |
|
| | 424 | | // Let listeners know a new interceptor has been created. |
| 1 | 425 | | OnNewInterceptor?.Invoke(interceptor); |
| | 426 | |
|
| 1 | 427 | | return interceptor; |
| 1 | 428 | | } |
| | 429 | |
|
| | 430 | | // Creates a threat based on the provided configuration. |
| | 431 | | // Returns the created threat instance, or null if creation failed. |
| 15 | 432 | | public Threat CreateThreat(Configs.AgentConfig config) { |
| 15 | 433 | | if (config == null) { |
| 0 | 434 | | return null; |
| | 435 | | } |
| | 436 | |
|
| | 437 | | // Load the static configuration for the threat. |
| 15 | 438 | | Configs.StaticConfig staticConfig = ConfigLoader.LoadStaticConfig(config.ConfigFile); |
| 15 | 439 | | if (staticConfig == null) { |
| 0 | 440 | | return null; |
| | 441 | | } |
| | 442 | |
|
| | 443 | | // Create an agent corresponding to the threat. |
| 15 | 444 | | GameObject threatObject = null; |
| 30 | 445 | | if (AgentTypePrefabMap.TryGetValue(staticConfig.AgentType, out var prefab)) { |
| 15 | 446 | | threatObject = CreateRandomAgent(config, prefab); |
| 15 | 447 | | } |
| 15 | 448 | | if (threatObject == null) { |
| 0 | 449 | | return null; |
| | 450 | | } |
| | 451 | |
|
| 15 | 452 | | Threat threat = threatObject.GetComponent<Threat>(); |
| 15 | 453 | | _threatObjects.Add(threat); |
| | 454 | |
|
| | 455 | | // Set the static configuration. |
| 15 | 456 | | threat.SetStaticConfig(staticConfig); |
| | 457 | |
|
| | 458 | | // Set the attack behavior. |
| 15 | 459 | | AttackBehavior attackBehavior = LoadAttackBehavior(config); |
| 15 | 460 | | threat.SetAttackBehavior(attackBehavior); |
| | 461 | |
|
| | 462 | | // Subscribe events. |
| 15 | 463 | | threat.OnThreatHit += RegisterThreatHit; |
| 15 | 464 | | threat.OnThreatMiss += RegisterThreatMiss; |
| | 465 | |
|
| | 466 | | // Assign a unique and simple ID. |
| 15 | 467 | | int threatId = _threatObjects.Count; |
| 15 | 468 | | threatObject.name = $"{staticConfig.Name}_Threat_{threatId}"; |
| | 469 | |
|
| | 470 | | // Let listeners know that a new threat has been created. |
| 15 | 471 | | OnNewThreat?.Invoke(threat); |
| | 472 | |
|
| 15 | 473 | | return threatObject.GetComponent<Threat>(); |
| 15 | 474 | | } |
| | 475 | |
|
| | 476 | | // Creates a agent based on the provided configuration and prefab name. |
| | 477 | | // Returns the created GameObject instance, or null if creation failed. |
| | 478 | | public GameObject CreateAgent(Configs.AgentConfig config, Simulation.State initialState, |
| 16 | 479 | | string prefabName) { |
| 16 | 480 | | GameObject prefab = Resources.Load<GameObject>($"Prefabs/{prefabName}"); |
| 16 | 481 | | if (prefab == null) { |
| 0 | 482 | | Debug.LogError($"Prefab {prefabName} not found in Resources/Prefabs directory."); |
| 0 | 483 | | return null; |
| | 484 | | } |
| | 485 | |
|
| | 486 | | // Set the position. |
| 16 | 487 | | GameObject agentObject = |
| | 488 | | Instantiate(prefab, Coordinates3.FromProto(initialState.Position), Quaternion.identity); |
| | 489 | |
|
| | 490 | | // Set the velocity. The rigid body is frozen while the agent is in the initialized phase. |
| 16 | 491 | | agentObject.GetComponent<Agent>().SetInitialVelocity( |
| | 492 | | Coordinates3.FromProto(initialState.Velocity)); |
| | 493 | |
|
| | 494 | | // Set the rotation to face the initial velocity. |
| 16 | 495 | | Vector3 velocityDirection = Coordinates3.FromProto(initialState.Velocity).normalized; |
| 16 | 496 | | Quaternion targetRotation = Quaternion.LookRotation(velocityDirection, Vector3.up); |
| 16 | 497 | | agentObject.transform.rotation = targetRotation; |
| | 498 | |
|
| 16 | 499 | | agentObject.GetComponent<Agent>().SetAgentConfig(config); |
| 16 | 500 | | return agentObject; |
| 16 | 501 | | } |
| | 502 | |
|
| | 503 | | // Creates a random agent based on the provided configuration and prefab name. |
| | 504 | | // Returns the created GameObject instance, or null if creation failed. |
| 15 | 505 | | public GameObject CreateRandomAgent(Configs.AgentConfig config, string prefabName) { |
| 15 | 506 | | if (config == null) { |
| 0 | 507 | | return null; |
| | 508 | | } |
| | 509 | |
|
| 15 | 510 | | GameObject prefab = Resources.Load<GameObject>($"Prefabs/{prefabName}"); |
| 15 | 511 | | if (prefab == null) { |
| 0 | 512 | | Debug.LogError($"Prefab {prefabName} not found in Resources/Prefabs directory."); |
| 0 | 513 | | return null; |
| | 514 | | } |
| | 515 | |
|
| | 516 | | // Randomize the initial state. |
| 15 | 517 | | Simulation.State initialState = new Simulation.State(); |
| | 518 | |
|
| | 519 | | // Randomize the position. |
| 15 | 520 | | Vector3 positionNoise = Utilities.GenerateRandomNoise(config.StandardDeviation.Position); |
| 15 | 521 | | initialState.Position = |
| | 522 | | Coordinates3.ToProto(Coordinates3.FromProto(config.InitialState.Position) + positionNoise); |
| | 523 | |
|
| | 524 | | // Randomize the velocity. |
| 15 | 525 | | Vector3 velocityNoise = Utilities.GenerateRandomNoise(config.StandardDeviation.Velocity); |
| 15 | 526 | | initialState.Velocity = |
| | 527 | | Coordinates3.ToProto(Coordinates3.FromProto(config.InitialState.Velocity) + velocityNoise); |
| 15 | 528 | | return CreateAgent(config, initialState, prefabName); |
| 15 | 529 | | } |
| | 530 | |
|
| 0 | 531 | | public void LoadNewConfig(string configFile) { |
| 0 | 532 | | SimulationConfig = ConfigLoader.LoadSimulationConfig(configFile); |
| | 533 | | // Reload the simulator configuration. |
| 0 | 534 | | SimulatorConfig = ConfigLoader.LoadSimulatorConfig(); |
| 0 | 535 | | if (SimulationConfig != null) { |
| 0 | 536 | | Debug.Log($"Loaded new configuration: {configFile}."); |
| 0 | 537 | | RestartSimulation(); |
| 0 | 538 | | } else { |
| 0 | 539 | | Debug.LogError($"Failed to load configuration: {configFile}."); |
| 0 | 540 | | } |
| 0 | 541 | | } |
| | 542 | |
|
| 0 | 543 | | public void RestartSimulation() { |
| 0 | 544 | | OnSimulationEnded?.Invoke(); |
| 0 | 545 | | Debug.Log("Simulation ended."); |
| 0 | 546 | | UIManager.Instance.LogActionMessage("[SIM] Simulation restarted."); |
| | 547 | | // Reset the simulation time. |
| 0 | 548 | | _elapsedSimulationTime = 0f; |
| 0 | 549 | | _isSimulationPaused = IsSimulationPaused(); |
| 0 | 550 | | _costLaunchedInterceptors = 0f; |
| 0 | 551 | | _costDestroyedThreats = 0f; |
| | 552 | |
|
| | 553 | | // Clear existing interceptors and threats. |
| 0 | 554 | | foreach (var interceptor in _interceptorObjects) { |
| 0 | 555 | | if (interceptor != null) { |
| 0 | 556 | | Destroy(interceptor.gameObject); |
| 0 | 557 | | } |
| 0 | 558 | | } |
| | 559 | |
|
| 0 | 560 | | foreach (var threat in _threatObjects) { |
| 0 | 561 | | if (threat != null) { |
| 0 | 562 | | Destroy(threat.gameObject); |
| 0 | 563 | | } |
| 0 | 564 | | } |
| | 565 | |
|
| 0 | 566 | | foreach (var dummyAgent in _dummyAgentObjects) { |
| 0 | 567 | | if (dummyAgent != null) { |
| 0 | 568 | | Destroy(dummyAgent); |
| 0 | 569 | | } |
| 0 | 570 | | } |
| | 571 | |
|
| 0 | 572 | | _interceptorObjects.Clear(); |
| 0 | 573 | | _activeInterceptors.Clear(); |
| 0 | 574 | | _threatObjects.Clear(); |
| 0 | 575 | | _dummyAgentObjects.Clear(); |
| 0 | 576 | | _dummyAgentTable.Clear(); |
| 0 | 577 | | _interceptorSwarms.Clear(); |
| 0 | 578 | | _submunitionsSwarms.Clear(); |
| 0 | 579 | | _threatSwarms.Clear(); |
| 0 | 580 | | OnInterceptorSwarmChanged?.Invoke(_interceptorSwarms); |
| 0 | 581 | | OnSubmunitionsSwarmChanged?.Invoke(_submunitionsSwarms); |
| 0 | 582 | | OnThreatSwarmChanged?.Invoke(_threatSwarms); |
| 0 | 583 | | StartSimulation(); |
| 0 | 584 | | } |
| | 585 | |
|
| 0 | 586 | | void FixedUpdate() { |
| 0 | 587 | | if (!_isSimulationPaused && _elapsedSimulationTime < SimulationConfig.EndTime) { |
| 0 | 588 | | _elapsedSimulationTime += Time.deltaTime; |
| 0 | 589 | | } else if (_elapsedSimulationTime >= SimulationConfig.EndTime) { |
| 0 | 590 | | RestartSimulation(); |
| 0 | 591 | | Debug.Log("Simulation completed."); |
| 0 | 592 | | } |
| 0 | 593 | | } |
| | 594 | |
|
| 0 | 595 | | public void QuitSimulation() { |
| 0 | 596 | | Application.Quit(); |
| 0 | 597 | | } |
| | 598 | | } |