| | | 1 | | using UnityEngine; |
| | | 2 | | |
| | | 3 | | // Base implementation of an agent. |
| | | 4 | | // |
| | | 5 | | // See the agent interface for property and method documentation. |
| | | 6 | | public class AgentBase : MonoBehaviour, IAgent { |
| | | 7 | | public event AgentTerminatedEventHandler OnTerminated; |
| | | 8 | | |
| | | 9 | | private const float _epsilon = 1e-12f; |
| | | 10 | | |
| | | 11 | | // Rigid body component. |
| | | 12 | | protected Rigidbody _rigidbody; |
| | | 13 | | |
| | | 14 | | // The position field is cached and is updated before every fixed update. |
| | | 15 | | [SerializeField] |
| | | 16 | | private Vector3 _position; |
| | | 17 | | |
| | | 18 | | // The acceleration field is not part of the rigid body component, so it is tracked separately. |
| | | 19 | | // The acceleration is applied as a force during each frame update. |
| | | 20 | | [SerializeField] |
| | | 21 | | private Vector3 _acceleration; |
| | | 22 | | |
| | | 23 | | // The acceleration input is calculated by the controller and provided to the movement behavior. |
| | | 24 | | [SerializeField] |
| | | 25 | | private Vector3 _accelerationInput; |
| | | 26 | | |
| | | 27 | | // The agent's position within the hierarchical strategy is given by the hierarchical agent. |
| | | 28 | | [SerializeReference] |
| | | 29 | | private HierarchicalAgent _hierarchicalAgent; |
| | | 30 | | |
| | | 31 | | // Static configuration of the agent, including agent type, unit cost, acceleration configuration, |
| | | 32 | | // aerodynamics parameters, power table, and visualization configuration. |
| | | 33 | | private Configs.StaticConfig _staticConfig; |
| | | 34 | | |
| | | 35 | | // Agent configuration, including initial state, attack behavior configuration (for threats), |
| | | 36 | | // dynamic configuration, and sub-agent configuration (for interceptors). |
| | | 37 | | private Configs.AgentConfig _agentConfig; |
| | | 38 | | |
| | | 39 | | // Last sensing time. |
| | | 40 | | [SerializeField] |
| | 1929 | 41 | | private float _lastSensingTime = Mathf.NegativeInfinity; |
| | | 42 | | |
| | | 43 | | public HierarchicalAgent HierarchicalAgent { |
| | 47191 | 44 | | get => _hierarchicalAgent; |
| | 969 | 45 | | set => _hierarchicalAgent = value; |
| | | 46 | | } |
| | | 47 | | public Configs.StaticConfig StaticConfig { |
| | 25582 | 48 | | get => _staticConfig; |
| | 969 | 49 | | set { |
| | 969 | 50 | | _staticConfig = value; |
| | 969 | 51 | | _rigidbody.mass = StaticConfig.BodyConfig?.Mass ?? 1; |
| | 969 | 52 | | } |
| | | 53 | | } |
| | | 54 | | public Configs.AgentConfig AgentConfig { |
| | 8989 | 55 | | get => _agentConfig; |
| | 969 | 56 | | set { |
| | 969 | 57 | | _agentConfig = value; |
| | 969 | 58 | | UpdateAgentConfig(); |
| | 969 | 59 | | } |
| | | 60 | | } |
| | | 61 | | |
| | 8096 | 62 | | public IMovement Movement { get; set; } |
| | 8096 | 63 | | public IController Controller { get; set; } |
| | 9625 | 64 | | public ISensor Sensor { get; set; } |
| | 12933 | 65 | | public IAgent TargetModel { get; set; } |
| | | 66 | | |
| | | 67 | | public Vector3 Position { |
| | 30202 | 68 | | get => _position; |
| | 1661 | 69 | | set { |
| | 1661 | 70 | | Transform.position = value; |
| | 1661 | 71 | | _position = value; |
| | 1661 | 72 | | } |
| | | 73 | | } |
| | | 74 | | public Vector3 Velocity { |
| | 68665 | 75 | | get => _rigidbody.linearVelocity; |
| | 3585 | 76 | | set => _rigidbody.linearVelocity = value; |
| | | 77 | | } |
| | 28673 | 78 | | public float Speed => Velocity.magnitude; |
| | | 79 | | public Vector3 Acceleration { |
| | 17437 | 80 | | get => _acceleration; |
| | 8788 | 81 | | set => _acceleration = value; |
| | | 82 | | } |
| | | 83 | | public Vector3 AccelerationInput { |
| | 21117 | 84 | | get => _accelerationInput; |
| | 14122 | 85 | | set => _accelerationInput = value; |
| | | 86 | | } |
| | | 87 | | |
| | | 88 | | // If true, the agent is able to pursue targets. |
| | 0 | 89 | | public virtual bool IsPursuer => true; |
| | | 90 | | |
| | | 91 | | // Elapsed time since the creation of the agent. |
| | 38815 | 92 | | public float ElapsedTime { get; private set; } = 0f; |
| | | 93 | | |
| | | 94 | | // If true, the agent is terminated. |
| | 8924 | 95 | | public bool IsTerminated { get; private set; } = false; |
| | | 96 | | |
| | | 97 | | // The agent transform is cached. |
| | 110786 | 98 | | public Transform Transform { get; private set; } |
| | | 99 | | |
| | | 100 | | // The up direction is cached and updated before every fixed update. |
| | 16039 | 101 | | public Vector3 Up { get; private set; } |
| | | 102 | | |
| | | 103 | | // The forward direction is cached and updated before every fixed update. |
| | 44707 | 104 | | public Vector3 Forward { get; private set; } |
| | | 105 | | |
| | | 106 | | // The right direction is cached and updated before every fixed update. |
| | 16039 | 107 | | public Vector3 Right { get; private set; } |
| | | 108 | | |
| | | 109 | | // The inverse rotation is cached and updated before every fixed update. |
| | 33351 | 110 | | public Quaternion InverseRotation { get; private set; } |
| | | 111 | | |
| | 7563 | 112 | | public float MaxForwardAcceleration() { |
| | 7563 | 113 | | return StaticConfig.AccelerationConfig?.MaxForwardAcceleration ?? 0; |
| | 7563 | 114 | | } |
| | | 115 | | |
| | 7563 | 116 | | public float MaxNormalAcceleration() { |
| | 7563 | 117 | | float maxReferenceNormalAcceleration = |
| | | 118 | | (StaticConfig.AccelerationConfig?.MaxReferenceNormalAcceleration ?? 0) * Constants.kGravity; |
| | 7563 | 119 | | float referenceSpeed = StaticConfig.AccelerationConfig?.ReferenceSpeed ?? 1; |
| | 7563 | 120 | | return Mathf.Pow(Speed / referenceSpeed, 2) * maxReferenceNormalAcceleration; |
| | 7563 | 121 | | } |
| | | 122 | | |
| | 955 | 123 | | public void CreateTargetModel(IHierarchical target) { |
| | 955 | 124 | | TargetModel = SimManager.Instance.CreateDummyAgent(target.Position, target.Velocity); |
| | 955 | 125 | | } |
| | | 126 | | |
| | 0 | 127 | | public void DestroyTargetModel() { |
| | 0 | 128 | | if (TargetModel != null) { |
| | 0 | 129 | | SimManager.Instance.DestroyDummyAgent(TargetModel); |
| | 0 | 130 | | TargetModel = null; |
| | 0 | 131 | | } |
| | 0 | 132 | | } |
| | | 133 | | |
| | 14115 | 134 | | public void UpdateTargetModel() { |
| | 21235 | 135 | | if (HierarchicalAgent == null || HierarchicalAgent.Target == null || Sensor == null) { |
| | 7120 | 136 | | return; |
| | | 137 | | } |
| | 6995 | 138 | | if (HierarchicalAgent.Target.IsTerminated) { |
| | 0 | 139 | | HierarchicalAgent.Target = null; |
| | 0 | 140 | | return; |
| | | 141 | | } |
| | | 142 | | |
| | | 143 | | // Check whether the sensing period has elapsed. |
| | 6995 | 144 | | float sensingFrequency = AgentConfig?.DynamicConfig?.SensorConfig?.Frequency ?? Mathf.Infinity; |
| | 6995 | 145 | | float sensingPeriod = 1f / sensingFrequency; |
| | 8656 | 146 | | if (ElapsedTime - _lastSensingTime >= sensingPeriod) { |
| | | 147 | | // Sense the target. |
| | 1661 | 148 | | SensorOutput sensorOutput = Sensor.Sense(HierarchicalAgent.Target); |
| | 1661 | 149 | | TargetModel.Position = Position + sensorOutput.Position.Cartesian; |
| | 1661 | 150 | | TargetModel.Velocity = Velocity + sensorOutput.Velocity.Cartesian; |
| | 1661 | 151 | | TargetModel.Acceleration = Acceleration + sensorOutput.Acceleration.Cartesian; |
| | 1661 | 152 | | _lastSensingTime = ElapsedTime; |
| | 1661 | 153 | | } |
| | 14115 | 154 | | } |
| | | 155 | | |
| | 0 | 156 | | public Transformation GetRelativeTransformation(IAgent target) { |
| | 0 | 157 | | return GetRelativeTransformation(target.Position, target.Velocity, target.Acceleration); |
| | 0 | 158 | | } |
| | | 159 | | |
| | 1661 | 160 | | public Transformation GetRelativeTransformation(IHierarchical target) { |
| | 1661 | 161 | | return GetRelativeTransformation(target.Position, target.Velocity, target.Acceleration); |
| | 1661 | 162 | | } |
| | | 163 | | |
| | 6995 | 164 | | public Transformation GetRelativeTransformation(in Vector3 waypoint) { |
| | 6995 | 165 | | return GetRelativeTransformation(waypoint, velocity: Vector3.zero, acceleration: Vector3.zero); |
| | 6995 | 166 | | } |
| | | 167 | | |
| | 0 | 168 | | public void Terminate() { |
| | 0 | 169 | | if (HierarchicalAgent != null) { |
| | 0 | 170 | | HierarchicalAgent.Target = null; |
| | 0 | 171 | | } |
| | 0 | 172 | | if (Movement is MissileMovement movement) { |
| | 0 | 173 | | movement.FlightPhase = Simulation.FlightPhase.Terminated; |
| | 0 | 174 | | } |
| | 0 | 175 | | IsTerminated = true; |
| | 0 | 176 | | OnTerminated?.Invoke(this); |
| | 0 | 177 | | Destroy(gameObject); |
| | 0 | 178 | | } |
| | | 179 | | |
| | | 180 | | // Awake is called before Start and right after a prefab is instantiated. |
| | 1924 | 181 | | protected virtual void Awake() { |
| | 1924 | 182 | | Transform = transform; |
| | 1924 | 183 | | _rigidbody = GetComponent<Rigidbody>(); |
| | | 184 | | |
| | 1924 | 185 | | UpdateTransformData(); |
| | 3848 | 186 | | if (EarlyFixedUpdateManager.Instance != null) { |
| | 1924 | 187 | | EarlyFixedUpdateManager.Instance.OnEarlyFixedUpdate += UpdateTransformData; |
| | 1924 | 188 | | } |
| | 1924 | 189 | | } |
| | | 190 | | |
| | | 191 | | // Start is called before the first frame update. |
| | 3848 | 192 | | protected virtual void Start() {} |
| | | 193 | | |
| | | 194 | | // FixedUpdate is called multiple times per frame. All physics calculations and updates occur |
| | | 195 | | // immediately after FixedUpdate, and all movement values are multiplied by Time.deltaTime. |
| | 14115 | 196 | | protected virtual void FixedUpdate() { |
| | 14115 | 197 | | ElapsedTime += Time.fixedDeltaTime; |
| | | 198 | | |
| | 14115 | 199 | | UpdateTargetModel(); |
| | 14115 | 200 | | AlignWithVelocity(); |
| | 14115 | 201 | | } |
| | | 202 | | |
| | | 203 | | // Update is called every frame. |
| | 10484 | 204 | | protected virtual void Update() {} |
| | | 205 | | |
| | | 206 | | // LateUpdate is called every frame after all Update functions have been called. |
| | 8558 | 207 | | protected virtual void LateUpdate() {} |
| | | 208 | | |
| | | 209 | | // OnDestroy is called when the object is being destroyed. |
| | 1909 | 210 | | protected virtual void OnDestroy() { |
| | 3818 | 211 | | if (EarlyFixedUpdateManager.Instance != null) { |
| | 1909 | 212 | | EarlyFixedUpdateManager.Instance.OnEarlyFixedUpdate -= UpdateTransformData; |
| | 1909 | 213 | | } |
| | 1909 | 214 | | } |
| | | 215 | | |
| | | 216 | | // UpdateAgentConfig is called whenever the agent configuration is changed. |
| | 969 | 217 | | protected virtual void UpdateAgentConfig() { |
| | | 218 | | // Set the sensor. |
| | 969 | 219 | | switch (AgentConfig.DynamicConfig?.SensorConfig?.Type) { |
| | 969 | 220 | | case Simulation.SensorType.Ideal: { |
| | 969 | 221 | | Sensor = new IdealSensor(this); |
| | 969 | 222 | | break; |
| | | 223 | | } |
| | 0 | 224 | | default: { |
| | 0 | 225 | | Debug.LogError($"Sensor type {AgentConfig.DynamicConfig?.SensorConfig?.Type} not found."); |
| | 0 | 226 | | break; |
| | | 227 | | } |
| | | 228 | | } |
| | 969 | 229 | | } |
| | | 230 | | |
| | 0 | 231 | | protected virtual void OnDrawGizmos() { |
| | 0 | 232 | | if (Application.isPlaying) { |
| | 0 | 233 | | Gizmos.color = Color.green; |
| | 0 | 234 | | Gizmos.DrawRay(Position, _accelerationInput); |
| | 0 | 235 | | } |
| | 0 | 236 | | } |
| | | 237 | | |
| | 994 | 238 | | protected bool CheckFloorCollision(Collider other) { |
| | | 239 | | // Check if the agent hit the floor with a negative vertical speed. |
| | 994 | 240 | | return other.gameObject.name == "Floor" && Vector3.Dot(Velocity, Vector3.up) < 0; |
| | 994 | 241 | | } |
| | | 242 | | |
| | 994 | 243 | | protected bool ShouldIgnoreCollision(IAgent otherAgent) { |
| | | 244 | | // Dummy agents are virtual targets and should not trigger collisions. |
| | 994 | 245 | | return otherAgent == null || otherAgent is DummyAgent || otherAgent.IsTerminated; |
| | 994 | 246 | | } |
| | | 247 | | |
| | 16039 | 248 | | private void UpdateTransformData() { |
| | 16039 | 249 | | _position = Transform.position; |
| | 16039 | 250 | | Up = Transform.up; |
| | 16039 | 251 | | Forward = Transform.forward; |
| | 16039 | 252 | | Right = Transform.right; |
| | 16039 | 253 | | InverseRotation = Quaternion.Inverse(Transform.rotation); |
| | 16039 | 254 | | } |
| | | 255 | | |
| | 14115 | 256 | | private void AlignWithVelocity() { |
| | | 257 | | const float speedThreshold = 0.1f; |
| | | 258 | | const float rotationSpeedDegreesPerSecond = 10000f; |
| | | 259 | | |
| | | 260 | | // Only align if the velocity is significant. |
| | 27618 | 261 | | if (Speed > speedThreshold) { |
| | | 262 | | // Create a rotation with the forward direction along the velocity vector and the up direction |
| | | 263 | | // along world up. |
| | 13503 | 264 | | Quaternion targetRotation = Quaternion.LookRotation(Velocity, Vector3.up); |
| | | 265 | | |
| | | 266 | | // Smoothly rotate towards the target rotation. |
| | 13503 | 267 | | Transform.rotation = Quaternion.RotateTowards( |
| | | 268 | | Transform.rotation, targetRotation, |
| | | 269 | | maxDegreesDelta: rotationSpeedDegreesPerSecond * Time.fixedDeltaTime); |
| | 13503 | 270 | | } |
| | 14115 | 271 | | } |
| | | 272 | | |
| | | 273 | | private Transformation GetRelativeTransformation(in Vector3 position, in Vector3 velocity, |
| | 8656 | 274 | | in Vector3 acceleration) { |
| | 8656 | 275 | | Vector3 relativePosition = position - Position; |
| | 8656 | 276 | | Vector3 relativeLocalPosition = InverseRotation * relativePosition; |
| | 8656 | 277 | | Vector3 relativeVelocity = velocity - Velocity; |
| | 8656 | 278 | | Vector3 relativeLocalVelocity = InverseRotation * relativeVelocity; |
| | | 279 | | |
| | 8656 | 280 | | float x = relativeLocalPosition.x; |
| | 8656 | 281 | | float y = relativeLocalPosition.y; |
| | 8656 | 282 | | float z = relativeLocalPosition.z; |
| | | 283 | | |
| | 8656 | 284 | | float horizontalSqr = x * x + z * z; |
| | 8656 | 285 | | float horizontal = Mathf.Sqrt(horizontalSqr); |
| | 8656 | 286 | | float rangeSqr = horizontalSqr + y * y; |
| | 8656 | 287 | | float range = Mathf.Sqrt(rangeSqr); |
| | | 288 | | |
| | 8656 | 289 | | float azimuth = Mathf.Atan2(x, z); |
| | 8656 | 290 | | float elevation = Mathf.Atan2(y, horizontal); |
| | 8656 | 291 | | var positionTransformation = new PositionTransformation { |
| | | 292 | | Cartesian = relativePosition, |
| | | 293 | | Range = range, |
| | | 294 | | Azimuth = azimuth, |
| | | 295 | | Elevation = elevation, |
| | | 296 | | }; |
| | | 297 | | |
| | 8656 | 298 | | float rangeRate = |
| | | 299 | | range > _epsilon ? Vector3.Dot(relativeLocalVelocity, relativeLocalPosition) / range : 0f; |
| | 8656 | 300 | | float azimuthRate = 0f; |
| | 8656 | 301 | | float elevationRate = 0f; |
| | 17312 | 302 | | if (horizontal > _epsilon) { |
| | 8656 | 303 | | azimuthRate = -(x * relativeLocalVelocity.z - z * relativeLocalVelocity.x) / horizontalSqr; |
| | 8656 | 304 | | elevationRate = |
| | | 305 | | (relativeLocalVelocity.y * horizontal - |
| | | 306 | | y * (x * relativeLocalVelocity.x + z * relativeLocalVelocity.z) / horizontal) / |
| | | 307 | | rangeSqr; |
| | 8656 | 308 | | } else { |
| | | 309 | | // The other agent is exactly above or below. |
| | 0 | 310 | | azimuthRate = 0f; |
| | 0 | 311 | | float horizontalSpeed = Mathf.Sqrt(relativeLocalVelocity.x * relativeLocalVelocity.x + |
| | | 312 | | relativeLocalVelocity.z * relativeLocalVelocity.z); |
| | 0 | 313 | | elevationRate = -horizontalSpeed / (Mathf.Abs(y) > _epsilon ? y : Mathf.Sign(y) * _epsilon); |
| | 0 | 314 | | } |
| | 8656 | 315 | | var velocityTransformation = new VelocityTransformation { |
| | | 316 | | Cartesian = relativeVelocity, |
| | | 317 | | Range = rangeRate, |
| | | 318 | | Azimuth = azimuthRate, |
| | | 319 | | Elevation = elevationRate, |
| | | 320 | | }; |
| | | 321 | | |
| | 8656 | 322 | | var accelerationTransformation = new AccelerationTransformation { |
| | | 323 | | Cartesian = acceleration, |
| | | 324 | | }; |
| | 8656 | 325 | | return new Transformation { |
| | | 326 | | Position = positionTransformation, |
| | | 327 | | Velocity = velocityTransformation, |
| | | 328 | | Acceleration = accelerationTransformation, |
| | | 329 | | }; |
| | 8656 | 330 | | } |
| | | 331 | | } |