diff options
Diffstat (limited to 'Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI')
20 files changed, 6902 insertions, 0 deletions
diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AIBase.cs b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AIBase.cs new file mode 100644 index 0000000..7fe54e1 --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AIBase.cs @@ -0,0 +1,930 @@ +using UnityEngine; +using System.Collections; +using UnityEngine.Serialization; +using Unity.Jobs; + +namespace Pathfinding { + using Pathfinding.RVO; + using Pathfinding.Util; + using Pathfinding.Jobs; + using Pathfinding.Drawing; + using UnityEngine.Jobs; + + /// <summary> + /// Base class for AIPath and RichAI. + /// This class holds various methods and fields that are common to both AIPath and RichAI. + /// + /// See: <see cref="Pathfinding.AIPath"/> + /// See: <see cref="Pathfinding.RichAI"/> + /// See: <see cref="Pathfinding.IAstarAI"/> (all movement scripts implement this interface) + /// </summary> + [RequireComponent(typeof(Seeker))] + public abstract class AIBase : VersionedMonoBehaviour { + /// <summary>\copydocref{IAstarAI.radius}</summary> + public float radius = 0.5f; + + /// <summary>\copydocref{IAstarAI.height}</summary> + public float height = 2; + + /// <summary> + /// Determines how often the agent will search for new paths (in seconds). + /// The agent will plan a new path to the target every N seconds. + /// + /// If you have fast moving targets or AIs, you might want to set it to a lower value. + /// + /// See: <see cref="shouldRecalculatePath"/> + /// See: <see cref="SearchPath"/> + /// + /// Deprecated: This has been renamed to <see cref="autoRepath.period"/>. + /// See: <see cref="AutoRepathPolicy"/> + /// </summary> + public float repathRate { + get { + return this.autoRepath.period; + } + set { + this.autoRepath.period = value; + } + } + + /// <summary> + /// \copydocref{IAstarAI::canSearch} + /// Deprecated: This has been superseded by <see cref="autoRepath.mode"/>. + /// </summary> + public bool canSearch { + get { + return this.autoRepath.mode != AutoRepathPolicy.Mode.Never; + } + set { + if (value) { + if (this.autoRepath.mode == AutoRepathPolicy.Mode.Never) { + this.autoRepath.mode = AutoRepathPolicy.Mode.EveryNSeconds; + } + } else { + this.autoRepath.mode = AutoRepathPolicy.Mode.Never; + } + } + } + + /// <summary>\copydocref{IAstarAI.canMove}</summary> + public bool canMove = true; + + /// <summary>Max speed in world units per second</summary> + [UnityEngine.Serialization.FormerlySerializedAs("speed")] + public float maxSpeed = 1; + + /// <summary> + /// Gravity to use. + /// If set to (NaN,NaN,NaN) then Physics.Gravity (configured in the Unity project settings) will be used. + /// If set to (0,0,0) then no gravity will be used and no raycast to check for ground penetration will be performed. + /// </summary> + public Vector3 gravity = new Vector3(float.NaN, float.NaN, float.NaN); + + /// <summary> + /// Layer mask to use for ground placement. + /// Make sure this does not include the layer of any colliders attached to this gameobject. + /// + /// See: <see cref="gravity"/> + /// See: https://docs.unity3d.com/Manual/Layers.html + /// </summary> + public LayerMask groundMask = -1; + + /// <summary> + /// Distance to the end point to consider the end of path to be reached. + /// + /// When the end of the path is within this distance then <see cref="IAstarAI.reachedEndOfPath"/> will return true. + /// When the <see cref="destination"/> is within this distance then <see cref="IAstarAI.reachedDestination"/> will return true. + /// + /// Note that the <see cref="destination"/> may not be reached just because the end of the path was reached. The <see cref="destination"/> may not be reachable at all. + /// + /// See: <see cref="IAstarAI.reachedEndOfPath"/> + /// See: <see cref="IAstarAI.reachedDestination"/> + /// </summary> + public float endReachedDistance = 0.2f; + + /// <summary> + /// What to do when within <see cref="endReachedDistance"/> units from the destination. + /// The character can either stop immediately when it comes within that distance, which is useful for e.g archers + /// or other ranged units that want to fire on a target. Or the character can continue to try to reach the exact + /// destination point and come to a full stop there. This is useful if you want the character to reach the exact + /// point that you specified. + /// + /// Note: <see cref="IAstarAI.reachedEndOfPath"/> will become true when the character is within <see cref="endReachedDistance"/> units from the destination + /// regardless of what this field is set to. + /// </summary> + public CloseToDestinationMode whenCloseToDestination = CloseToDestinationMode.Stop; + + /// <summary> + /// Controls if the agent slows down to a stop if the area around the destination is crowded. + /// + /// Using this module requires that local avoidance is used: i.e. that an RVOController is attached to the GameObject. + /// + /// See: <see cref="Pathfinding.RVO.RVODestinationCrowdedBehavior"/> + /// See: local-avoidance (view in online documentation for working links) + /// </summary> + public RVODestinationCrowdedBehavior rvoDensityBehavior = new RVODestinationCrowdedBehavior(true, 0.5f, false); + + /// <summary> + /// Offset along the Y coordinate for the ground raycast start position. + /// Normally the pivot of the character is at the character's feet, but you usually want to fire the raycast + /// from the character's center, so this value should be half of the character's height. + /// + /// A green gizmo line will be drawn upwards from the pivot point of the character to indicate where the raycast will start. + /// + /// See: <see cref="gravity"/> + /// Deprecated: Use the <see cref="height"/> property instead (2x this value) + /// </summary> + [System.Obsolete("Use the height property instead (2x this value)")] + public float centerOffset { + get { return height * 0.5f; } set { height = value * 2; } + } + + [SerializeField] + [HideInInspector] + [FormerlySerializedAs("centerOffset")] + float centerOffsetCompatibility = float.NaN; + + [SerializeField] + [HideInInspector] + [UnityEngine.Serialization.FormerlySerializedAs("repathRate")] + float repathRateCompatibility = float.NaN; + + [SerializeField] + [HideInInspector] + [UnityEngine.Serialization.FormerlySerializedAs("canSearch")] + [UnityEngine.Serialization.FormerlySerializedAs("repeatedlySearchPaths")] + bool canSearchCompability = false; + + /// <summary> + /// Determines which direction the agent moves in. + /// For 3D games you most likely want the ZAxisIsForward option as that is the convention for 3D games. + /// For 2D games you most likely want the YAxisIsForward option as that is the convention for 2D games. + /// + /// Using the YAxisForward option will also allow the agent to assume that the movement will happen in the 2D (XY) plane instead of the XZ plane + /// if it does not know. This is important only for the point graph which does not have a well defined up direction. The other built-in graphs (e.g the grid graph) + /// will all tell the agent which movement plane it is supposed to use. + /// + /// [Open online documentation to see images] + /// </summary> + [UnityEngine.Serialization.FormerlySerializedAs("rotationIn2D")] + public OrientationMode orientation = OrientationMode.ZAxisForward; + + /// <summary> + /// If true, the forward axis of the character will be along the Y axis instead of the Z axis. + /// + /// Deprecated: Use <see cref="orientation"/> instead + /// </summary> + [System.Obsolete("Use orientation instead")] + public bool rotationIn2D { + get { return orientation == OrientationMode.YAxisForward; } + set { orientation = value ? OrientationMode.YAxisForward : OrientationMode.ZAxisForward; } + } + + /// <summary> + /// If true, the AI will rotate to face the movement direction. + /// See: <see cref="orientation"/> + /// </summary> + public bool enableRotation = true; + + /// <summary> + /// Position of the agent. + /// If <see cref="updatePosition"/> is true then this value will be synchronized every frame with Transform.position. + /// </summary> + protected Vector3 simulatedPosition; + + /// <summary> + /// Rotation of the agent. + /// If <see cref="updateRotation"/> is true then this value will be synchronized every frame with Transform.rotation. + /// </summary> + protected Quaternion simulatedRotation; + + /// <summary> + /// Position of the agent. + /// In world space. + /// If <see cref="updatePosition"/> is true then this value is idential to transform.position. + /// See: <see cref="Teleport"/> + /// See: <see cref="Move"/> + /// </summary> + public Vector3 position { get { return updatePosition ? tr.position : simulatedPosition; } } + + /// <summary> + /// Rotation of the agent. + /// If <see cref="updateRotation"/> is true then this value is identical to transform.rotation. + /// </summary> + public virtual Quaternion rotation { + get { return updateRotation ? tr.rotation : simulatedRotation; } + set { + if (updateRotation) { + tr.rotation = value; + } else { + simulatedRotation = value; + } + } + } + + /// <summary>Accumulated movement deltas from the <see cref="Move"/> method</summary> + protected Vector3 accumulatedMovementDelta = Vector3.zero; + + /// <summary> + /// Current desired velocity of the agent (does not include local avoidance and physics). + /// Lies in the movement plane. + /// </summary> + protected Vector2 velocity2D; + + /// <summary> + /// Velocity due to gravity. + /// Perpendicular to the movement plane. + /// + /// When the agent is grounded this may not accurately reflect the velocity of the agent. + /// It may be non-zero even though the agent is not moving. + /// </summary> + protected float verticalVelocity; + + /// <summary>Cached Seeker component</summary> + protected Seeker seeker; + + /// <summary>Cached Transform component</summary> + protected Transform tr; + + /// <summary>Cached Rigidbody component</summary> + protected Rigidbody rigid; + + /// <summary>Cached Rigidbody component</summary> + protected Rigidbody2D rigid2D; + + /// <summary>Cached CharacterController component</summary> + protected CharacterController controller; + + /// <summary>Cached RVOController component</summary> + protected RVOController rvoController; + + /// <summary> + /// Plane which this agent is moving in. + /// This is used to convert between world space and a movement plane to make it possible to use this script in + /// both 2D games and 3D games. + /// </summary> + public SimpleMovementPlane movementPlane = new SimpleMovementPlane(Quaternion.identity); + + /// <summary> + /// Determines if the character's position should be coupled to the Transform's position. + /// If false then all movement calculations will happen as usual, but the object that this component is attached to will not move + /// instead only the <see cref="position"/> property will change. + /// + /// This is useful if you want to control the movement of the character using some other means such + /// as for example root motion but still want the AI to move freely. + /// See: Combined with calling <see cref="MovementUpdate"/> from a separate script instead of it being called automatically one can take a similar approach to what is documented here: https://docs.unity3d.com/Manual/nav-CouplingAnimationAndNavigation.html + /// + /// See: <see cref="canMove"/> which in contrast to this field will disable all movement calculations. + /// See: <see cref="updateRotation"/> + /// </summary> + [System.NonSerialized] + public bool updatePosition = true; + + /// <summary> + /// Determines if the character's rotation should be coupled to the Transform's rotation. + /// If false then all movement calculations will happen as usual, but the object that this component is attached to will not rotate + /// instead only the <see cref="rotation"/> property will change. + /// + /// See: <see cref="updatePosition"/> + /// </summary> + [System.NonSerialized] + public bool updateRotation = true; + + /// <summary> + /// Determines how the agent recalculates its path automatically. + /// This corresponds to the settings under the "Recalculate Paths Automatically" field in the inspector. + /// </summary> + public AutoRepathPolicy autoRepath = new AutoRepathPolicy(); + + /// <summary>Indicates if gravity is used during this frame</summary> + protected bool usingGravity { get; set; } + + /// <summary>Delta time used for movement during the last frame</summary> + protected float lastDeltaTime; + + /// <summary>Position of the character at the end of the last frame</summary> + protected Vector3 prevPosition1; + + /// <summary>Position of the character at the end of the frame before the last frame</summary> + protected Vector3 prevPosition2; + + /// <summary>Amount which the character wants or tried to move with during the last frame</summary> + protected Vector2 lastDeltaPosition; + + /// <summary>Only when the previous path has been calculated should the script consider searching for a new path</summary> + protected bool waitingForPathCalculation = false; + + /// <summary>Time when the last path request was started</summary> + protected float lastRepath = float.NegativeInfinity; + + [UnityEngine.Serialization.FormerlySerializedAs("target")][SerializeField][HideInInspector] + Transform targetCompatibility; + + /// <summary> + /// True if the Start method has been executed. + /// Used to test if coroutines should be started in OnEnable to prevent calculating paths + /// in the awake stage (or rather before start on frame 0). + /// </summary> + protected bool startHasRun = false; + + /// <summary> + /// Target to move towards. + /// The AI will try to follow/move towards this target. + /// It can be a point on the ground where the player has clicked in an RTS for example, or it can be the player object in a zombie game. + /// + /// Deprecated: In 4.1 this will automatically add a <see cref="Pathfinding.AIDestinationSetter"/> component and set the target on that component. + /// Try instead to use the <see cref="destination"/> property which does not require a transform to be created as the target or use + /// the AIDestinationSetter component directly. + /// </summary> + [System.Obsolete("Use the destination property or the AIDestinationSetter component instead")] + public Transform target { + get { + return TryGetComponent(out AIDestinationSetter setter) ? setter.target : null; + } + set { + targetCompatibility = null; + if (!TryGetComponent(out AIDestinationSetter setter)) setter = gameObject.AddComponent<AIDestinationSetter>(); + setter.target = value; + destination = value != null ? value.position : new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + } + } + + /// <summary>Backing field for <see cref="destination"/></summary> + Vector3 destinationBackingField = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + + /// <summary>\copydocref{IAstarAI.destination}</summary> + public Vector3 destination { + get { return destinationBackingField; } + set { + // Note: vector3 equality operator will return false if both are (inf,inf,inf). So do the extra check to see if both are infinity. + if (rvoDensityBehavior.enabled && !(value == destinationBackingField || (float.IsPositiveInfinity(value.x) && float.IsPositiveInfinity(destinationBackingField.x)))) { + destinationBackingField = value; + rvoDensityBehavior.OnDestinationChanged(value, reachedDestination); + } else { + destinationBackingField = value; + } + } + } + + /// <summary>\copydocref{IAstarAI.velocity}</summary> + public Vector3 velocity { + get { + return lastDeltaTime > 0.000001f ? (prevPosition1 - prevPosition2) / lastDeltaTime : Vector3.zero; + } + } + + /// <summary>\copydocref{IAstarAI.desiredVelocity}</summary> + public Vector3 desiredVelocity { + get { return lastDeltaTime > 0.00001f ? movementPlane.ToWorld(lastDeltaPosition / lastDeltaTime, verticalVelocity) : Vector3.zero; } + } + + /// <summary>\copydocref{IAstarAI.desiredVelocityWithoutLocalAvoidance}</summary> + public Vector3 desiredVelocityWithoutLocalAvoidance { + get { return movementPlane.ToWorld(velocity2D, verticalVelocity); } + set { velocity2D = movementPlane.ToPlane(value, out verticalVelocity); } + } + + /// <summary>\copydocref{IAstarAI.endOfPath}</summary> + public abstract Vector3 endOfPath { get; } + + /// <summary>\copydocref{IAstarAI.reachedDestination}</summary> + public abstract bool reachedDestination { get; } + + /// <summary>\copydocref{IAstarAI.isStopped}</summary> + public bool isStopped { get; set; } + + /// <summary>\copydocref{IAstarAI.onSearchPath}</summary> + public System.Action onSearchPath { get; set; } + + /// <summary> + /// Cached delegate for the <see cref="OnPathComplete"/> method. + /// + /// Caching this avoids allocating a new one every time a path is calculated, which reduces GC pressure. + /// </summary> + protected OnPathDelegate onPathComplete; + + /// <summary>True if the path should be automatically recalculated as soon as possible</summary> + protected virtual bool shouldRecalculatePath { + get { + return !waitingForPathCalculation && autoRepath.ShouldRecalculatePath(position, radius, destination, Time.time); + } + } + + /// <summary> + /// Looks for any attached components like RVOController and CharacterController etc. + /// + /// This is done during <see cref="OnEnable"/>. If you are adding/removing components during runtime you may want to call this function + /// to make sure that this script finds them. It is unfortunately prohibitive from a performance standpoint to look for components every frame. + /// </summary> + public virtual void FindComponents () { + tr = transform; + // GetComponent is a bit slow, so only call it if we don't know about the component already. + // This is important when selecting a lot of objects in the editor as OnDrawGizmos will call + // this method every frame when outside of play mode. + if (!seeker) TryGetComponent(out seeker); + if (!rvoController) TryGetComponent(out rvoController); + // Find attached movement components + if (!controller) TryGetComponent(out controller); + if (!rigid) TryGetComponent(out rigid); + if (!rigid2D) TryGetComponent(out rigid2D); + } + + /// <summary>Called when the component is enabled</summary> + protected virtual void OnEnable () { + FindComponents(); + onPathComplete = OnPathComplete; + Init(); + + // When using rigidbodies all movement is done inside FixedUpdate instead of Update + bool fixedUpdate = rigid != null || rigid2D != null; + BatchedEvents.Add(this, fixedUpdate ? BatchedEvents.Event.FixedUpdate : BatchedEvents.Event.Update, OnUpdate); + } + + /// <summary> + /// Called every frame. + /// This may be called during FixedUpdate or Update depending on if a rigidbody is attached to the GameObject. + /// </summary> + static void OnUpdate (AIBase[] components, int count, TransformAccessArray transforms, BatchedEvents.Event ev) { + // Sync transforms to ensure raycasts will hit the correct colliders + Physics.SyncTransforms(); + Physics2D.SyncTransforms(); + + float dt = ev == BatchedEvents.Event.FixedUpdate ? Time.fixedDeltaTime : Time.deltaTime; + + var simulator = RVOSimulator.active?.GetSimulator(); + if (simulator != null) { + int agentsWithRVOControllers = 0; + for (int i = 0; i < count; i++) agentsWithRVOControllers += (components[i].rvoController != null && components[i].rvoController.enabled ? 1 : 0); + RVODestinationCrowdedBehavior.JobDensityCheck densityJobData = new RVODestinationCrowdedBehavior.JobDensityCheck(agentsWithRVOControllers, dt); + + for (int i = 0, j = 0; i < count; i++) { + var agent = components[i]; + if (agent.rvoController != null && agent.rvoController.enabled) { + densityJobData.Set(j, agent.rvoController.rvoAgent.AgentIndex, agent.endOfPath, agent.rvoDensityBehavior.densityThreshold, agent.rvoDensityBehavior.progressAverage); + j++; + } + } + var densityJob = densityJobData.ScheduleBatch(agentsWithRVOControllers, agentsWithRVOControllers / 16, simulator.lastJob); + densityJob.Complete(); + + for (int i = 0, j = 0; i < count; i++) { + var agent = components[i]; + if (agent.rvoController != null && agent.rvoController.enabled) { + agent.rvoDensityBehavior.ReadJobResult(ref densityJobData, j); + j++; + } + } + + densityJobData.Dispose(); + } + + for (int i = 0; i < count; i++) { + var agent = components[i]; + UnityEngine.Profiling.Profiler.BeginSample("OnUpdate"); + agent.OnUpdate(dt); + UnityEngine.Profiling.Profiler.EndSample(); + } + + if (count > 0 && components[0] is AIPathAlignedToSurface) { + AIPathAlignedToSurface.UpdateMovementPlanes(components as AIPathAlignedToSurface[], count); + } + + Physics.SyncTransforms(); + Physics2D.SyncTransforms(); + } + + /// <summary>Called every frame</summary> + protected virtual void OnUpdate (float dt) { + // If gravity is used depends on a lot of things. + // For example when a non-kinematic rigidbody is used then the rigidbody will apply the gravity itself + // Note that the gravity can contain NaN's, which is why the comparison uses !(a==b) instead of just a!=b. + usingGravity = !(gravity == Vector3.zero) && (!updatePosition || ((rigid == null || rigid.isKinematic) && (rigid2D == null || rigid2D.isKinematic))); + + if (shouldRecalculatePath) SearchPath(); + + if (canMove) { + MovementUpdate(dt, out var nextPosition, out var nextRotation); + UnityEngine.Profiling.Profiler.BeginSample("Finalize"); + FinalizeMovement(nextPosition, nextRotation); + UnityEngine.Profiling.Profiler.EndSample(); + } + } + + /// <summary> + /// Starts searching for paths. + /// If you override this method you should in most cases call base.Start () at the start of it. + /// See: <see cref="Init"/> + /// </summary> + protected virtual void Start () { + startHasRun = true; + Init(); + } + + void Init () { + if (startHasRun) { + // Clamp the agent to the navmesh (which is what the Teleport call will do essentially. Though only some movement scripts require this, like RichAI). + // The Teleport call will also make sure some variables are properly initialized (like #prevPosition1 and #prevPosition2) + if (canMove) Teleport(position, false); + autoRepath.Reset(); + if (shouldRecalculatePath) SearchPath(); + } + } + + /// <summary>\copydocref{IAstarAI.Teleport}</summary> + public virtual void Teleport (Vector3 newPosition, bool clearPath = true) { + if (clearPath) ClearPath(); + prevPosition1 = prevPosition2 = simulatedPosition = newPosition; + if (updatePosition) tr.position = newPosition; + if (rvoController != null) rvoController.Move(Vector3.zero); + if (clearPath) SearchPath(); + } + + protected void CancelCurrentPathRequest () { + waitingForPathCalculation = false; + // Abort calculation of the current path + if (seeker != null) seeker.CancelCurrentPathRequest(); + } + + protected virtual void OnDisable () { + BatchedEvents.Remove(this); + ClearPath(); + + velocity2D = Vector3.zero; + accumulatedMovementDelta = Vector3.zero; + verticalVelocity = 0f; + lastDeltaTime = 0; + } + + /// <summary>\copydocref{IAstarAI.MovementUpdate}</summary> + public void MovementUpdate (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation) { + lastDeltaTime = deltaTime; + MovementUpdateInternal(deltaTime, out nextPosition, out nextRotation); + } + + /// <summary>Called during either Update or FixedUpdate depending on if rigidbodies are used for movement or not</summary> + protected abstract void MovementUpdateInternal(float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation); + + /// <summary> + /// Outputs the start point and end point of the next automatic path request. + /// This is a separate method to make it easy for subclasses to swap out the endpoints + /// of path requests. For example the <see cref="LocalSpaceRichAI"/> script which requires the endpoints + /// to be transformed to graph space first. + /// </summary> + protected virtual void CalculatePathRequestEndpoints (out Vector3 start, out Vector3 end) { + start = GetFeetPosition(); + end = destination; + } + + /// <summary>\copydocref{IAstarAI.SearchPath}</summary> + public virtual void SearchPath () { + if (float.IsPositiveInfinity(destination.x)) return; + if (onSearchPath != null) onSearchPath(); + + // Find out where we are and where we are going + Vector3 start, end; + CalculatePathRequestEndpoints(out start, out end); + + // Request a path to be calculated from our current position to the destination + ABPath p = ABPath.Construct(start, end, null); + SetPath(p, false); + } + + /// <summary> + /// Position of the base of the character. + /// This is used for pathfinding as the character's pivot point is sometimes placed + /// at the center of the character instead of near the feet. In a building with multiple floors + /// the center of a character may in some scenarios be closer to the navmesh on the floor above + /// than to the floor below which could cause an incorrect path to be calculated. + /// To solve this the start point of the requested paths is always at the base of the character. + /// </summary> + public virtual Vector3 GetFeetPosition () { + return position; + } + + /// <summary>Called when a requested path has been calculated</summary> + protected abstract void OnPathComplete(Path newPath); + + /// <summary> + /// Clears the current path of the agent. + /// + /// Usually invoked using SetPath(null). + /// + /// See: <see cref="SetPath"/> + /// See: <see cref="isStopped"/> + /// </summary> + protected abstract void ClearPath(); + + /// <summary>\copydocref{IAstarAI.SetPath}</summary> + public void SetPath (Path path, bool updateDestinationFromPath = true) { + if (updateDestinationFromPath && path is ABPath abPath && abPath.endPointKnownBeforeCalculation) { + this.destination = abPath.originalEndPoint; + } + + if (path == null) { + CancelCurrentPathRequest(); + ClearPath(); + } else if (path.PipelineState == PathState.Created) { + // Path has not started calculation yet + waitingForPathCalculation = true; + seeker.CancelCurrentPathRequest(); + seeker.StartPath(path, onPathComplete); + autoRepath.DidRecalculatePath(destination, Time.time); + } else if (path.PipelineState >= PathState.Returning) { + // Path has already been calculated + + // We might be calculating another path at the same time, and we don't want that path to override this one. So cancel it. + if (seeker.GetCurrentPath() != path) seeker.CancelCurrentPathRequest(); + + OnPathComplete(path); + } else { + // Path calculation has been started, but it is not yet complete. Cannot really handle this. + throw new System.ArgumentException("You must call the SetPath method with a path that either has been completely calculated or one whose path calculation has not been started at all. It looks like the path calculation for the path you tried to use has been started, but is not yet finished."); + } + } + + /// <summary> + /// Accelerates the agent downwards. + /// See: <see cref="verticalVelocity"/> + /// See: <see cref="gravity"/> + /// </summary> + protected virtual void ApplyGravity (float deltaTime) { + // Apply gravity + if (usingGravity) { + float verticalGravity; + velocity2D += movementPlane.ToPlane(deltaTime * (float.IsNaN(gravity.x) ? Physics.gravity : gravity), out verticalGravity); + verticalVelocity += verticalGravity; + } else { + verticalVelocity = 0; + } + } + + /// <summary>Calculates how far to move during a single frame</summary> + protected Vector2 CalculateDeltaToMoveThisFrame (Vector3 position, float distanceToEndOfPath, float deltaTime) { + if (rvoController != null && rvoController.enabled) { + // Use RVOController to get a processed delta position + // such that collisions will be avoided if possible + return movementPlane.ToPlane(rvoController.CalculateMovementDelta(position, deltaTime)); + } + // Direction and distance to move during this frame + return Vector2.ClampMagnitude(velocity2D * deltaTime, distanceToEndOfPath); + } + + /// <summary> + /// Simulates rotating the agent towards the specified direction and returns the new rotation. + /// + /// Note that this only calculates a new rotation, it does not change the actual rotation of the agent. + /// Useful when you are handling movement externally using <see cref="FinalizeMovement"/> but you want to use the built-in rotation code. + /// + /// See: <see cref="orientation"/> + /// </summary> + /// <param name="direction">Direction in world space to rotate towards.</param> + /// <param name="maxDegrees">Maximum number of degrees to rotate this frame.</param> + public Quaternion SimulateRotationTowards (Vector3 direction, float maxDegrees) { + return SimulateRotationTowards(movementPlane.ToPlane(direction), maxDegrees, maxDegrees); + } + + /// <summary> + /// Simulates rotating the agent towards the specified direction and returns the new rotation. + /// + /// Note that this only calculates a new rotation, it does not change the actual rotation of the agent. + /// + /// See: <see cref="orientation"/> + /// See: <see cref="movementPlane"/> + /// </summary> + /// <param name="direction">Direction in the movement plane to rotate towards.</param> + /// <param name="maxDegreesMainAxis">Maximum number of degrees to rotate this frame around the character's main axis. This is rotating left and right as a character normally does.</param> + /// <param name="maxDegreesOffAxis">Maximum number of degrees to rotate this frame around other axes. This is used to ensure the character's up direction is correct. + /// It is only used for non-planar worlds where the up direction changes depending on the position of the character. + /// More precisely a faster code path which ignores this parameter is used whenever the current #movementPlane is exactly the XZ or XY plane. + /// This must be at least as large as maxDegreesMainAxis.</param> + protected Quaternion SimulateRotationTowards (Vector2 direction, float maxDegreesMainAxis, float maxDegreesOffAxis = float.PositiveInfinity) { + Quaternion targetRotation; + + if (movementPlane.isXY || movementPlane.isXZ) { + if (direction == Vector2.zero) return simulatedRotation; + + // Common fast path. + // A standard XY or XZ movement plane indicates that the character is moving in a normal planar world. + // We will use a much faster code path for this case since we don't have to deal with changing the 'up' direction of the character all the time. + // This code path mostly works for non-planar worlds too, but it will fail in some cases. + // In particular it will not be able to adjust the up direction of the character while it is standing still (because then a zero maxDegreesMainAxis is usually passed). + // That case may be important, especially when the character has just been spawned and does not have a destination yet. + targetRotation = Quaternion.LookRotation(movementPlane.ToWorld(direction, 0), movementPlane.ToWorld(Vector2.zero, 1)); + maxDegreesOffAxis = maxDegreesMainAxis; + } else { + // Decompose the rotation into two parts: a rotation around the main axis of the character, and a rotation around the other axes. + // Then limit the rotation speed along those two components separately. + var forwardInPlane = movementPlane.ToPlane(rotation * (orientation == OrientationMode.YAxisForward ? Vector3.up : Vector3.forward)); + + // Can happen if the character is perpendicular to the plane + if (forwardInPlane == Vector2.zero) forwardInPlane = Vector2.right; + + var rotationVectorAroundMainAxis = VectorMath.ComplexMultiplyConjugate(direction, forwardInPlane); + + // Note: If the direction is zero, then angle will also be zero since atan2(0,0) = 0 + var angle = Mathf.Atan2(rotationVectorAroundMainAxis.y, rotationVectorAroundMainAxis.x) * Mathf.Rad2Deg; + var rotationAroundMainAxis = Quaternion.AngleAxis(-Mathf.Min(Mathf.Abs(angle), maxDegreesMainAxis) * Mathf.Sign(angle), Vector3.up); + + targetRotation = Quaternion.LookRotation(movementPlane.ToWorld(forwardInPlane, 0), movementPlane.ToWorld(Vector2.zero, 1)); + targetRotation = targetRotation * rotationAroundMainAxis; + } + + // This causes the character to only rotate around the Z axis + if (orientation == OrientationMode.YAxisForward) targetRotation *= Quaternion.Euler(90, 0, 0); + return Quaternion.RotateTowards(simulatedRotation, targetRotation, maxDegreesOffAxis); + } + + /// <summary>\copydocref{IAstarAI.Move}</summary> + public virtual void Move (Vector3 deltaPosition) { + accumulatedMovementDelta += deltaPosition; + } + + /// <summary> + /// Moves the agent to a position. + /// + /// This is used if you want to override how the agent moves. For example if you are using + /// root motion with Mecanim. + /// + /// This will use a CharacterController, Rigidbody, Rigidbody2D or the Transform component depending on what options + /// are available. + /// + /// The agent will be clamped to the navmesh after the movement (if such information is available, generally this is only done by the RichAI component). + /// + /// See: <see cref="MovementUpdate"/> for some example code. + /// See: <see cref="controller"/>, <see cref="rigid"/>, <see cref="rigid2D"/> + /// </summary> + /// <param name="nextPosition">New position of the agent.</param> + /// <param name="nextRotation">New rotation of the agent. If #enableRotation is false then this parameter will be ignored.</param> + public virtual void FinalizeMovement (Vector3 nextPosition, Quaternion nextRotation) { + if (enableRotation) FinalizeRotation(nextRotation); + FinalizePosition(nextPosition); + } + + void FinalizeRotation (Quaternion nextRotation) { + simulatedRotation = nextRotation; + if (updateRotation) { + if (rigid != null) rigid.MoveRotation(nextRotation); + else if (rigid2D != null) rigid2D.MoveRotation(nextRotation.eulerAngles.z); + else tr.rotation = nextRotation; + } + } + + void FinalizePosition (Vector3 nextPosition) { + // Use a local variable, it is significantly faster + Vector3 currentPosition = simulatedPosition; + bool positionDirty1 = false; + + if (controller != null && controller.enabled && updatePosition) { + // Use CharacterController + // The Transform may not be at #position if it was outside the navmesh and had to be moved to the closest valid position + tr.position = currentPosition; + controller.Move((nextPosition - currentPosition) + accumulatedMovementDelta); + // Grab the position after the movement to be able to take physics into account + // TODO: Add this into the clampedPosition calculation below to make RVO better respond to physics + currentPosition = tr.position; + if (controller.isGrounded) verticalVelocity = 0; + } else { + // Use Transform, Rigidbody, Rigidbody2D or nothing at all (if updatePosition = false) + float lastElevation; + movementPlane.ToPlane(currentPosition, out lastElevation); + currentPosition = nextPosition + accumulatedMovementDelta; + + // Position the character on the ground + if (usingGravity) currentPosition = RaycastPosition(currentPosition, lastElevation); + positionDirty1 = true; + } + + // Clamp the position to the navmesh after movement is done + bool positionDirty2 = false; + currentPosition = ClampToNavmesh(currentPosition, out positionDirty2); + + // Assign the final position to the character if we haven't already set it (mostly for performance, setting the position can be slow) + if ((positionDirty1 || positionDirty2) && updatePosition) { + // Note that rigid.MovePosition may or may not move the character immediately. + // Check the Unity documentation for the special cases. + if (rigid != null) rigid.MovePosition(currentPosition); + else if (rigid2D != null) rigid2D.MovePosition(currentPosition); + else tr.position = currentPosition; + } + + accumulatedMovementDelta = Vector3.zero; + simulatedPosition = currentPosition; + UpdateVelocity(); + } + + protected void UpdateVelocity () { + prevPosition2 = prevPosition1; + prevPosition1 = position; + } + + /// <summary> + /// Constrains the character's position to lie on the navmesh. + /// Not all movement scripts have support for this. + /// + /// Returns: New position of the character that has been clamped to the navmesh. + /// </summary> + /// <param name="position">Current position of the character.</param> + /// <param name="positionChanged">True if the character's position was modified by this method.</param> + protected virtual Vector3 ClampToNavmesh (Vector3 position, out bool positionChanged) { + positionChanged = false; + return position; + } + + /// <summary> + /// Hit info from the last raycast done for ground placement. + /// Will not update unless gravity is used (if no gravity is used, then raycasts are disabled). + /// + /// See: <see cref="RaycastPosition"/> + /// </summary> + protected RaycastHit lastRaycastHit; + + /// <summary> + /// Checks if the character is grounded and prevents ground penetration. + /// + /// Sets <see cref="verticalVelocity"/> to zero if the character is grounded. + /// + /// Returns: The new position of the character. + /// </summary> + /// <param name="position">Position of the character in the world.</param> + /// <param name="lastElevation">Elevation coordinate before the agent was moved. This is along the 'up' axis of the #movementPlane.</param> + protected Vector3 RaycastPosition (Vector3 position, float lastElevation) { + float elevation; + + movementPlane.ToPlane(position, out elevation); + float rayLength = tr.localScale.y * height * 0.5f + Mathf.Max(0, lastElevation-elevation); + Vector3 rayOffset = movementPlane.ToWorld(Vector2.zero, rayLength); + + if (Physics.Raycast(position + rayOffset, -rayOffset, out lastRaycastHit, rayLength, groundMask, QueryTriggerInteraction.Ignore)) { + // Grounded + // Make the vertical velocity fall off exponentially. This is reasonable from a physical standpoint as characters + // are not completely stiff and touching the ground will not immediately negate all velocity downwards. The AI will + // stop moving completely due to the raycast penetration test but it will still *try* to move downwards. This helps + // significantly when moving down along slopes as if the vertical velocity would be set to zero when the character + // was grounded it would lead to a kind of 'bouncing' behavior (try it, it's hard to explain). Ideally this should + // use a more physically correct formula but this is a good approximation and is much more performant. The constant + // '5' in the expression below determines how quickly it converges but high values can lead to too much noise. + verticalVelocity *= System.Math.Max(0, 1 - 5 * lastDeltaTime); + return lastRaycastHit.point; + } + return position; + } + + protected virtual void OnDrawGizmosSelected () { + // When selected in the Unity inspector it's nice to make the component react instantly if + // any other components are attached/detached or enabled/disabled. + // We don't want to do this normally every frame because that would be expensive. + if (Application.isPlaying) FindComponents(); + } + + public static readonly Color ShapeGizmoColor = new Color(240/255f, 213/255f, 30/255f); + + public override void DrawGizmos () { + if (!Application.isPlaying || !enabled || tr == null) FindComponents(); + + var color = ShapeGizmoColor; + if (rvoController != null && rvoController.locked) color *= 0.5f; + if (orientation == OrientationMode.YAxisForward) { + Draw.WireCylinder(position, Vector3.forward, 0, radius * tr.localScale.x, color); + } else { + Draw.WireCylinder(position, rotation * Vector3.up, tr.localScale.y * height, radius * tr.localScale.x, color); + } + + if (!float.IsPositiveInfinity(destination.x) && Application.isPlaying) Draw.Circle(destination, movementPlane.rotation * Vector3.up, 0.2f, Color.blue); + + autoRepath.DrawGizmos(Draw.editor, position, radius, new NativeMovementPlane(movementPlane.rotation)); + } + + protected override void Reset () { + ResetShape(); + base.Reset(); + } + + void ResetShape () { + if (TryGetComponent(out CharacterController cc)) { + radius = cc.radius; + height = Mathf.Max(radius*2, cc.height); + } + } + + protected override void OnUpgradeSerializedData (ref Serialization.Migrations migrations, bool unityThread) { + if (migrations.TryMigrateFromLegacyFormat(out var legacyVersion)) { + // Version == 5 is the 4.2 branch. + if (legacyVersion <= 2 || legacyVersion == 5) rvoDensityBehavior.enabled = false; + + if (legacyVersion <= 3) { + repathRate = repathRateCompatibility; + canSearch = canSearchCompability; + } + } + if (unityThread && !float.IsNaN(centerOffsetCompatibility)) { + height = centerOffsetCompatibility*2; + ResetShape(); + if (TryGetComponent(out RVOController rvo)) radius = rvo.radiusBackingField; + centerOffsetCompatibility = float.NaN; + } + #pragma warning disable 618 + if (unityThread && targetCompatibility != null) target = targetCompatibility; + #pragma warning restore 618 + } + } +} diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AIBase.cs.meta b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AIBase.cs.meta new file mode 100644 index 0000000..b9f18be --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AIBase.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a08f67bbe580e4ddfaebd06363c9cc97 +timeCreated: 1496932372 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 100 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AILerp.cs b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AILerp.cs new file mode 100644 index 0000000..681420d --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AILerp.cs @@ -0,0 +1,770 @@ +using UnityEngine; +using System.Collections; +using System.Collections.Generic; + +namespace Pathfinding { + using Pathfinding.Util; + + /// <summary> + /// Linearly interpolating movement script. + /// + /// This movement script will follow the path exactly, it uses linear interpolation to move between the waypoints in the path. + /// This is desirable for some types of games. + /// It also works in 2D. + /// + /// See: You can see an example of this script in action in the example scene called Example15_2D. + /// + /// \section rec Configuration + /// \subsection rec-snapped Recommended setup for movement along connections + /// + /// This depends on what type of movement you are aiming for. + /// If you are aiming for movement where the unit follows the path exactly and move only along the graph connections on a grid/point graph. + /// I recommend that you adjust the StartEndModifier on the Seeker component: set the 'Start Point Snapping' field to 'NodeConnection' and the 'End Point Snapping' field to 'SnapToNode'. + /// [Open online documentation to see images] + /// [Open online documentation to see images] + /// + /// \subsection rec-smooth Recommended setup for smooth movement + /// If you on the other hand want smoother movement I recommend setting 'Start Point Snapping' and 'End Point Snapping' to 'ClosestOnNode' and to add the Simple Smooth Modifier to the GameObject as well. + /// Alternatively you can use the <see cref="Pathfinding.FunnelModifier Funnel"/> which works better on navmesh/recast graphs or the <see cref="Pathfinding.RaycastModifier"/>. + /// + /// You should not combine the Simple Smooth Modifier or the Funnel Modifier with the NodeConnection snapping mode. This may lead to very odd behavior. + /// + /// [Open online documentation to see images] + /// [Open online documentation to see images] + /// You may also want to tweak the <see cref="rotationSpeed"/>. + /// </summary> + [RequireComponent(typeof(Seeker))] + [AddComponentMenu("Pathfinding/AI/AILerp (2D,3D)")] + [UniqueComponent(tag = "ai")] + [HelpURL("https://arongranberg.com/astar/documentation/stable/ailerp.html")] + public class AILerp : VersionedMonoBehaviour, IAstarAI { + /// <summary> + /// Determines how often it will search for new paths. + /// If you have fast moving targets or AIs, you might want to set it to a lower value. + /// The value is in seconds between path requests. + /// + /// Deprecated: This has been renamed to <see cref="autoRepath.period"/>. + /// See: <see cref="AutoRepathPolicy"/> + /// </summary> + public float repathRate { + get { + return this.autoRepath.period; + } + set { + this.autoRepath.period = value; + } + } + + /// <summary> + /// \copydoc Pathfinding::IAstarAI::canSearch + /// Deprecated: This has been superseded by <see cref="autoRepath.mode"/>. + /// </summary> + public bool canSearch { + get { + return this.autoRepath.mode != AutoRepathPolicy.Mode.Never; + } + set { + this.autoRepath.mode = value ? AutoRepathPolicy.Mode.EveryNSeconds : AutoRepathPolicy.Mode.Never; + } + } + + /// <summary> + /// Determines how the agent recalculates its path automatically. + /// This corresponds to the settings under the "Recalculate Paths Automatically" field in the inspector. + /// </summary> + public AutoRepathPolicy autoRepath = new AutoRepathPolicy(); + + /// <summary>\copydoc Pathfinding::IAstarAI::canMove</summary> + public bool canMove = true; + + /// <summary>Speed in world units</summary> + public float speed = 3; + + /// <summary> + /// Determines which direction the agent moves in. + /// For 3D games you most likely want the ZAxisIsForward option as that is the convention for 3D games. + /// For 2D games you most likely want the YAxisIsForward option as that is the convention for 2D games. + /// + /// Using the YAxisForward option will also allow the agent to assume that the movement will happen in the 2D (XY) plane instead of the XZ plane + /// if it does not know. This is important only for the point graph which does not have a well defined up direction. The other built-in graphs (e.g the grid graph) + /// will all tell the agent which movement plane it is supposed to use. + /// + /// [Open online documentation to see images] + /// </summary> + [UnityEngine.Serialization.FormerlySerializedAs("rotationIn2D")] + public OrientationMode orientation = OrientationMode.ZAxisForward; + + /// <summary> + /// If true, the forward axis of the character will be along the Y axis instead of the Z axis. + /// + /// Deprecated: Use <see cref="orientation"/> instead + /// </summary> + [System.Obsolete("Use orientation instead")] + public bool rotationIn2D { + get { return orientation == OrientationMode.YAxisForward; } + set { orientation = value ? OrientationMode.YAxisForward : OrientationMode.ZAxisForward; } + } + + /// <summary> + /// If true, the AI will rotate to face the movement direction. + /// See: <see cref="orientation"/> + /// </summary> + public bool enableRotation = true; + + /// <summary>How quickly to rotate</summary> + public float rotationSpeed = 10; + + /// <summary> + /// If true, some interpolation will be done when a new path has been calculated. + /// This is used to avoid short distance teleportation. + /// See: <see cref="switchPathInterpolationSpeed"/> + /// </summary> + public bool interpolatePathSwitches = true; + + /// <summary> + /// How quickly to interpolate to the new path. + /// See: <see cref="interpolatePathSwitches"/> + /// </summary> + public float switchPathInterpolationSpeed = 5; + + /// <summary>True if the end of the current path has been reached</summary> + public bool reachedEndOfPath { get; private set; } + + /// <summary>\copydoc Pathfinding::IAstarAI::reachedDestination</summary> + public bool reachedDestination { + get { + if (!reachedEndOfPath || !interpolator.valid) return false; + // Note: distanceToSteeringTarget is the distance to the end of the path when approachingPathEndpoint is true + var dir = destination - interpolator.endPoint; + // Ignore either the y or z coordinate depending on if we are using 2D mode or not + if (orientation == OrientationMode.YAxisForward) dir.z = 0; + else dir.y = 0; + + // Check against using a very small margin + // In theory a check against 0 should be done, but this will be a bit more resilient against targets that move slowly or maybe jitter around due to floating point errors. + if (remainingDistance + dir.magnitude >= 0.05f) return false; + + return true; + } + } + + public Vector3 destination { get; set; } + + /// <summary>\copydoc Pathfinding::IAstarAI::movementPlane</summary> + public NativeMovementPlane movementPlane { + get { + if (path != null && path.path.Count > 0) { + var graph = path.path[0].Graph; + if (graph is NavmeshBase navmeshBase) { + return new NativeMovementPlane(navmeshBase.transform.ToSimpleMovementPlane()); + } else if (graph is GridGraph gg) { + return new NativeMovementPlane(gg.transform.ToSimpleMovementPlane()); + } + } + return new NativeMovementPlane(Unity.Mathematics.quaternion.identity); + } + } + + /// <summary> + /// Determines if the character's position should be coupled to the Transform's position. + /// If false then all movement calculations will happen as usual, but the object that this component is attached to will not move + /// instead only the <see cref="position"/> property will change. + /// + /// See: <see cref="canMove"/> which in contrast to this field will disable all movement calculations. + /// See: <see cref="updateRotation"/> + /// </summary> + [System.NonSerialized] + public bool updatePosition = true; + + /// <summary> + /// Determines if the character's rotation should be coupled to the Transform's rotation. + /// If false then all movement calculations will happen as usual, but the object that this component is attached to will not rotate + /// instead only the <see cref="rotation"/> property will change. + /// + /// See: <see cref="updatePosition"/> + /// </summary> + [System.NonSerialized] + public bool updateRotation = true; + + /// <summary> + /// Cached delegate for the <see cref="OnPathComplete"/> method. + /// + /// Caching this avoids allocating a new one every time a path is calculated, which reduces GC pressure. + /// </summary> + protected OnPathDelegate onPathComplete; + + /// <summary> + /// Target to move towards. + /// The AI will try to follow/move towards this target. + /// It can be a point on the ground where the player has clicked in an RTS for example, or it can be the player object in a zombie game. + /// + /// Deprecated: In 4.0 this will automatically add a <see cref="Pathfinding.AIDestinationSetter"/> component and set the target on that component. + /// Try instead to use the <see cref="destination"/> property which does not require a transform to be created as the target or use + /// the AIDestinationSetter component directly. + /// </summary> + [System.Obsolete("Use the destination property or the AIDestinationSetter component instead")] + public Transform target { + get { + var setter = GetComponent<AIDestinationSetter>(); + return setter != null ? setter.target : null; + } + set { + targetCompatibility = null; + var setter = GetComponent<AIDestinationSetter>(); + if (setter == null) setter = gameObject.AddComponent<AIDestinationSetter>(); + setter.target = value; + destination = value != null ? value.position : new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::position</summary> + public Vector3 position { get { return updatePosition ? tr.position : simulatedPosition; } } + + /// <summary>\copydoc Pathfinding::IAstarAI::rotation</summary> + public Quaternion rotation { + get { return updateRotation ? tr.rotation : simulatedRotation; } + set { + if (updateRotation) { + tr.rotation = value; + } else { + simulatedRotation = value; + } + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::endOfPath</summary> + public Vector3 endOfPath { + get { + if (interpolator.valid) return interpolator.endPoint; + if (float.IsFinite(destination.x)) return destination; + return position; + } + } + + #region IAstarAI implementation + + /// <summary>\copydoc Pathfinding::IAstarAI::Move</summary> + void IAstarAI.Move (Vector3 deltaPosition) { + // This script does not know the concept of being away from the path that it is following + // so this call will be ignored (as is also mentioned in the documentation). + } + + /// <summary>\copydoc Pathfinding::IAstarAI::radius</summary> + float IAstarAI.radius { get { return 0; } set {} } + + /// <summary>\copydoc Pathfinding::IAstarAI::height</summary> + float IAstarAI.height { get { return 0; } set {} } + + /// <summary>\copydoc Pathfinding::IAstarAI::maxSpeed</summary> + float IAstarAI.maxSpeed { get { return speed; } set { speed = value; } } + + /// <summary>\copydoc Pathfinding::IAstarAI::canSearch</summary> + bool IAstarAI.canSearch { get { return canSearch; } set { canSearch = value; } } + + /// <summary>\copydoc Pathfinding::IAstarAI::canMove</summary> + bool IAstarAI.canMove { get { return canMove; } set { canMove = value; } } + + /// <summary>\copydoc Pathfinding::IAstarAI::velocity</summary> + public Vector3 velocity { + get { + return Time.deltaTime > 0.00001f ? (previousPosition1 - previousPosition2) / Time.deltaTime : Vector3.zero; + } + } + + Vector3 IAstarAI.desiredVelocity { + get { + // The AILerp script sets the position every frame. It does not take into account physics + // or other things. So the velocity should always be the same as the desired velocity. + return (this as IAstarAI).velocity; + } + } + + Vector3 IAstarAI.desiredVelocityWithoutLocalAvoidance { + get { + // The AILerp script sets the position every frame. It does not take into account physics + // or other things. So the velocity should always be the same as the desired velocity. + return (this as IAstarAI).velocity; + } + set { + throw new System.InvalidOperationException("The AILerp component does not support setting the desiredVelocityWithoutLocalAvoidance property since it does not make sense for how its movement works."); + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::steeringTarget</summary> + Vector3 IAstarAI.steeringTarget { + get { + // AILerp doesn't use steering at all, so we will just return a point ahead of the agent in the direction it is moving. + return interpolator.valid ? interpolator.position + interpolator.tangent : simulatedPosition; + } + } + + #endregion + + /// <summary>\copydoc Pathfinding::IAstarAI::remainingDistance</summary> + public float remainingDistance { + get { + return interpolator.valid ? Mathf.Max(interpolator.remainingDistance, 0) : float.PositiveInfinity; + } + set { + if (!interpolator.valid) throw new System.InvalidOperationException("Cannot set the remaining distance on the AILerp component because it doesn't have a path to follow."); + interpolator.remainingDistance = Mathf.Max(value, 0); + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::hasPath</summary> + public bool hasPath { + get { + return interpolator.valid; + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::pathPending</summary> + public bool pathPending { + get { + return !canSearchAgain; + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::isStopped</summary> + public bool isStopped { get; set; } + + /// <summary>\copydoc Pathfinding::IAstarAI::onSearchPath</summary> + public System.Action onSearchPath { get; set; } + + /// <summary>Cached Seeker component</summary> + protected Seeker seeker; + + /// <summary>Cached Transform component</summary> + protected Transform tr; + + /// <summary>Current path which is followed</summary> + protected ABPath path; + + /// <summary>Only when the previous path has been returned should a search for a new path be done</summary> + protected bool canSearchAgain = true; + + /// <summary> + /// When a new path was returned, the AI was moving along this ray. + /// Used to smoothly interpolate between the previous movement and the movement along the new path. + /// The speed is equal to movement direction. + /// </summary> + protected Vector3 previousMovementOrigin; + protected Vector3 previousMovementDirection; + + /// <summary> + /// Time since the path was replaced by a new path. + /// See: <see cref="interpolatePathSwitches"/> + /// </summary> + protected float pathSwitchInterpolationTime = 0; + + protected PathInterpolator.Cursor interpolator; + protected PathInterpolator interpolatorPath = new PathInterpolator(); + + + /// <summary> + /// Holds if the Start function has been run. + /// Used to test if coroutines should be started in OnEnable to prevent calculating paths + /// in the awake stage (or rather before start on frame 0). + /// </summary> + bool startHasRun = false; + + Vector3 previousPosition1, previousPosition2, simulatedPosition; + Quaternion simulatedRotation; + + /// <summary>Required for serialization backward compatibility</summary> + [UnityEngine.Serialization.FormerlySerializedAs("target")][SerializeField][HideInInspector] + Transform targetCompatibility; + + [SerializeField] + [HideInInspector] + [UnityEngine.Serialization.FormerlySerializedAs("repathRate")] + float repathRateCompatibility = float.NaN; + + [SerializeField] + [HideInInspector] + [UnityEngine.Serialization.FormerlySerializedAs("canSearch")] + bool canSearchCompability = false; + + protected AILerp () { + // Note that this needs to be set here in the constructor and not in e.g Awake + // because it is possible that other code runs and sets the destination property + // before the Awake method on this script runs. + destination = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + } + + /// <summary> + /// Initializes reference variables. + /// If you override this function you should in most cases call base.Awake () at the start of it. + /// </summary> + protected override void Awake () { + base.Awake(); + //This is a simple optimization, cache the transform component lookup + tr = transform; + + seeker = GetComponent<Seeker>(); + + // Tell the StartEndModifier to ask for our exact position when post processing the path This + // is important if we are using prediction and requesting a path from some point slightly ahead + // of us since then the start point in the path request may be far from our position when the + // path has been calculated. This is also good because if a long path is requested, it may take + // a few frames for it to be calculated so we could have moved some distance during that time + seeker.startEndModifier.adjustStartPoint = () => simulatedPosition; + } + + /// <summary> + /// Starts searching for paths. + /// If you override this function you should in most cases call base.Start () at the start of it. + /// See: <see cref="Init"/> + /// </summary> + protected virtual void Start () { + startHasRun = true; + Init(); + } + + /// <summary>Called when the component is enabled</summary> + protected virtual void OnEnable () { + onPathComplete = OnPathComplete; + Init(); + } + + void Init () { + if (startHasRun) { + // The Teleport call will make sure some variables are properly initialized (like #prevPosition1 and #prevPosition2) + Teleport(position, false); + autoRepath.Reset(); + if (shouldRecalculatePath) SearchPath(); + } + } + + public void OnDisable () { + ClearPath(); + } + + /// <summary>\copydocref{IAstarAI.GetRemainingPath(List<Vector3>,bool)}</summary> + public void GetRemainingPath (List<Vector3> buffer, out bool stale) { + buffer.Clear(); + if (!interpolator.valid) { + buffer.Add(position); + stale = true; + return; + } + + stale = false; + interpolator.GetRemainingPath(buffer); + // The agent is almost always at interpolation.position (which is buffer[0]) + // but sometimes - in particular when interpolating between two paths - the agent might at a slightly different position. + // So we replace the first point with the actual position of the agent. + buffer[0] = position; + } + + /// <summary>\copydocref{IAstarAI.GetRemainingPath(List<Vector3>,List<PathPartWithLinkInfo>,bool)}</summary> + public void GetRemainingPath (List<Vector3> buffer, List<PathPartWithLinkInfo> partsBuffer, out bool stale) { + GetRemainingPath(buffer, out stale); + // This movement script doesn't keep track of path parts, so we just add the whole path as a single part + if (partsBuffer != null) { + partsBuffer.Clear(); + partsBuffer.Add(new PathPartWithLinkInfo { startIndex = 0, endIndex = buffer.Count - 1 }); + } + } + + public void Teleport (Vector3 position, bool clearPath = true) { + if (clearPath) ClearPath(); + simulatedPosition = previousPosition1 = previousPosition2 = position; + if (updatePosition) tr.position = position; + reachedEndOfPath = false; + if (clearPath) SearchPath(); + } + + /// <summary>True if the path should be automatically recalculated as soon as possible</summary> + protected virtual bool shouldRecalculatePath { + get { + return canSearchAgain && autoRepath.ShouldRecalculatePath(position, 0.0f, destination, Time.time); + } + } + + /// <summary> + /// Requests a path to the target. + /// Deprecated: Use <see cref="SearchPath"/> instead. + /// </summary> + [System.Obsolete("Use SearchPath instead")] + public virtual void ForceSearchPath () { + SearchPath(); + } + + /// <summary>Requests a path to the target.</summary> + public virtual void SearchPath () { + if (float.IsPositiveInfinity(destination.x)) return; + if (onSearchPath != null) onSearchPath(); + + // This is where the path should start to search from + var currentPosition = GetFeetPosition(); + + // If we are following a path, start searching from the node we will + // reach next this can prevent odd turns right at the start of the path + /*if (interpolator.valid) { + var prevDist = interpolator.distance; + // Move to the end of the current segment + interpolator.MoveToSegment(interpolator.segmentIndex, 1); + currentPosition = interpolator.position; + // Move back to the original position + interpolator.distance = prevDist; + }*/ + + canSearchAgain = false; + + // Create a new path request + // The OnPathComplete method will later be called with the result + SetPath(ABPath.Construct(currentPosition, destination, null), false); + } + + /// <summary> + /// The end of the path has been reached. + /// If you want custom logic for when the AI has reached it's destination + /// add it here. + /// You can also create a new script which inherits from this one + /// and override the function in that script. + /// + /// Deprecated: Avoid overriding this method. Instead poll the <see cref="reachedDestination"/> or <see cref="reachedEndOfPath"/> properties. + /// </summary> + public virtual void OnTargetReached () { + } + + /// <summary> + /// Called when a requested path has finished calculation. + /// A path is first requested by <see cref="SearchPath"/>, it is then calculated, probably in the same or the next frame. + /// Finally it is returned to the seeker which forwards it to this function. + /// </summary> + protected virtual void OnPathComplete (Path _p) { + ABPath p = _p as ABPath; + + if (p == null) throw new System.Exception("This function only handles ABPaths, do not use special path types"); + + canSearchAgain = true; + + // Increase the reference count on the path. + // This is used for path pooling + p.Claim(this); + + // Path couldn't be calculated of some reason. + // More info in p.errorLog (debug string) + if (p.error) { + p.Release(this); + return; + } + + if (interpolatePathSwitches) { + ConfigurePathSwitchInterpolation(); + } + + + // Replace the old path + var oldPath = path; + + path = p; + reachedEndOfPath = false; + + // The RandomPath and MultiTargetPath do not have a well defined destination that could have been + // set before the paths were calculated. So we instead set the destination here so that some properties + // like #reachedDestination and #remainingDistance work correctly. + if (path is RandomPath rpath) { + destination = rpath.originalEndPoint; + } else if (path is MultiTargetPath mpath) { + destination = mpath.originalEndPoint; + } + + // Just for the rest of the code to work, if there + // is only one waypoint in the path add another one + if (path.vectorPath != null && path.vectorPath.Count == 1) { + path.vectorPath.Insert(0, GetFeetPosition()); + } + + // Reset some variables + ConfigureNewPath(); + + // Release the previous path + // This is used for path pooling. + // This is done after the interpolator has been configured in the ConfigureNewPath method + // as this method would otherwise invalidate the interpolator + // since the vectorPath list (which the interpolator uses) will be pooled. + if (oldPath != null) oldPath.Release(this); + + if (interpolator.remainingDistance < 0.0001f && !reachedEndOfPath) { + reachedEndOfPath = true; + OnTargetReached(); + } + } + + /// <summary> + /// Clears the current path of the agent. + /// + /// Usually invoked using <see cref="SetPath"/>(null) + /// + /// See: <see cref="SetPath"/> + /// See: <see cref="isStopped"/> + /// </summary> + protected virtual void ClearPath () { + // Abort any calculations in progress + if (seeker != null) seeker.CancelCurrentPathRequest(); + canSearchAgain = true; + reachedEndOfPath = false; + + // Release current path so that it can be pooled + if (path != null) path.Release(this); + path = null; + interpolatorPath.SetPath(null); + } + + /// <summary>\copydoc Pathfinding::IAstarAI::SetPath</summary> + public void SetPath (Path path, bool updateDestinationFromPath = true) { + if (updateDestinationFromPath && path is ABPath abPath && !(path is RandomPath)) { + this.destination = abPath.originalEndPoint; + } + + if (path == null) { + ClearPath(); + } else if (path.PipelineState == PathState.Created) { + // Path has not started calculation yet + canSearchAgain = false; + seeker.CancelCurrentPathRequest(); + seeker.StartPath(path, onPathComplete); + autoRepath.DidRecalculatePath(destination, Time.time); + } else if (path.PipelineState >= PathState.Returning) { + // Path has already been calculated + + // We might be calculating another path at the same time, and we don't want that path to override this one. So cancel it. + if (seeker.GetCurrentPath() != path) seeker.CancelCurrentPathRequest(); + + OnPathComplete(path); + } else { + // Path calculation has been started, but it is not yet complete. Cannot really handle this. + throw new System.ArgumentException("You must call the SetPath method with a path that either has been completely calculated or one whose path calculation has not been started at all. It looks like the path calculation for the path you tried to use has been started, but is not yet finished."); + } + } + + protected virtual void ConfigurePathSwitchInterpolation () { + bool reachedEndOfPreviousPath = interpolator.valid && interpolator.remainingDistance < 0.0001f; + + if (interpolator.valid && !reachedEndOfPreviousPath) { + previousMovementOrigin = interpolator.position; + previousMovementDirection = interpolator.tangent.normalized * interpolator.remainingDistance; + pathSwitchInterpolationTime = 0; + } else { + previousMovementOrigin = Vector3.zero; + previousMovementDirection = Vector3.zero; + pathSwitchInterpolationTime = float.PositiveInfinity; + } + } + + public virtual Vector3 GetFeetPosition () { + return position; + } + + /// <summary>Finds the closest point on the current path and configures the <see cref="interpolator"/></summary> + protected virtual void ConfigureNewPath () { + var hadValidPath = interpolator.valid; + var prevTangent = hadValidPath ? interpolator.tangent : Vector3.zero; + + interpolatorPath.SetPath(path.vectorPath); + interpolator = interpolatorPath.start; + interpolator.MoveToClosestPoint(GetFeetPosition()); + + if (interpolatePathSwitches && switchPathInterpolationSpeed > 0.01f && hadValidPath) { + var correctionFactor = Mathf.Max(-Vector3.Dot(prevTangent.normalized, interpolator.tangent.normalized), 0); + interpolator.distance -= speed*correctionFactor*(1f/switchPathInterpolationSpeed); + } + } + + protected virtual void Update () { + if (shouldRecalculatePath) SearchPath(); + if (canMove) { + Vector3 nextPosition; + Quaternion nextRotation; + MovementUpdate(Time.deltaTime, out nextPosition, out nextRotation); + FinalizeMovement(nextPosition, nextRotation); + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::MovementUpdate</summary> + public void MovementUpdate (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation) { + if (updatePosition) simulatedPosition = tr.position; + if (updateRotation) simulatedRotation = tr.rotation; + + Vector3 direction; + + nextPosition = CalculateNextPosition(out direction, isStopped ? 0f : deltaTime); + + if (enableRotation) nextRotation = SimulateRotationTowards(direction, deltaTime); + else nextRotation = simulatedRotation; + } + + /// <summary>\copydoc Pathfinding::IAstarAI::FinalizeMovement</summary> + public void FinalizeMovement (Vector3 nextPosition, Quaternion nextRotation) { + previousPosition2 = previousPosition1; + previousPosition1 = simulatedPosition = nextPosition; + simulatedRotation = nextRotation; + if (updatePosition) tr.position = nextPosition; + if (updateRotation) tr.rotation = nextRotation; + } + + Quaternion SimulateRotationTowards (Vector3 direction, float deltaTime) { + // Rotate unless we are really close to the target + if (direction != Vector3.zero) { + Quaternion targetRotation = Quaternion.LookRotation(direction, orientation == OrientationMode.YAxisForward ? Vector3.back : Vector3.up); + // This causes the character to only rotate around the Z axis + if (orientation == OrientationMode.YAxisForward) targetRotation *= Quaternion.Euler(90, 0, 0); + return Quaternion.Slerp(simulatedRotation, targetRotation, deltaTime * rotationSpeed); + } + return simulatedRotation; + } + + /// <summary>Calculate the AI's next position (one frame in the future).</summary> + /// <param name="direction">The tangent of the segment the AI is currently traversing. Not normalized.</param> + /// <param name="deltaTime">The time to simulate into the future.</param> + protected virtual Vector3 CalculateNextPosition (out Vector3 direction, float deltaTime) { + if (!interpolator.valid) { + direction = Vector3.zero; + return simulatedPosition; + } + + interpolator.distance += deltaTime * speed; + + if (interpolator.remainingDistance < 0.0001f && !reachedEndOfPath) { + reachedEndOfPath = true; + OnTargetReached(); + } + + direction = interpolator.tangent; + pathSwitchInterpolationTime += deltaTime; + var alpha = switchPathInterpolationSpeed * pathSwitchInterpolationTime; + + if (interpolatePathSwitches && alpha < 1f) { + // Find the approximate position we would be at if we + // would have continued to follow the previous path + Vector3 positionAlongPreviousPath = previousMovementOrigin + Vector3.ClampMagnitude(previousMovementDirection, speed * pathSwitchInterpolationTime); + + // Interpolate between the position on the current path and the position + // we would have had if we would have continued along the previous path. + return Vector3.Lerp(positionAlongPreviousPath, interpolator.position, alpha); + } else { + return interpolator.position; + } + } + + protected override void OnUpgradeSerializedData (ref Serialization.Migrations migrations, bool unityThread) { + if (migrations.TryMigrateFromLegacyFormat(out var legacyVersion)) { + if (legacyVersion <= 3) { + repathRate = repathRateCompatibility; + canSearch = canSearchCompability; + } + } + #pragma warning disable 618 + if (unityThread && targetCompatibility != null) target = targetCompatibility; + #pragma warning restore 618 + } + + public override void DrawGizmos () { + tr = transform; + autoRepath.DrawGizmos(Pathfinding.Drawing.Draw.editor, this.position, 0.0f, new NativeMovementPlane(orientation == OrientationMode.YAxisForward ? Quaternion.Euler(-90, 0, 0) : Quaternion.identity)); + } + } +} diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AILerp.cs.meta b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AILerp.cs.meta new file mode 100644 index 0000000..f22788b --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AILerp.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 847a14d4dc9cc43679ab34fc78e0182f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: f2e81a0445323b64f973d2f5b5c56e15, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AIPath.cs b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AIPath.cs new file mode 100644 index 0000000..49b9648 --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AIPath.cs @@ -0,0 +1,542 @@ +using UnityEngine; +using System.Collections.Generic; + +namespace Pathfinding { + using Pathfinding.Util; + using Pathfinding.Drawing; + + /// <summary> + /// AI for following paths. + /// + /// This AI is the default movement script which comes with the A* Pathfinding Project. + /// It is in no way required by the rest of the system, so feel free to write your own. But I hope this script will make it easier + /// to set up movement for the characters in your game. + /// This script works well for many types of units, but if you need the highest performance (for example if you are moving hundreds of characters) you + /// may want to customize this script or write a custom movement script to be able to optimize it specifically for your game. + /// + /// This script will try to move to a given <see cref="destination"/>. At <see cref="repathRate regular"/>, the path to the destination will be recalculated. + /// If you want to make the AI to follow a particular object you can attach the <see cref="Pathfinding.AIDestinationSetter"/> component. + /// Take a look at the getstarted (view in online documentation for working links) tutorial for more instructions on how to configure this script. + /// + /// Here is a video of this script being used move an agent around (technically it uses the <see cref="Pathfinding.Examples.MineBotAI"/> script that inherits from this one but adds a bit of animation support for the example scenes): + /// [Open online documentation to see videos] + /// + /// \section variables Quick overview of the variables + /// In the inspector in Unity, you will see a bunch of variables. You can view detailed information further down, but here's a quick overview. + /// + /// The <see cref="repathRate"/> determines how often it will search for new paths, if you have fast moving targets, you might want to set it to a lower value. + /// The <see cref="destination"/> field is where the AI will try to move, it can be a point on the ground where the player has clicked in an RTS for example. + /// Or it can be the player object in a zombie game. + /// The <see cref="maxSpeed"/> is self-explanatory, as is <see cref="rotationSpeed"/>. however <see cref="slowdownDistance"/> might require some explanation: + /// It is the approximate distance from the target where the AI will start to slow down. Setting it to a large value will make the AI slow down very gradually. + /// <see cref="pickNextWaypointDist"/> determines the distance to the point the AI will move to (see image below). + /// + /// Below is an image illustrating several variables that are exposed by this class (<see cref="pickNextWaypointDist"/>, <see cref="steeringTarget"/>, <see cref="desiredVelocity)"/> + /// [Open online documentation to see images] + /// + /// This script has many movement fallbacks. + /// If it finds an RVOController attached to the same GameObject as this component, it will use that. If it finds a character controller it will also use that. + /// If it finds a rigidbody it will use that. Lastly it will fall back to simply modifying Transform.position which is guaranteed to always work and is also the most performant option. + /// + /// \section how-aipath-works How it works + /// In this section I'm going to go over how this script is structured and how information flows. + /// This is useful if you want to make changes to this script or if you just want to understand how it works a bit more deeply. + /// However you do not need to read this section if you are just going to use the script as-is. + /// + /// This script inherits from the <see cref="AIBase"/> class. The movement happens either in Unity's standard Update or FixedUpdate method. + /// They are both defined in the AIBase class. Which one is actually used depends on if a rigidbody is used for movement or not. + /// Rigidbody movement has to be done inside the FixedUpdate method while otherwise it is better to do it in Update. + /// + /// From there a call is made to the <see cref="MovementUpdate"/> method (which in turn calls <see cref="MovementUpdateInternal)"/>. + /// This method contains the main bulk of the code and calculates how the AI *wants* to move. However it doesn't do any movement itself. + /// Instead it returns the position and rotation it wants the AI to move to have at the end of the frame. + /// The Update (or FixedUpdate) method then passes these values to the <see cref="FinalizeMovement"/> method which is responsible for actually moving the character. + /// That method also handles things like making sure the AI doesn't fall through the ground using raycasting. + /// + /// The AI recalculates its path regularly. This happens in the Update method which checks <see cref="shouldRecalculatePath"/>, and if that returns true it will call <see cref="SearchPath"/>. + /// The <see cref="SearchPath"/> method will prepare a path request and send it to the <see cref="Seeker"/> component, which should be attached to the same GameObject as this script. + /// </summary> + [AddComponentMenu("Pathfinding/AI/AIPath (2D,3D)")] + [UniqueComponent(tag = "ai")] + public partial class AIPath : AIBase, IAstarAI { + /// <summary> + /// How quickly the agent accelerates. + /// Positive values represent an acceleration in world units per second squared. + /// Negative values are interpreted as an inverse time of how long it should take for the agent to reach its max speed. + /// For example if it should take roughly 0.4 seconds for the agent to reach its max speed then this field should be set to -1/0.4 = -2.5. + /// For a negative value the final acceleration will be: -acceleration*maxSpeed. + /// This behaviour exists mostly for compatibility reasons. + /// + /// In the Unity inspector there are two modes: Default and Custom. In the Default mode this field is set to -2.5 which means that it takes about 0.4 seconds for the agent to reach its top speed. + /// In the Custom mode you can set the acceleration to any positive value. + /// </summary> + public float maxAcceleration = -2.5f; + + /// <summary> + /// Rotation speed in degrees per second. + /// Rotation is calculated using Quaternion.RotateTowards. This variable represents the rotation speed in degrees per second. + /// The higher it is, the faster the character will be able to rotate. + /// </summary> + [UnityEngine.Serialization.FormerlySerializedAs("turningSpeed")] + public float rotationSpeed = 360; + + /// <summary>Distance from the end of the path where the AI will start to slow down</summary> + public float slowdownDistance = 0.6F; + + /// <summary> + /// How far the AI looks ahead along the path to determine the point it moves to. + /// In world units. + /// If you enable the <see cref="alwaysDrawGizmos"/> toggle this value will be visualized in the scene view as a blue circle around the agent. + /// [Open online documentation to see images] + /// + /// Here are a few example videos showing some typical outcomes with good values as well as how it looks when this value is too low and too high. + /// <table> + /// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-danger">Too low</span><br/></verbatim>\endxmlonly A too low value and a too low acceleration will result in the agent overshooting a lot and not managing to follow the path well.</td></tr> + /// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-warning">Ok</span><br/></verbatim>\endxmlonly A low value but a high acceleration works decently to make the AI follow the path more closely. Note that the <see cref="Pathfinding.AILerp"/> component is better suited if you want the agent to follow the path without any deviations.</td></tr> + /// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-success">Ok</span><br/></verbatim>\endxmlonly A reasonable value in this example.</td></tr> + /// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-success">Ok</span><br/></verbatim>\endxmlonly A reasonable value in this example, but the path is followed slightly more loosely than in the previous video.</td></tr> + /// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-danger">Too high</span><br/></verbatim>\endxmlonly A too high value will make the agent follow the path too loosely and may cause it to try to move through obstacles.</td></tr> + /// </table> + /// </summary> + public float pickNextWaypointDist = 2; + + /// <summary>Draws detailed gizmos constantly in the scene view instead of only when the agent is selected and settings are being modified</summary> + public bool alwaysDrawGizmos; + + /// <summary> + /// Slow down when not facing the target direction. + /// Incurs at a small performance overhead. + /// + /// This setting only has an effect if <see cref="enableRotation"/> is enabled. + /// </summary> + public bool slowWhenNotFacingTarget = true; + + /// <summary> + /// Prevent the velocity from being too far away from the forward direction of the character. + /// If the character is ordered to move in the opposite direction from where it is facing + /// then enabling this will cause it to make a small loop instead of turning on the spot. + /// + /// This setting only has an effect if <see cref="slowWhenNotFacingTarget"/> is enabled. + /// </summary> + public bool preventMovingBackwards = false; + + /// <summary> + /// Ensure that the character is always on the traversable surface of the navmesh. + /// When this option is enabled a <see cref="AstarPath.GetNearest"/> query will be done every frame to find the closest node that the agent can walk on + /// and if the agent is not inside that node, then the agent will be moved to it. + /// + /// This is especially useful together with local avoidance in order to avoid agents pushing each other into walls. + /// See: local-avoidance (view in online documentation for working links) for more info about this. + /// + /// This option also integrates with local avoidance so that if the agent is say forced into a wall by other agents the local avoidance + /// system will be informed about that wall and can take that into account. + /// + /// Enabling this has some performance impact depending on the graph type (pretty fast for grid graphs, slightly slower for navmesh/recast graphs). + /// If you are using a navmesh/recast graph you may want to switch to the <see cref="Pathfinding.RichAI"/> movement script which is specifically written for navmesh/recast graphs and + /// does this kind of clamping out of the box. In many cases it can also follow the path more smoothly around sharp bends in the path. + /// + /// It is not recommended that you use this option together with the funnel modifier on grid graphs because the funnel modifier will make the path + /// go very close to the border of the graph and this script has a tendency to try to cut corners a bit. This may cause it to try to go slightly outside the + /// traversable surface near corners and that will look bad if this option is enabled. + /// + /// Warning: This option makes no sense to use on point graphs because point graphs do not have a surface. + /// Enabling this option when using a point graph will lead to the agent being snapped to the closest node every frame which is likely not what you want. + /// + /// Below you can see an image where several agents using local avoidance were ordered to go to the same point in a corner. + /// When not constraining the agents to the graph they are easily pushed inside obstacles. + /// [Open online documentation to see images] + /// </summary> + public bool constrainInsideGraph = false; + + /// <summary>Current path which is followed</summary> + protected Path path; + + /// <summary>Represents the current steering target for the agent</summary> + protected PathInterpolator.Cursor interpolator; + /// <summary>Helper which calculates points along the current path</summary> + protected PathInterpolator interpolatorPath = new PathInterpolator(); + + #region IAstarAI implementation + + /// <summary>\copydoc Pathfinding::IAstarAI::Teleport</summary> + public override void Teleport (Vector3 newPosition, bool clearPath = true) { + reachedEndOfPath = false; + base.Teleport(newPosition, clearPath); + } + + /// <summary>\copydoc Pathfinding::IAstarAI::remainingDistance</summary> + public float remainingDistance => interpolator.valid ? interpolator.remainingDistance + movementPlane.ToPlane(interpolator.position - position).magnitude : float.PositiveInfinity; + + /// <summary>\copydoc Pathfinding::IAstarAI::reachedDestination</summary> + public override bool reachedDestination { + get { + if (!reachedEndOfPath) return false; + if (!interpolator.valid || remainingDistance + movementPlane.ToPlane(destination - interpolator.endPoint).magnitude > endReachedDistance) return false; + + // Don't do height checks in 2D mode + if (orientation != OrientationMode.YAxisForward) { + // Check if the destination is above the head of the character or far below the feet of it + movementPlane.ToPlane(destination - position, out float yDifference); + var h = tr.localScale.y * height; + if (yDifference > h || yDifference < -h*0.5) return false; + } + + return true; + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::reachedEndOfPath</summary> + public bool reachedEndOfPath { get; protected set; } + + /// <summary>\copydoc Pathfinding::IAstarAI::hasPath</summary> + public bool hasPath => interpolator.valid; + + /// <summary>\copydoc Pathfinding::IAstarAI::pathPending</summary> + public bool pathPending => waitingForPathCalculation; + + /// <summary>\copydoc Pathfinding::IAstarAI::steeringTarget</summary> + public Vector3 steeringTarget => interpolator.valid ? interpolator.position : position; + + /// <summary>\copydoc Pathfinding::IAstarAI::endOfPath</summary> + public override Vector3 endOfPath { + get { + if (interpolator.valid) return interpolator.endPoint; + if (float.IsFinite(destination.x)) return destination; + return position; + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::radius</summary> + float IAstarAI.radius { get => radius; set => radius = value; } + + /// <summary>\copydoc Pathfinding::IAstarAI::height</summary> + float IAstarAI.height { get => height; set => height = value; } + + /// <summary>\copydoc Pathfinding::IAstarAI::maxSpeed</summary> + float IAstarAI.maxSpeed { get => maxSpeed; set => maxSpeed = value; } + + /// <summary>\copydoc Pathfinding::IAstarAI::canSearch</summary> + bool IAstarAI.canSearch { get => canSearch; set => canSearch = value; } + + /// <summary>\copydoc Pathfinding::IAstarAI::canMove</summary> + bool IAstarAI.canMove { get => canMove; set => canMove = value; } + + /// <summary>\copydoc Pathfinding::IAstarAI::movementPlane</summary> + NativeMovementPlane IAstarAI.movementPlane => new NativeMovementPlane(movementPlane); + + #endregion + + /// <summary>\copydocref{IAstarAI.GetRemainingPath(List<Vector3>,bool)}</summary> + public void GetRemainingPath (List<Vector3> buffer, out bool stale) { + buffer.Clear(); + buffer.Add(position); + if (!interpolator.valid) { + stale = true; + return; + } + + stale = false; + interpolator.GetRemainingPath(buffer); + } + + /// <summary>\copydocref{IAstarAI.GetRemainingPath(List<Vector3>,List<PathPartWithLinkInfo>,bool)}</summary> + public void GetRemainingPath (List<Vector3> buffer, List<PathPartWithLinkInfo> partsBuffer, out bool stale) { + GetRemainingPath(buffer, out stale); + // This movement script doesn't keep track of path parts, so we just add the whole path as a single part + if (partsBuffer != null) { + partsBuffer.Clear(); + partsBuffer.Add(new PathPartWithLinkInfo { startIndex = 0, endIndex = buffer.Count - 1 }); + } + } + + protected override void OnDisable () { + // This will, among other things call ClearPath + base.OnDisable(); + rotationFilterState = Vector2.zero; + rotationFilterState2 = Vector2.zero; + } + + /// <summary> + /// The end of the path has been reached. + /// If you want custom logic for when the AI has reached it's destination add it here. You can + /// also create a new script which inherits from this one and override the function in that script. + /// + /// This method will be called again if a new path is calculated as the destination may have changed. + /// So when the agent is close to the destination this method will typically be called every <see cref="repathRate"/> seconds. + /// + /// Deprecated: Avoid overriding this method. Instead poll the <see cref="reachedDestination"/> or <see cref="reachedEndOfPath"/> properties. + /// </summary> + public virtual void OnTargetReached () { + } + + protected virtual void UpdateMovementPlane () { + if (path.path == null || path.path.Count == 0) return; + var graph = AstarData.GetGraph(path.path[0]) as ITransformedGraph; + IMovementPlane graphTransform = graph != null ? graph.transform : (orientation == OrientationMode.YAxisForward ? new GraphTransform(Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(-90, 270, 90), Vector3.one)) : GraphTransform.identityTransform); + + movementPlane = graphTransform.ToSimpleMovementPlane(); + } + + /// <summary> + /// Called when a requested path has been calculated. + /// A path is first requested by <see cref="SearchPath"/>, it is then calculated, probably in the same or the next frame. + /// Finally it is returned to the seeker which forwards it to this function. + /// </summary> + protected override void OnPathComplete (Path newPath) { + ABPath p = newPath as ABPath; + + if (p == null) throw new System.Exception("This function only handles ABPaths, do not use special path types"); + + waitingForPathCalculation = false; + + // Increase the reference count on the new path. + // This is used for object pooling to reduce allocations. + p.Claim(this); + + // Path couldn't be calculated of some reason. + // More info in p.errorLog (debug string) + if (p.error) { + p.Release(this); + SetPath(null); + return; + } + + // Release the previous path. + if (path != null) path.Release(this); + + // Replace the old path + path = p; + + // The RandomPath and MultiTargetPath do not have a well defined destination that could have been + // set before the paths were calculated. So we instead set the destination here so that some properties + // like #reachedDestination and #remainingDistance work correctly. + if (!p.endPointKnownBeforeCalculation) { + destination = p.originalEndPoint; + } + + // Make sure the path contains at least 2 points + if (path.vectorPath.Count == 1) path.vectorPath.Add(path.vectorPath[0]); + interpolatorPath.SetPath(path.vectorPath); + interpolator = interpolatorPath.start; + + UpdateMovementPlane(); + + // Reset some variables + reachedEndOfPath = false; + + // Simulate movement from the point where the path was requested + // to where we are right now. This reduces the risk that the agent + // gets confused because the first point in the path is far away + // from the current position (possibly behind it which could cause + // the agent to turn around, and that looks pretty bad). + interpolator.MoveToLocallyClosestPoint((GetFeetPosition() + p.originalStartPoint) * 0.5f); + interpolator.MoveToLocallyClosestPoint(GetFeetPosition()); + + // Update which point we are moving towards. + // Note that we need to do this here because otherwise the remainingDistance field might be incorrect for 1 frame. + // (due to interpolator.remainingDistance being incorrect). + interpolator.MoveToCircleIntersection2D(position, pickNextWaypointDist, movementPlane); + + var distanceToEnd = remainingDistance; + + if (distanceToEnd <= endReachedDistance) { + reachedEndOfPath = true; + OnTargetReached(); + } + } + + protected override void ClearPath () { + CancelCurrentPathRequest(); + // Release current path so that it can be pooled + if (path != null) path.Release(this); + path = null; + interpolatorPath.SetPath(null); + reachedEndOfPath = false; + } + + /// <summary>Called during either Update or FixedUpdate depending on if rigidbodies are used for movement or not</summary> + protected override void MovementUpdateInternal (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation) { + float currentAcceleration = maxAcceleration; + + // If negative, calculate the acceleration from the max speed + if (currentAcceleration < 0) currentAcceleration *= -maxSpeed; + + if (updatePosition) { + // Get our current position. We read from transform.position as few times as possible as it is relatively slow + // (at least compared to a local variable) + simulatedPosition = tr.position; + } + if (updateRotation) simulatedRotation = tr.rotation; + + var currentPosition = simulatedPosition; + + // Normalized direction of where the agent is looking + var forwards = movementPlane.ToPlane(simulatedRotation * (orientation == OrientationMode.YAxisForward ? Vector3.up : Vector3.forward)); + + // Check if we have a valid path to follow and some other script has not stopped the character + bool stopped = isStopped || (reachedDestination && whenCloseToDestination == CloseToDestinationMode.Stop); + + if (rvoController != null) rvoDensityBehavior.Update(rvoController.enabled, reachedDestination, ref stopped, ref rvoController.priorityMultiplier, ref rvoController.flowFollowingStrength, currentPosition); + + float speedLimitFactor = 0; + float distanceToEnd; + // Check if we have a path to follow + if (interpolator.valid) { + // Update which point we are moving towards + interpolator.MoveToCircleIntersection2D(currentPosition, pickNextWaypointDist, movementPlane); + var dir = movementPlane.ToPlane(steeringTarget - currentPosition); + + // Calculate the distance to the end of the path + distanceToEnd = dir.magnitude + Mathf.Max(0, interpolator.remainingDistance); + + // Check if we have reached the target + var prevTargetReached = reachedEndOfPath; + reachedEndOfPath = distanceToEnd <= endReachedDistance; + if (!prevTargetReached && reachedEndOfPath) OnTargetReached(); + + if (!stopped) { + // How fast to move depending on the distance to the destination. + // Move slower as the character gets closer to the destination. + // This is always a value between 0 and 1. + speedLimitFactor = distanceToEnd < slowdownDistance? Mathf.Sqrt(distanceToEnd / slowdownDistance) : 1; + velocity2D += MovementUtilities.CalculateAccelerationToReachPoint(dir, dir.normalized*maxSpeed, velocity2D, currentAcceleration, rotationSpeed, maxSpeed, forwards) * deltaTime; + } + } else { + reachedEndOfPath = false; + distanceToEnd = float.PositiveInfinity; + } + + if (!interpolator.valid || stopped) { + // Slow down as quickly as possible + velocity2D -= Vector2.ClampMagnitude(velocity2D, currentAcceleration * deltaTime); + // We are already slowing down as quickly as possible. Avoid limiting the speed in other ways. + speedLimitFactor = 1; + } + + velocity2D = MovementUtilities.ClampVelocity(velocity2D, maxSpeed, speedLimitFactor, slowWhenNotFacingTarget && enableRotation, preventMovingBackwards, forwards); + + ApplyGravity(deltaTime); + bool avoidingOtherAgents = false; + + if (rvoController != null && rvoController.enabled) { + // Send a message to the RVOController that we want to move + // with this velocity. In the next simulation step, this + // velocity will be processed and it will be fed back to the + // rvo controller and finally it will be used by this script + // when calling the CalculateMovementDelta method below + + // Make sure that we don't move further than to the end point + // of the path. If the RVO simulation FPS is low and we did + // not do this, the agent might overshoot the target a lot. + var rvoTarget = currentPosition + movementPlane.ToWorld(Vector2.ClampMagnitude(velocity2D, distanceToEnd), 0f); + rvoController.SetTarget(rvoTarget, velocity2D.magnitude, maxSpeed, endOfPath); + avoidingOtherAgents = rvoController.AvoidingAnyAgents; + } + + // Set how much the agent wants to move during this frame + var delta2D = lastDeltaPosition = CalculateDeltaToMoveThisFrame(currentPosition, distanceToEnd, deltaTime); + nextPosition = currentPosition + movementPlane.ToWorld(delta2D, verticalVelocity * deltaTime); + CalculateNextRotation(speedLimitFactor, avoidingOtherAgents, out nextRotation); + } + + Vector2 rotationFilterState, rotationFilterState2; + + protected virtual void CalculateNextRotation (float slowdown, bool avoidingOtherAgents, out Quaternion nextRotation) { + if (lastDeltaTime > 0.00001f && enableRotation) { + // Rotate towards the direction we are moving in + // Filter out noise in the movement direction + // This is especially important when the agent is almost standing still and when using local avoidance + float noiseThreshold = radius * tr.localScale.x * 0.2f; + float rotationSpeedFactor = MovementUtilities.FilterRotationDirection(ref rotationFilterState, ref rotationFilterState2, lastDeltaPosition, noiseThreshold, lastDeltaTime, avoidingOtherAgents); + nextRotation = SimulateRotationTowards(rotationFilterState, rotationSpeed * lastDeltaTime * rotationSpeedFactor, rotationSpeed * lastDeltaTime); + } else { + // TODO: simulatedRotation + nextRotation = rotation; + } + } + + static NNConstraint cachedNNConstraint = NNConstraint.Walkable; + protected override Vector3 ClampToNavmesh (Vector3 position, out bool positionChanged) { + if (constrainInsideGraph) { + cachedNNConstraint.tags = seeker.traversableTags; + cachedNNConstraint.graphMask = seeker.graphMask; + cachedNNConstraint.distanceMetric = DistanceMetric.ClosestAsSeenFromAboveSoft(); + // Note: We don't want to set nn.constrainDistance = false (i.e. allow finding nodes arbitrarily far away), because that can lead to harsh + // performance cliffs if agents for example fall through the ground or get thrown off the map, or something like that (it's bound to happen in some games). + var nearestOnNavmesh = AstarPath.active.GetNearest(position, cachedNNConstraint); + + if (nearestOnNavmesh.node == null) { + // Found no valid node to constrain to. This can happen if there are no valid nodes close enough to the agent. + positionChanged = false; + return position; + } + + var clampedPosition = nearestOnNavmesh.position; + + if (rvoController != null && rvoController.enabled) { + // Inform the RVO system about the edges of the navmesh which will allow + // it to better keep inside the navmesh in the first place. + rvoController.SetObstacleQuery(nearestOnNavmesh.node); + } + + // We cannot simply check for equality because some precision may be lost + // if any coordinate transformations are used. + var difference = movementPlane.ToPlane(clampedPosition - position); + float sqrDifference = difference.sqrMagnitude; + if (sqrDifference > 0.001f*0.001f) { + // The agent was outside the navmesh. Remove that component of the velocity + // so that the velocity only goes along the direction of the wall, not into it + velocity2D -= difference * Vector2.Dot(difference, velocity2D) / sqrDifference; + + positionChanged = true; + // Return the new position, but ignore any changes in the y coordinate from the ClampToNavmesh method as the y coordinates in the navmesh are rarely very accurate + return position + movementPlane.ToWorld(difference); + } + } + + positionChanged = false; + return position; + } + +#if UNITY_EDITOR + [System.NonSerialized] + int gizmoHash = 0; + + [System.NonSerialized] + float lastChangedTime = float.NegativeInfinity; + + protected static readonly Color GizmoColor = new Color(46.0f/255, 104.0f/255, 201.0f/255); + + public override void DrawGizmos () { + base.DrawGizmos(); + + // If alwaysDrawGizmos is false, gizmos are only visible for a short while after the user changes any settings on this component + var newGizmoHash = pickNextWaypointDist.GetHashCode() ^ slowdownDistance.GetHashCode() ^ endReachedDistance.GetHashCode(); + + if (newGizmoHash != gizmoHash && gizmoHash != 0) lastChangedTime = Time.realtimeSinceStartup; + gizmoHash = newGizmoHash; + float alpha = alwaysDrawGizmos ? 1 : Mathf.SmoothStep(1, 0, (Time.realtimeSinceStartup - lastChangedTime - 5f)/0.5f) * (GizmoContext.selectionSize == 1 ? 1 : 0); + + if (alpha > 0) { + // Make sure the scene view is repainted while the gizmos are visible + if (!alwaysDrawGizmos) UnityEditor.SceneView.RepaintAll(); + Draw.Line(position, steeringTarget, GizmoColor * new Color(1, 1, 1, alpha)); + using (Draw.WithMatrix(Matrix4x4.TRS(position, transform.rotation * (orientation == OrientationMode.YAxisForward ? Quaternion.Euler(-90, 0, 0) : Quaternion.identity), Vector3.one))) { + Draw.xz.Circle(Vector3.zero, pickNextWaypointDist, GizmoColor * new Color(1, 1, 1, alpha)); + Draw.xz.Circle(Vector3.zero, slowdownDistance, Color.Lerp(GizmoColor, Color.red, 0.5f) * new Color(1, 1, 1, alpha)); + Draw.xz.Circle(Vector3.zero, endReachedDistance, Color.Lerp(GizmoColor, Color.red, 0.8f) * new Color(1, 1, 1, alpha)); + } + } + } +#endif + + protected override void OnUpgradeSerializedData (ref Serialization.Migrations migrations, bool unityThread) { + if (migrations.IsLegacyFormat) { + // Approximately convert from a damping value to a degrees per second value. + if (migrations.LegacyVersion < 1) rotationSpeed *= 90; + // The base call will migrate the legacy format further + } + base.OnUpgradeSerializedData(ref migrations, unityThread); + } + } +} diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AIPath.cs.meta b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AIPath.cs.meta new file mode 100644 index 0000000..435260d --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/AIPath.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f6eb1402c17e84a9282a7f0f62eb584f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: f2e81a0445323b64f973d2f5b5c56e15, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/FollowerEntity.cs b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/FollowerEntity.cs new file mode 100644 index 0000000..a262873 --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/FollowerEntity.cs @@ -0,0 +1,1826 @@ +#pragma warning disable CS0282 // "There is no defined ordering between fields in multiple declarations of partial struct" +#if MODULE_ENTITIES +using UnityEngine; +using Unity.Mathematics; +using System.Collections.Generic; +using Unity.Collections; +using UnityEngine.Profiling; +using Unity.Entities; +using Unity.Transforms; + +namespace Pathfinding { + using Pathfinding.Drawing; + using Pathfinding.Util; + using Palette = Pathfinding.Drawing.Palette.Colorbrewer.Set1; + using System; + using Pathfinding.PID; + using Pathfinding.ECS.RVO; + using Pathfinding.ECS; + using UnityEngine.Assertions; + + /// <summary> + /// Movement script that uses ECS. + /// + /// Warning: This script is still in beta and may change in the future. It aims to be much more robust than AIPath/RichAI, but there may still be rough edges. + /// + /// This script is a replacement for the <see cref="AIPath"/> and <see cref="RichAI"/> scripts. + /// + /// This script is a movement script. It takes care of moving an agent along a path, updating the path, and so on. + /// + /// The intended way to use this script is to use these two components: + /// - <see cref="FollowerEntity"/> + /// - <see cref="AIDestinationSetter"/> (optional, you can instead set the <see cref="destination"/> property manually) + /// + /// Of note is that this component shouldn't be used with a <see cref="Seeker"/> component. + /// It instead has its own settings for pathfinding, which are stored in the <see cref="pathfindingSettings"/> field. + /// + /// <b>Features</b> + /// + /// - Uses Unity's ECS (Entity Component System) to move the agent. This means it is highly-performant and is able to utilize multiple threads. + /// - Supports local avoidance (see local-avoidance) (view in online documentation for working links). + /// - Supports movement in both 2D and 3D games. + /// - Supports movement on spherical on non-planar worlds (see spherical) (view in online documentation for working links). + /// - Supports movement on grid graphs as well as navmesh/recast graphs. + /// - Does <b>not</b> support movement on point graphs at the moment. This may be added in a future update. + /// - Supports time-scales greater than 1. The agent will automatically run multiple simulation steps per frame if the time-scale is greater than 1, to ensure stability. + /// - Supports off-mesh links. Subscribe to the <see cref="onTraverseOffMeshLink"/> event to handle this. + /// - Knows which node it is traversing at all times (see <see cref="currentNode)"/>. + /// - Automatically stops when trying to reach a crowded destination when using local avoidance. + /// - Clamps the agent to the navmesh at all times. + /// - Follows paths very smoothly. + /// - Can keep a desired distance to walls. + /// - Can approach its destination with a desired facing direction. + /// + /// <b>%ECS</b> + /// + /// This script uses Unity's ECS (Entity Component System) to move the agent. This means it is highly-performant and is able to utilize multiple threads. + /// Internally, an entity is created for the agent with the following components: + /// + /// - LocalTransform + /// - <see cref="MovementState"/> + /// - <see cref="MovementSettings"/> + /// - <see cref="MovementControl"/> + /// - <see cref="ManagedState"/> + /// - <see cref="SearchState"/> + /// - <see cref="MovementStatistics"/> + /// - <see cref="AgentCylinderShape"/> + /// - <see cref="ResolvedMovement"/> + /// - <see cref="GravityState"/> + /// - <see cref="DestinationPoint"/> + /// - <see cref="AgentMovementPlane"/> + /// - <see cref="SimulateMovement"/> - tag component (if <see cref="canMove"/> is enabled) + /// - <see cref="SimulateMovementRepair"/> - tag component + /// - <see cref="SimulateMovementControl"/> - tag component + /// - <see cref="SimulateMovementFinalize"/> - tag component + /// - <see cref="SyncPositionWithTransform"/> - tag component (if <see cref="updatePosition"/> is enabled) + /// - <see cref="SyncRotationWithTransform"/> - tag component (if <see cref="updateRotation"/> is enabled) + /// - <see cref="OrientationYAxisForward"/> - tag component (if <see cref="orientation"/> is <see cref="OrientationMode"/>.YAxisForward) + /// - <see cref="ECS.RVO.RVOAgent"/> (if local avoidance is enabled) + /// + /// Then this script barely does anything by itself. It is a thin wrapper around the ECS components. + /// Instead, actual movement calculations are carried out by the following systems: + /// + /// - <see cref="SyncTransformsToEntitiesSystem"/> - Updates the entity's transform from the GameObject. + /// - <see cref="MovementPlaneFromGraphSystem"/> - Updates the agent's movement plane. + /// - <see cref="SyncDestinationTransformSystem"/> - Updates the destination point if the destination transform moves. + /// - <see cref="FollowerControlSystem"/> - Calculates how the agent wants to move. + /// - <see cref="RVOSystem"/> - Local avoidance calculations. + /// - <see cref="FallbackResolveMovementSystem"/> - NOOP system for if local avoidance is disabled. + /// - <see cref="AIMoveSystem"/> - Performs the actual movement. + /// + /// In fact, as long as you create the appropriate ECS components, you do not even need this script. You can use the systems directly. + /// + /// This is <b>not</b> a baked component. That is, this script will continue to work even in standalone games. It is designed to be easily used + /// without having to care too much about the underlying ECS implementation. + /// + /// <b>Differences compared to AIPath and RichAI</b> + /// + /// This movement script has been written to remedy several inconsistency issues with other movement scrips, to provide very smooth movement, + /// and "just work" for most games. + /// + /// For example, it goes to great lengths to ensure + /// that the <see cref="reachedDestination"/> and <see cref="reachedEndOfPath"/> properties are as accurate as possible at all times, even before it has had time to recalculate its path to account for a new <see cref="destination"/>. + /// It does this by locally repairing the path (if possible) immediately when the destination changes instead of waiting for a path recalculation. + /// This also has a bonus effect that the agent can often work just fine with moving targets, even if it almost never recalculates its path (though the repaired path may not always be optimal), + /// and it leads to very responsive movement. + /// + /// In contrast to other movement scripts, this movement script does not use path modifiers at all. + /// Instead, this script contains its own internal <see cref="FunnelModifier"/> which it uses to simplify the path before it follows it. + /// In also doesn't use a separate <see cref="RVOController"/> component for local avoidance, but instead it stores local avoidance settings in <see cref="rvoSettings"/>. + /// + /// <b>Best practices for good performance</b> + /// + /// Using ECS components has some downsides. Accessing properties on this script is significantly slower compared to accessing properties on other movement scripts. + /// This is because on each property access, the script has to make sure no jobs are running concurrently, which is a relatively expensive operation. + /// Slow is a relative term, though. This only starts to matter if you have lots of agents, maybe a hundred or so. So don't be scared of using it. + /// + /// But if you have a lot of agents, it is recommended to not access properties on this script more often than required. Avoid setting fields to the same value over and over again every frame, for example. + /// If you have a moving target, try to use the <see cref="AIDestinationSetter"/> component instead of setting the <see cref="destination"/> property manually, as that is faster than setting the <see cref="destination"/> property every frame. + /// + /// You can instead write custom ECS systems to access the properties on the ECS components directly. This is much faster. + /// For example, if you want to make the agent follow a particular entity, you could create a new DestinationEntity component which just holds an entity reference, + /// and then create a system that every frame copies that entity's position to the <see cref="DestinationPoint.destination"/> field (a component that this entity will always have). + /// + /// This script has some optional parts. Local avoidance, for example. Local avoidance is used to make sure that agents do not overlap each other. + /// However, if you do not need it, you can disable it to improve performance. + /// </summary> + [AddComponentMenu("Pathfinding/AI/Follower Entity (2D,3D)")] + [UniqueComponent(tag = "ai")] + [UniqueComponent(tag = "rvo")] + public sealed partial class FollowerEntity : VersionedMonoBehaviour, IAstarAI, ISerializationCallbackReceiver { + [SerializeField] + AgentCylinderShape shape = new AgentCylinderShape { + height = 2, + radius = 0.5f, + }; + [SerializeField] + MovementSettings movement = new MovementSettings { + follower = new PIDMovement { + rotationSpeed = 600, + speed = 5, + maxRotationSpeed = 720, + maxOnSpotRotationSpeed = 720, + slowdownTime = 0.5f, + desiredWallDistance = 0.5f, + allowRotatingOnSpot = true, + leadInRadiusWhenApproachingDestination = 1f, + }, + stopDistance = 0.2f, + rotationSmoothing = 0f, + groundMask = -1, + isStopped = false, + }; + + [SerializeField] + ManagedState managedState = new ManagedState { + enableLocalAvoidance = false, + pathfindingSettings = PathRequestSettings.Default, + }; + + [SerializeField] + ECS.AutoRepathPolicy autoRepathBacking = ECS.AutoRepathPolicy.Default; + + /// <summary> + /// Determines which direction the agent moves in. + /// + /// See: <see cref="orientation"/> + /// </summary> + [SerializeField] + OrientationMode orientationBacking; + [SerializeField] + MovementPlaneSource movementPlaneSourceBacking = MovementPlaneSource.Graph; + + /// <summary>Cached transform component</summary> + Transform tr; + + /// <summary> + /// Entity which this movement script represents. + /// + /// An entity will be created when this script is enabled, and destroyed when this script is disabled. + /// + /// Check the class documentation to see which components it usually has, and what systems typically affect it. + /// </summary> + public Entity entity { get; private set; } + + static EntityAccess<DestinationPoint> destinationPointAccessRW = new EntityAccess<DestinationPoint>(false); + static EntityAccess<DestinationPoint> destinationPointAccessRO = new EntityAccess<DestinationPoint>(true); + static EntityAccess<AgentMovementPlane> movementPlaneAccessRW = new EntityAccess<AgentMovementPlane>(false); + static EntityAccess<AgentMovementPlane> movementPlaneAccessRO = new EntityAccess<AgentMovementPlane>(false); + static EntityAccess<MovementState> movementStateAccessRW = new EntityAccess<MovementState>(false); + static EntityAccess<MovementState> movementStateAccessRO = new EntityAccess<MovementState>(true); + static EntityAccess<MovementStatistics> movementOutputAccessRW = new EntityAccess<MovementStatistics>(false); + static EntityAccess<ResolvedMovement> resolvedMovementAccessRO = new EntityAccess<ResolvedMovement>(true); + static EntityAccess<ResolvedMovement> resolvedMovementAccessRW = new EntityAccess<ResolvedMovement>(false); + static EntityAccess<MovementControl> movementControlAccessRO = new EntityAccess<MovementControl>(true); + static EntityAccess<MovementControl> movementControlAccessRW = new EntityAccess<MovementControl>(false); + static ManagedEntityAccess<ManagedState> managedStateAccessRO = new ManagedEntityAccess<ManagedState>(true); + static ManagedEntityAccess<ManagedState> managedStateAccessRW = new ManagedEntityAccess<ManagedState>(false); + static EntityAccess<ECS.AutoRepathPolicy> autoRepathPolicyRW = new EntityAccess<ECS.AutoRepathPolicy>(false); + static EntityAccess<LocalTransform> localTransformAccessRO = new EntityAccess<LocalTransform>(true); + static EntityAccess<LocalTransform> localTransformAccessRW = new EntityAccess<LocalTransform>(false); + static EntityAccess<AgentCylinderShape> agentCylinderShapeAccessRO = new EntityAccess<AgentCylinderShape>(true); + static EntityAccess<AgentCylinderShape> agentCylinderShapeAccessRW = new EntityAccess<AgentCylinderShape>(false); + static EntityAccess<MovementSettings> movementSettingsAccessRO = new EntityAccess<MovementSettings>(true); + static EntityAccess<MovementSettings> movementSettingsAccessRW = new EntityAccess<MovementSettings>(false); + static EntityAccess<AgentOffMeshLinkTraversal> agentOffMeshLinkTraversalRO = new EntityAccess<AgentOffMeshLinkTraversal>(true); + static EntityAccess<ReadyToTraverseOffMeshLink> readyToTraverseOffMeshLinkRW = new EntityAccess<ReadyToTraverseOffMeshLink>(false); + static EntityStorageCache entityStorageCache; + + static EntityArchetype archetype; + static World achetypeWorld; + + void OnEnable () { + scratchReferenceCount++; + + var world = World.DefaultGameObjectInjectionWorld; + if (!archetype.Valid || achetypeWorld != world) { + if (world == null) throw new Exception("World.DefaultGameObjectInjectionWorld is null. Has the world been destroyed?"); + achetypeWorld = world; + archetype = world.EntityManager.CreateArchetype( + typeof(LocalTransform), + typeof(MovementState), + typeof(MovementSettings), + typeof(ECS.AutoRepathPolicy), + typeof(MovementControl), + typeof(ManagedState), + typeof(SearchState), + typeof(MovementStatistics), + typeof(AgentCylinderShape), + typeof(ResolvedMovement), + typeof(DestinationPoint), + typeof(AgentMovementPlane), + typeof(GravityState), + typeof(SimulateMovement), + typeof(SimulateMovementRepair), + typeof(SimulateMovementControl), + typeof(SimulateMovementFinalize), + typeof(SyncPositionWithTransform), + typeof(SyncRotationWithTransform), + typeof(ReadyToTraverseOffMeshLink), + typeof(AgentMovementPlaneSource) + ); + } + + FindComponents(); + + entity = world.EntityManager.CreateEntity(archetype); + var pos = tr.position; + // This GameObject may be in a hierarchy, but the entity will not be. So we copy the world orientation to the entity's local transform component + world.EntityManager.SetComponentData(entity, LocalTransform.FromPositionRotationScale(pos, tr.rotation, tr.localScale.x)); + world.EntityManager.SetComponentData(entity, new MovementState(pos)); +#if UNITY_EDITOR + world.EntityManager.SetName(entity, "Follower Entity"); +#endif + // Set the initial movement plane. This will be overriden before the first simulation loop runs. + world.EntityManager.SetComponentData(entity, new AgentMovementPlane(tr.rotation)); + world.EntityManager.SetComponentData(entity, new DestinationPoint { + destination = new float3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity), + }); + autoRepathBacking.Reset(); + world.EntityManager.SetComponentData(entity, autoRepathBacking); + world.EntityManager.SetComponentData(entity, movement); + if (!managedState.pathTracer.isCreated) { + managedState.pathTracer = new PathTracer(Allocator.Persistent); + } + world.EntityManager.SetComponentData(entity, managedState); + world.EntityManager.SetComponentData(entity, new MovementStatistics { + estimatedVelocity = float3.zero, + lastPosition = pos, + }); + world.EntityManager.SetComponentData(entity, shape); + world.EntityManager.SetComponentEnabled<GravityState>(entity, managedState.enableGravity); + if (orientation == OrientationMode.YAxisForward) { + world.EntityManager.AddComponent<OrientationYAxisForward>(entity); + } + world.EntityManager.SetComponentEnabled<ReadyToTraverseOffMeshLink>(entity, false); + world.EntityManager.SetSharedComponent(entity, new AgentMovementPlaneSource { value = movementPlaneSourceBacking }); + + // Register with the BatchedEvents system + // This is used not for the events, but because it keeps track of a TransformAccessArray + // of all components. This is then used by the SyncEntitiesToTransformsJob. + BatchedEvents.Add(this, BatchedEvents.Event.None, (components, ev) => {}); + + var runtimeBakers = GetComponents<IRuntimeBaker>(); + for (int i = 0; i < runtimeBakers.Length; i++) if (((MonoBehaviour)runtimeBakers[i]).enabled) runtimeBakers[i].OnCreatedEntity(world, entity); + } + + internal void RegisterRuntimeBaker (IRuntimeBaker baker) { + if (entityExists) baker.OnCreatedEntity(World.DefaultGameObjectInjectionWorld, entity); + } + + void Start () { + var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; + managedStateAccessRW.Update(entityManager); + movementPlaneAccessRO.Update(entityManager); + if (!managedState.pathTracer.hasPath && AstarPath.active != null) { + var nearest = AstarPath.active.GetNearest(position, NNConstraint.Walkable); + if (nearest.node != null) { + var storage = entityManager.GetStorageInfo(entity); + var movementPlane = movementPlaneAccessRO[storage]; + managedState.pathTracer.SetFromSingleNode(nearest.node, nearest.position, movementPlane.value); + managedState.pathTracer.UpdateEnd(new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity), PathTracer.RepairQuality.High, movementPlane.value, null, null); + } + } + } + + /// <summary> + /// Called when the component is disabled or about to be destroyed. + /// + /// This is also called by Unity when an undo/redo event is performed. This means that + /// when an undo event happens the entity will get destroyed and then re-created. + /// </summary> + void OnDisable () { + scratchReferenceCount--; + if (scratchReferenceCount == 0) { + if (indicesScratch.IsCreated) indicesScratch.Dispose(); + if (nextCornersScratch.IsCreated) nextCornersScratch.Dispose(); + } + + BatchedEvents.Remove(this); + CancelCurrentPathRequest(); + if (World.DefaultGameObjectInjectionWorld != null && World.DefaultGameObjectInjectionWorld.IsCreated) World.DefaultGameObjectInjectionWorld.EntityManager.DestroyEntity(entity); + managedState.pathTracer.Dispose(); + } + + /// <summary>\copydoc Pathfinding::IAstarAI::radius</summary> + public float radius { + get => shape.radius; + set { + this.shape.radius = value; + if (entityStorageCache.GetComponentData(entity, ref agentCylinderShapeAccessRW, out var shape)) { + shape.value.radius = value; + } + } + } + + /// <summary> + /// Height of the agent in world units. + /// This is visualized in the scene view as a yellow cylinder around the character. + /// + /// This value is used for various heuristics, and for visualization purposes. + /// For example, the destination is only considered reached if the destination is not above the agent's head, and it's not more than half the agent's height below its feet. + /// + /// If local lavoidance is enabled, this is also used to filter out collisions with agents and obstacles that are too far above or below the agent. + /// </summary> + public float height { + get => shape.height; + set { + this.shape.height = value; + if (entityStorageCache.GetComponentData(entity, ref agentCylinderShapeAccessRW, out var shape)) { + shape.value.height = value; + } + } + } + + /// <summary>Pathfinding settings</summary> + public ref PathRequestSettings pathfindingSettings { + get { + // Complete any job dependencies + // Need RW because this getter has a ref return. + entityStorageCache.GetComponentData(entity, ref movementStateAccessRW, out var _); + return ref managedState.pathfindingSettings; + } + } + + /// <summary>Local avoidance settings</summary> + public ref RVOAgent rvoSettings { + get { + // Complete any job dependencies + // Need RW because this getter has a ref return. + entityStorageCache.GetComponentData(entity, ref movementStateAccessRW, out var _); + return ref managedState.rvoSettings; + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::position</summary> + public Vector3 position { + get { + // Make sure we are not waiting for a job to update the world position + if (entityStorageCache.GetComponentData(entity, ref localTransformAccessRO, out var localTransform)) { + return localTransform.value.Position; + } else { + return transform.position; + } + } + set { + if (entityStorageCache.Update(World.DefaultGameObjectInjectionWorld, entity, out var entityManager, out var storage)) { + // Update path and other properties using our new position + if (entityManager.HasComponent<SyncPositionWithTransform>(entity)) { + transform.position = value; + } + movementStateAccessRW.Update(entityManager); + managedStateAccessRW.Update(entityManager); + agentCylinderShapeAccessRO.Update(entityManager); + movementSettingsAccessRO.Update(entityManager); + destinationPointAccessRO.Update(entityManager); + movementPlaneAccessRO.Update(entityManager); + localTransformAccessRW.Update(entityManager); + readyToTraverseOffMeshLinkRW.Update(entityManager); + + ref var localTransform = ref localTransformAccessRW[storage]; + localTransform.Position = value; + ref var movementState = ref movementStateAccessRW[storage]; + movementState.positionOffset = float3.zero; + if (managedState.pathTracer.hasPath) { + Profiler.BeginSample("RepairStart"); + ref var movementPlane = ref movementPlaneAccessRO[storage]; + var oldVersion = managedState.pathTracer.version; + managedState.pathTracer.UpdateStart(value, PathTracer.RepairQuality.High, movementPlane.value, managedState.pathfindingSettings.traversalProvider, managedState.activePath); + Profiler.EndSample(); + if (managedState.pathTracer.version != oldVersion) { + Profiler.BeginSample("EstimateNative"); + ref var shape = ref agentCylinderShapeAccessRO[storage]; + ref var movementSettings = ref movementSettingsAccessRO[storage]; + ref var destinationPoint = ref destinationPointAccessRO[storage]; + var readyToTraverseOffMeshLink = storage.Chunk.GetEnabledMask(ref readyToTraverseOffMeshLinkRW.handle).GetEnabledRefRW<ReadyToTraverseOffMeshLink>(storage.IndexInChunk); + if (!nextCornersScratch.IsCreated) nextCornersScratch = new NativeList<float3>(4, Allocator.Persistent); + JobRepairPath.Execute( + ref localTransform, + ref movementState, + ref shape, + ref movementPlane, + ref destinationPoint, + readyToTraverseOffMeshLink, + managedState, + in movementSettings, + nextCornersScratch, + ref indicesScratch, + Allocator.Persistent, + false + ); + Profiler.EndSample(); + } + } + } else { + transform.position = value; + } + } + } + + /// <summary> + /// True if the agent is currently traversing an off-mesh link. + /// + /// See: offmeshlinks (view in online documentation for working links) + /// See: <see cref="onTraverseOffMeshLink"/> + /// See: <see cref="offMeshLink"/> + /// </summary> + public bool isTraversingOffMeshLink { + get { + if (!entityExists) return false; + + var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; + return entityManager.HasComponent<AgentOffMeshLinkTraversal>(entity); + } + } + + /// <summary> + /// The off-mesh link that the agent is currently traversing. + /// + /// This will be a default <see cref="OffMeshLinks.OffMeshLinkTracer"/> if the agent is not traversing an off-mesh link (the <see cref="OffMeshLinks.OffMeshLinkTracer.link"/> field will be null). + /// + /// Note: If the off-mesh link is destroyed while the agent is traversing it, this property will still return the link. + /// But be careful about accessing properties like <see cref="OffMeshLinkSource.gameObject"/>, as that may refer to a destroyed gameObject. + /// + /// See: offmeshlinks (view in online documentation for working links) + /// See: <see cref="onTraverseOffMeshLink"/> + /// See: <see cref="isTraversingOffMeshLink"/> + /// </summary> + public OffMeshLinks.OffMeshLinkTracer offMeshLink { + get { + if (entityStorageCache.Update(World.DefaultGameObjectInjectionWorld, entity, out var entityManager, out var storage) && entityManager.HasComponent<ManagedAgentOffMeshLinkTraversal>(entity)) { + agentOffMeshLinkTraversalRO.Update(entityManager); + var linkTraversal = agentOffMeshLinkTraversalRO[storage]; + var linkTraversalManaged = entityManager.GetComponentData<ManagedAgentOffMeshLinkTraversal>(entity); + return new OffMeshLinks.OffMeshLinkTracer(linkTraversalManaged.context.concreteLink, linkTraversal.relativeStart, linkTraversal.relativeEnd, linkTraversal.isReverse); + } else { + return default; + } + } + } + + /// <summary> + /// Callback to be called when an agent starts traversing an off-mesh link. + /// + /// The handler will be called when the agent starts traversing an off-mesh link. + /// It allows you to to control the agent for the full duration of the link traversal. + /// + /// Use the passed context struct to get information about the link and to control the agent. + /// + /// <code> + /// using UnityEngine; + /// using Pathfinding; + /// using System.Collections; + /// using Pathfinding.ECS; + /// + /// namespace Pathfinding.Examples { + /// public class FollowerJumpLink : MonoBehaviour, IOffMeshLinkHandler, IOffMeshLinkStateMachine { + /// // Register this class as the handler for off-mesh links when the component is enabled + /// void OnEnable() => GetComponent<NodeLink2>().onTraverseOffMeshLink = this; + /// void OnDisable() => GetComponent<NodeLink2>().onTraverseOffMeshLink = null; + /// + /// IOffMeshLinkStateMachine IOffMeshLinkHandler.GetOffMeshLinkStateMachine(AgentOffMeshLinkTraversalContext context) => this; + /// + /// void IOffMeshLinkStateMachine.OnFinishTraversingOffMeshLink (AgentOffMeshLinkTraversalContext context) { + /// Debug.Log("An agent finished traversing an off-mesh link"); + /// } + /// + /// void IOffMeshLinkStateMachine.OnAbortTraversingOffMeshLink () { + /// Debug.Log("An agent aborted traversing an off-mesh link"); + /// } + /// + /// IEnumerable IOffMeshLinkStateMachine.OnTraverseOffMeshLink (AgentOffMeshLinkTraversalContext ctx) { + /// var start = (Vector3)ctx.link.relativeStart; + /// var end = (Vector3)ctx.link.relativeEnd; + /// var dir = end - start; + /// + /// // Disable local avoidance while traversing the off-mesh link. + /// // If it was enabled, it will be automatically re-enabled when the agent finishes traversing the link. + /// ctx.DisableLocalAvoidance(); + /// + /// // Move and rotate the agent to face the other side of the link. + /// // When reaching the off-mesh link, the agent may be facing the wrong direction. + /// while (!ctx.MoveTowards( + /// position: start, + /// rotation: Quaternion.LookRotation(dir, ctx.movementPlane.up), + /// gravity: true, + /// slowdown: true).reached) { + /// yield return null; + /// } + /// + /// var bezierP0 = start; + /// var bezierP1 = start + Vector3.up*5; + /// var bezierP2 = end + Vector3.up*5; + /// var bezierP3 = end; + /// var jumpDuration = 1.0f; + /// + /// // Animate the AI to jump from the start to the end of the link + /// for (float t = 0; t < jumpDuration; t += ctx.deltaTime) { + /// ctx.transform.Position = AstarSplines.CubicBezier(bezierP0, bezierP1, bezierP2, bezierP3, Mathf.SmoothStep(0, 1, t / jumpDuration)); + /// yield return null; + /// } + /// } + /// } + /// } + /// </code> + /// + /// Warning: Off-mesh links can be destroyed or disabled at any moment. The built-in code will attempt to make the agent continue following the link even if it is destroyed, + /// but if you write your own traversal code, you should be aware of this. + /// + /// You can alternatively set the corresponding property property on the off-mesh link (<see cref="NodeLink2.onTraverseOffMeshLink"/>) to specify a callback for a specific off-mesh link. + /// + /// Note: The agent's off-mesh link handler takes precedence over the link's off-mesh link handler, if both are set. + /// + /// See: offmeshlinks (view in online documentation for working links) for more details and example code + /// See: <see cref="isTraversingOffMeshLink"/> + /// </summary> + public IOffMeshLinkHandler onTraverseOffMeshLink { + get => managedState.onTraverseOffMeshLink; + set { + // Complete any job dependencies + entityStorageCache.GetComponentData(entity, ref movementStateAccessRW, out var _); + managedState.onTraverseOffMeshLink = value; + } + } + + /// <summary> + /// Node which the agent is currently traversing. + /// + /// You can, for example, use this to make the agent use a different animation when traversing nodes with a specific tag. + /// + /// Note: Will be null if the agent does not have a path, or if the node under the agent has just been destroyed by a graph update. + /// + /// When traversing an off-mesh link, this will return the final non-link node in the path before the agent started traversing the link. + /// </summary> + public GraphNode currentNode { + get { + if (!entityExists) return null; + + var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; + // Complete any job dependencies + managedStateAccessRO.Update(entityManager); + var node = managedState.pathTracer.startNode; + if (node == null || node.Destroyed) return null; + return node; + } + } + + /// <summary> + /// Rotation of the agent. + /// In world space. + /// + /// The entity internally always treats the Z axis as forward, but this property respects the <see cref="orientation"/> field. So it + /// will return either a rotation with the Y axis as forward, or Z axis as forward, depending on the <see cref="orientation"/> field. + /// + /// This will return the agent's rotation even if <see cref="updateRotation"/> is false. + /// + /// See: <see cref="position"/> + /// </summary> + public Quaternion rotation { + get { + if (entityStorageCache.GetComponentData(entity, ref localTransformAccessRO, out var localTransform)) { + var r = localTransform.value.Rotation; + if (orientation == OrientationMode.YAxisForward) r = math.mul(r, SyncTransformsToEntitiesSystem.ZAxisForwardToYAxisForward); + return r; + } else { + return transform.rotation; + } + } + set { + if (entityStorageCache.Update(World.DefaultGameObjectInjectionWorld, entity, out var entityManager, out var storage)) { + // Update path and other properties using our new position + if (entityManager.HasComponent<SyncRotationWithTransform>(entity)) { + transform.rotation = value; + } + + if (orientation == OrientationMode.YAxisForward) value = math.mul(value, SyncTransformsToEntitiesSystem.YAxisForwardToZAxisForward); + localTransformAccessRW.Update(entityManager); + localTransformAccessRW[storage].Rotation = value; + } else { + transform.rotation = value; + } + } + } + + /// <summary> + /// How to calculate which direction is "up" for the agent. + /// + /// In almost all cases, you should use the Graph option. This will make the agent use the graph's natural "up" direction. + /// However, if you are using a spherical world, or a world with some other strange shape, then you may want to use the NavmeshNormal or Raycast options. + /// + /// See: spherical (view in online documentation for working links) + /// </summary> + public MovementPlaneSource movementPlaneSource { + get => movementPlaneSourceBacking; + set { + movementPlaneSourceBacking = value; + if (entityExists) { + var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; + entityManager.SetSharedComponent(entity, new AgentMovementPlaneSource { value = value }); + } + } + } + + /// <summary> + /// Determines which layers the agent will stand on. + /// + /// The agent will use a raycast each frame to check if it should stop falling. + /// + /// This layer mask should ideally not contain the agent's own layer, if the agent has a collider, + /// as this may cause it to try to stand on top of itself. + /// </summary> + public LayerMask groundMask { + get => movement.groundMask; + set { + movement.groundMask = value; + if (entityStorageCache.GetComponentData(entity, ref movementSettingsAccessRW, out var movementSettings)) { + movementSettings.value.groundMask = value; + } + } + } + + /// <summary> + /// Enables or disables debug drawing for this agent. + /// + /// This is a bitmask with multiple flags so that you can choose exactly what you want to debug. + /// + /// See: <see cref="PIDMovement.DebugFlags"/> + /// See: bitmasks (view in online documentation for working links) + /// </summary> + public PIDMovement.DebugFlags debugFlags { + get => movement.debugFlags; + set { + movement.debugFlags = value; + if (entityStorageCache.GetComponentData(entity, ref movementSettingsAccessRW, out var movementSettings)) { + movementSettings.value.debugFlags = value; + } + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::maxSpeed</summary> + public float maxSpeed { + get => movement.follower.speed; + set { + movement.follower.speed = value; + if (entityStorageCache.GetComponentData(entity, ref movementSettingsAccessRW, out var movementSettings)) { + movementSettings.value.follower.speed = value; + } + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::velocity</summary> + public Vector3 velocity => entityExists ? (Vector3)World.DefaultGameObjectInjectionWorld.EntityManager.GetComponentData<MovementStatistics>(entity).estimatedVelocity : Vector3.zero; + + /// <summary>\copydoc Pathfinding::IAstarAI::desiredVelocity</summary> + public Vector3 desiredVelocity { + get { + if (entityStorageCache.GetComponentData(entity, ref resolvedMovementAccessRO, out var resolvedMovement)) { + var dt = Mathf.Max(Time.deltaTime, 0.0001f); + return Vector3.ClampMagnitude((Vector3)resolvedMovement.value.targetPoint - position, dt * resolvedMovement.value.speed) / dt; + } else { + return Vector3.zero; + } + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::desiredVelocityWithoutLocalAvoidance</summary> + public Vector3 desiredVelocityWithoutLocalAvoidance { + get { + if (entityStorageCache.GetComponentData(entity, ref movementControlAccessRO, out var movementControl)) { + var dt = Mathf.Max(Time.deltaTime, 0.0001f); + return Vector3.ClampMagnitude((Vector3)movementControl.value.targetPoint - position, dt * movementControl.value.speed) / dt; + } else { + return Vector3.zero; + } + } + set => throw new NotImplementedException("The FollowerEntity does not support setting this property. If you want to override the movement, you'll need to write a custom entity component system."); + } + + /// <summary> + /// Approximate remaining distance along the current path to the end of the path. + /// + /// The agent does not know the true distance at all times, so this is an approximation. + /// It tends to be a bit lower than the true distance. + /// + /// Note: This is the distance to the end of the path, which may or may not be the same as the destination. + /// If the character cannot reach the destination it will try to move as close as possible to it. + /// + /// This value will update immediately if the <see cref="destination"/> property is changed, or if the agent is moved using the <see cref="position"/> property or the <see cref="Teleport"/> method. + /// + /// If the agent has no path, or if the current path is stale (e.g. if the graph has been updated close to the agent, and it hasn't had time to recalculate its path), this will return positive infinity. + /// + /// See: <see cref="reachedDestination"/> + /// See: <see cref="reachedEndOfPath"/> + /// See: <see cref="pathPending"/> + /// </summary> + public float remainingDistance { + get { + if (!entityStorageCache.Update(World.DefaultGameObjectInjectionWorld, entity, out var entityManager, out var storage)) return float.PositiveInfinity; + + movementStateAccessRO.Update(entityManager); + managedStateAccessRO.Update(entityManager); + // TODO: Should this perhaps only check if the start/end points are stale, and ignore the case when the graph is updated and some nodes are destroyed? + if (managedState.pathTracer.hasPath && !managedState.pathTracer.isStale) { + ref var movementState = ref movementStateAccessRO[storage]; + return movementState.remainingDistanceToEndOfPart + Vector3.Distance(managedState.pathTracer.endPointOfFirstPart, managedState.pathTracer.endPoint); + } else { + return float.PositiveInfinity; + } + } + } + + /// <summary>\copydocref{MovementSettings.stopDistance}</summary> + public float stopDistance { + get => movement.stopDistance; + set { + if (movement.stopDistance != value) { + movement.stopDistance = value; + if (entityStorageCache.GetComponentData(entity, ref movementSettingsAccessRW, out var movementSettings)) { + movementSettings.value.stopDistance = value; + } + } + } + } + + /// <summary>\copydocref{MovementSettings.rotationSmoothing}</summary> + public float rotationSmoothing { + get => movement.rotationSmoothing; + set { + if (movement.rotationSmoothing != value) { + movement.rotationSmoothing = value; + if (entityStorageCache.GetComponentData(entity, ref movementSettingsAccessRW, out var movementSettings)) { + movementSettings.value.rotationSmoothing = value; + } + } + } + } + + /// <summary> + /// True if the ai has reached the <see cref="destination"/>. + /// + /// The agent considers the destination reached when it is within <see cref="stopDistance"/> world units from the <see cref="destination"/>. + /// Additionally, the destination must not be above the agent's head, and it must not be more than half the agent's height below its feet. + /// + /// If a facing direction was specified when setting the destination, this will only return true once the agent is approximately facing the correct orientation. + /// + /// This value will be updated immediately when the <see cref="destination"/> is changed. + /// + /// <code> + /// IEnumerator Start () { + /// ai.destination = somePoint; + /// // Start to search for a path to the destination immediately + /// ai.SearchPath(); + /// // Wait until the agent has reached the destination + /// while (!ai.reachedDestination) { + /// yield return null; + /// } + /// // The agent has reached the destination now + /// } + /// </code> + /// + /// Note: The agent may not be able to reach the destination. In that case this property may never become true. Sometimes <see cref="reachedEndOfPath"/> is more appropriate. + /// + /// See: <see cref="stopDistance"/> + /// See: <see cref="remainingDistance"/> + /// See: <see cref="reachedEndOfPath"/> + /// </summary> + public bool reachedDestination => entityStorageCache.GetComponentData(entity, ref movementStateAccessRW, out var movementState) ? movementState.value.reachedDestinationAndOrientation : false; + + /// <summary> + /// True if the agent has reached the end of the current path. + /// + /// The agent considers the end of the path reached when it is within <see cref="stopDistance"/> world units from the end of the path. + /// Additionally, the end of the path must not be above the agent's head, and it must not be more than half the agent's height below its feet. + /// + /// If a facing direction was specified when setting the destination, this will only return true once the agent is approximately facing the correct orientation. + /// + /// This value will be updated immediately when the <see cref="destination"/> is changed. + /// + /// Note: Reaching the end of the path does not imply that it has reached its desired destination, as the destination may not even be possible to reach. + /// Sometimes <see cref="reachedDestination"/> is more appropriate. + /// + /// See: <see cref="remainingDistance"/> + /// See: <see cref="reachedDestination"/> + /// </summary> + public bool reachedEndOfPath => entityStorageCache.GetComponentData(entity, ref movementStateAccessRW, out var movementState) ? movementState.value.reachedEndOfPathAndOrientation : false; + + /// <summary> + /// End point of path the agent is currently following. + /// If the agent has no path (or if it's not calculated yet), this will return the <see cref="destination"/> instead. + /// If the agent has no destination it will return the agent's current position. + /// + /// The end of the path is usually identical or very close to the <see cref="destination"/>, but it may differ + /// if the path for example was blocked by a wall, so that the agent couldn't get any closer. + /// + /// See: <see cref="GetRemainingPath"/> + /// </summary> + public Vector3 endOfPath { + get { + if (entityExists) { + // Make sure we block to ensure no managed state changes are made in jobs while we are reading from it + managedStateAccessRO.Update(World.DefaultGameObjectInjectionWorld.EntityManager); + if (hasPath) return managedState.pathTracer.endPoint; + var d = destination; + if (float.IsFinite(d.x)) return d; + } + return position; + } + } + + static NativeList<float3> nextCornersScratch; + static NativeArray<int> indicesScratch; + static int scratchReferenceCount = 0; + + /// <summary>\copydoc Pathfinding::IAstarAI::destination</summary> + + /// <summary> + /// Position in the world that this agent should move to. + /// + /// If no destination has been set yet, then (+infinity, +infinity, +infinity) will be returned. + /// + /// Setting this property will immediately try to repair the path if the agent already has a path. + /// This will also immediately update properties like <see cref="reachedDestination"/>, <see cref="reachedEndOfPath"/> and <see cref="remainingDistance"/>. + /// + /// The agent may do a full path recalculation if the local repair was not sufficient, + /// but this will at earliest happen in the next simulation step. + /// + /// <code> + /// IEnumerator Start () { + /// ai.destination = somePoint; + /// // Wait until the AI has reached the destination + /// while (!ai.reachedEndOfPath) { + /// yield return null; + /// } + /// // The agent has reached the destination now + /// } + /// </code> + /// + /// See: <see cref="SetDestination"/>, which also allows you to set a facing direction for the agent. + /// </summary> + public Vector3 destination { + get => entityStorageCache.GetComponentData(entity, ref destinationPointAccessRO, out var destination) ? (Vector3)destination.value.destination : Vector3.positiveInfinity; + set => SetDestination(value, default); + } + + /// <summary> + /// Direction the agent will try to face when it reaches the destination. + /// + /// If this is zero, the agent will not try to face any particular direction. + /// + /// The following video shows three agents, one with no facing direction set, and then two agents with varying values of the <see cref="PIDMovement.leadInRadiusWhenApproachingDestination;lead in radius"/>. + /// [Open online documentation to see videos] + /// + /// See: <see cref="MovementSettings.follower.leadInRadiusWhenApproachingDestination"/> + /// See: <see cref="SetDestination"/> + /// </summary> + Vector3 destinationFacingDirection { + get => entityStorageCache.GetComponentData(entity, ref destinationPointAccessRO, out var destination) ? (Vector3)destination.value.facingDirection : Vector3.zero; + } + + /// <summary> + /// Set the position in the world that this agent should move to. + /// + /// This method will immediately try to repair the path if the agent already has a path. + /// This will also immediately update properties like <see cref="reachedDestination"/>, <see cref="reachedEndOfPath"/> and <see cref="remainingDistance"/>. + /// The agent may do a full path recalculation if the local repair was not sufficient, + /// but this will at earliest happen in the next simulation step. + /// + /// If you are setting a destination and want to know when the agent has reached that destination, + /// then you could use either <see cref="reachedDestination"/> or <see cref="reachedEndOfPath"/>. + /// + /// You may also set a facing direction for the agent. If set, the agent will try to approach the destination point + /// with the given heading. <see cref="reachedDestination"/> and <see cref="reachedEndOfPath"/> will only return true once the agent is approximately facing the correct direction. + /// The <see cref="MovementSettings.follower.leadInRadiusWhenApproachingDestination"/> field controls how wide an arc the agent will try to use when approaching the destination. + /// + /// The following video shows three agents, one with no facing direction set, and then two agents with varying values of the <see cref="PIDMovement.leadInRadiusWhenApproachingDestination;lead in radius"/>. + /// [Open online documentation to see videos] + /// + /// <code> + /// IEnumerator Start () { + /// ai.SetDestination(somePoint, Vector3.right); + /// // Wait until the AI has reached the destination and is rotated to the right in world space + /// while (!ai.reachedEndOfPath) { + /// yield return null; + /// } + /// // The agent has reached the destination now + /// } + /// </code> + /// + /// See: <see cref="destination"/> + /// </summary> + public void SetDestination (float3 destination, float3 facingDirection = default) { + AssertEntityExists(); + var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; + movementStateAccessRW.Update(entityManager); + managedStateAccessRW.Update(entityManager); + agentCylinderShapeAccessRO.Update(entityManager); + movementSettingsAccessRO.Update(entityManager); + localTransformAccessRO.Update(entityManager); + destinationPointAccessRW.Update(entityManager); + movementPlaneAccessRO.Update(entityManager); + readyToTraverseOffMeshLinkRW.Update(entityManager); + + var storage = entityManager.GetStorageInfo(entity); + destinationPointAccessRW[storage] = new DestinationPoint { + destination = destination, + facingDirection = facingDirection, + }; + + // If we already have a path, we try to repair it immediately. + // This ensures that the #reachedDestination and #reachedEndOfPath flags are as up to date as possible. + if (managedState.pathTracer.hasPath) { + Profiler.BeginSample("RepairEnd"); + ref var movementPlane = ref movementPlaneAccessRO[storage]; + managedState.pathTracer.UpdateEnd(destination, PathTracer.RepairQuality.High, movementPlane.value, managedState.pathfindingSettings.traversalProvider, managedState.activePath); + Profiler.EndSample(); + ref var movementState = ref movementStateAccessRW[storage]; + if (movementState.pathTracerVersion != managedState.pathTracer.version) { + Profiler.BeginSample("EstimateNative"); + ref var shape = ref agentCylinderShapeAccessRO[storage]; + ref var movementSettings = ref movementSettingsAccessRO[storage]; + ref var localTransform = ref localTransformAccessRO[storage]; + ref var destinationPoint = ref destinationPointAccessRW[storage]; + var readyToTraverseOffMeshLink = storage.Chunk.GetEnabledMask(ref readyToTraverseOffMeshLinkRW.handle).GetEnabledRefRW<ReadyToTraverseOffMeshLink>(storage.IndexInChunk); + if (!nextCornersScratch.IsCreated) nextCornersScratch = new NativeList<float3>(4, Allocator.Persistent); + JobRepairPath.Execute( + ref localTransform, + ref movementState, + ref shape, + ref movementPlane, + ref destinationPoint, + readyToTraverseOffMeshLink, + managedState, + in movementSettings, + nextCornersScratch, + ref indicesScratch, + Allocator.Persistent, + false + ); + Profiler.EndSample(); + } + } + } + + /// <summary> + /// Policy for when the agent recalculates its path. + /// + /// See: <see cref="AutoRepathPolicy"/> + /// </summary> + public ECS.AutoRepathPolicy autoRepath { + get { + return autoRepathBacking; + } + set { + autoRepathBacking = value; + if (entityStorageCache.GetComponentData(entity, ref autoRepathPolicyRW, out var component)) { + component.value = value; + } + } + } + + /// <summary> + /// \copydoc Pathfinding::IAstarAI::canSearch + /// Deprecated: This has been superseded by <see cref="autoRepath.mode"/>. + /// </summary> + [System.Obsolete("This has been superseded by autoRepath.mode")] + public bool canSearch { + get { + return autoRepathBacking.mode != AutoRepathPolicy.Mode.Never; + } + set { + if (value) { + if (autoRepathBacking.mode == AutoRepathPolicy.Mode.Never) { + autoRepathBacking.mode = AutoRepathPolicy.Mode.EveryNSeconds; + } + } else { + autoRepathBacking.mode = AutoRepathPolicy.Mode.Never; + } + // Ensure the entity date is up to date + autoRepath = autoRepathBacking; + } + } + + /// <summary> + /// Enables or disables movement completely. + /// If you want the agent to stand still, but still react to local avoidance and use gravity: use <see cref="isStopped"/> instead. + /// + /// Disabling this will remove the <see cref="SimulateMovement"/> component from the entity, which prevents + /// most systems from running for this entity. + /// + /// See: <see cref="autoRepath"/> + /// See: <see cref="isStopped"/> + /// </summary> + public bool canMove { + get { + if (!entityExists) return true; + + var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; + return entityManager.HasComponent<SimulateMovement>(entity); + } + set => ToggleComponent<SimulateMovement>(entity, value, true); + } + + /// <summary>\copydoc Pathfinding::IAstarAI::movementPlane</summary> + public NativeMovementPlane movementPlane => entityStorageCache.GetComponentData(entity, ref movementPlaneAccessRO, out var movementPlane) ? movementPlane.value.value : new NativeMovementPlane(rotation); + + /// <summary> + /// Enables or disables gravity. + /// + /// If gravity is enabled, the agent will accelerate downwards, and use a raycast to check if it should stop falling. + /// + /// See: <see cref="groundMask"/> + /// </summary> + public bool enableGravity { + get { + if (!entityExists) return managedState.enableGravity; + + var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; + return entityManager.HasComponent<GravityState>(entity); + } + set { + if (managedState.enableGravity != value) { + managedState.enableGravity = value; + ToggleComponentEnabled<GravityState>(entity, value, false); + } + } + } + + /// <summary>\copydocref{ManagedState.enableLocalAvoidance}</summary> + public bool enableLocalAvoidance { + get => managedState.enableLocalAvoidance; + set => managedState.enableLocalAvoidance = value; + } + + /// <summary> + /// Determines if the character's position should be coupled to the Transform's position. + /// If false then all movement calculations will happen as usual, but the GameObject that this component is attached to will not move. + /// Instead, only the <see cref="position"/> property and the internal entity's position will change. + /// + /// This is useful if you want to control the movement of the character using some other means, such + /// as root motion, but still want the AI to move freely. + /// + /// See: <see cref="canMove"/> which in contrast to this field will disable all movement calculations. + /// See: <see cref="updateRotation"/> + /// </summary> + public bool updatePosition { + get { + if (!entityExists) return true; + var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; + return entityManager.HasComponent<SyncPositionWithTransform>(entity); + } + set => ToggleComponent<SyncPositionWithTransform>(entity, value, true); + } + + /// <summary> + /// Determines which direction the agent moves in. + /// For 3D games you most likely want the ZAxisIsForward option as that is the convention for 3D games. + /// For 2D games you most likely want the YAxisIsForward option as that is the convention for 2D games. + /// + /// When using ZAxisForard, the +Z axis will be the forward direction of the agent, +Y will be upwards, and +X will be the right direction. + /// When using YAxisForward, the +Y axis will be the forward direction of the agent, +Z will be upwards, and +X will be the right direction. + /// + /// [Open online documentation to see images] + /// </summary> + public OrientationMode orientation { + get => orientationBacking; + set { + if (orientationBacking != value) { + orientationBacking = value; + ToggleComponent<OrientationYAxisForward>(entity, value == OrientationMode.YAxisForward, false); + } + } + } + + /// <summary> + /// Determines if the character's rotation should be coupled to the Transform's rotation. + /// If false then all movement calculations will happen as usual, but the GameObject that this component is attached to will not rotate. + /// Instead, only the <see cref="rotation"/> property and the internal entity's rotation will change. + /// + /// You can enable <see cref="PIDMovement.DebugFlags"/>.Rotation in <see cref="debugFlags"/> to draw a gizmos arrow in the scene view to indicate the agent's internal rotation. + /// + /// See: <see cref="updatePosition"/> + /// See: <see cref="rotation"/> + /// See: <see cref="orientation"/> + /// </summary> + public bool updateRotation { + get { + if (!entityExists) return true; + var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; + return entityManager.HasComponent<SyncRotationWithTransform>(entity); + } + set => ToggleComponent<SyncRotationWithTransform>(entity, value, true); + } + + /// <summary>Adds or removes a component from an entity</summary> + static void ToggleComponent<T>(Entity entity, bool enabled, bool mustExist) where T : struct, IComponentData { + var world = World.DefaultGameObjectInjectionWorld; + if (world == null || !world.EntityManager.Exists(entity)) { + if (!mustExist) throw new System.InvalidOperationException("Entity does not exist. You can only access this if the component is active and enabled."); + return; + } + if (enabled) { + world.EntityManager.AddComponent<T>(entity); + } else { + world.EntityManager.RemoveComponent<T>(entity); + } + } + + /// <summary>Enables or disables a component on an entity</summary> + static void ToggleComponentEnabled<T>(Entity entity, bool enabled, bool mustExist) where T : struct, IComponentData, IEnableableComponent { + var world = World.DefaultGameObjectInjectionWorld; + if (world == null || !world.EntityManager.Exists(entity)) { + if (!mustExist) throw new System.InvalidOperationException("Entity does not exist. You can only access this if the component is active and enabled."); + return; + } + world.EntityManager.SetComponentEnabled<T>(entity, enabled); + } + + /// <summary> + /// True if this agent currently has a valid path that it follows. + /// + /// This is true if the agent has a path and the path is not stale. + /// + /// A path may become stale if the graph is updated close to the agent and it hasn't had time to recalculate its path yet. + /// </summary> + public bool hasPath { + get { + // Ensure no jobs are writing to the managed state while we are reading from it + if (entityExists) managedStateAccessRO.Update(World.DefaultGameObjectInjectionWorld.EntityManager); + return !managedState.pathTracer.isStale; + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::pathPending</summary> + public bool pathPending { + get { + if (!entityExists) return false; + var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; + managedStateAccessRO.Update(entityManager); + return managedState.pendingPath != null; + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::isStopped</summary> + public bool isStopped { + get => movement.isStopped; + set { + if (movement.isStopped != value) { + movement.isStopped = value; + if (entityStorageCache.GetComponentData(entity, ref movementSettingsAccessRW, out var movementSettings)) { + movementSettings.value.isStopped = value; + } + } + } + } + + /// <summary> + /// Various movement settings. + /// + /// Some of these settings are exposed on the FollowerEntity directly. For example <see cref="maxSpeed"/>. + /// + /// Note: The return value is a struct. If you want to change some settings, you'll need to modify the returned struct and then assign it back to this property. + /// </summary> + public MovementSettings movementSettings { + get => movement; + set { + movement = value; + if (entityStorageCache.GetComponentData(entity, ref movementSettingsAccessRW, out var movementSettings)) { + movementSettings.value = value; + } + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::steeringTarget</summary> + public Vector3 steeringTarget => entityStorageCache.GetComponentData(entity, ref movementStateAccessRO, out var movementState) ? (Vector3)movementState.value.nextCorner : position; + + /// <summary>\copydoc Pathfinding::IAstarAI::onSearchPath</summary> + Action IAstarAI.onSearchPath { + get => null; + set => throw new NotImplementedException("The FollowerEntity does not support this property."); + } + + /// <summary> + /// Provides callbacks during various parts of the movement calculations. + /// + /// With this property you can register callbacks that will be called during various parts of the movement calculations. + /// These can be used to modify movement of the agent. + /// + /// The following example demonstrates how one can hook into one of the available phases and modify the agent's movement. + /// In this case, the movement is modified to become wavy. + /// + /// [Open online documentation to see videos] + /// + /// <code> + /// using Pathfinding; + /// using Pathfinding.ECS; + /// using Unity.Entities; + /// using Unity.Mathematics; + /// using Unity.Transforms; + /// using UnityEngine; + /// + /// public class MovementModifierNoise : MonoBehaviour { + /// /** How much noise to apply */ + /// public float strength = 1; + /// /** How fast the noise should change */ + /// public float frequency = 1; + /// float phase; + /// + /// public void Start () { + /// // Register a callback to modify the movement. + /// // This will be called during every simulation step for the agent. + /// // This may be called multiple times per frame if the time scale is high or fps is low, + /// // or less than once per frame, if the fps is very high. + /// GetComponent<FollowerEntity>().movementOverrides.AddBeforeControlCallback(MovementOverride); + /// + /// // Randomize a phase, to make different agents behave differently + /// phase = UnityEngine.Random.value * 1000; + /// } + /// + /// public void OnDisable () { + /// // Remove the callback when the component is disabled + /// GetComponent<FollowerEntity>().movementOverrides.RemoveBeforeControlCallback(MovementOverride); + /// } + /// + /// public void MovementOverride (Entity entity, float dt, ref LocalTransform localTransform, ref AgentCylinderShape shape, ref AgentMovementPlane movementPlane, ref DestinationPoint destination, ref MovementState movementState, ref MovementSettings movementSettings) { + /// // Rotate the next corner the agent is moving towards around the agent by a random angle. + /// // This will make the agent appear to move in a drunken fashion. + /// + /// // Don't modify the movement as much if we are very close to the end of the path + /// var strengthMultiplier = Mathf.Min(1, movementState.remainingDistanceToEndOfPart / Mathf.Max(shape.radius, movementSettings.follower.slowdownTime * movementSettings.follower.speed)); + /// strengthMultiplier *= strengthMultiplier; + /// + /// // Generate a smoothly varying rotation angle + /// var rotationAngleRad = strength * strengthMultiplier * (Mathf.PerlinNoise1D(Time.time * frequency + phase) - 0.5f); + /// // Clamp it to at most plus or minus 90 degrees + /// rotationAngleRad = Mathf.Clamp(rotationAngleRad, -math.PI*0.5f, math.PI*0.5f); + /// + /// // Convert the rotation angle to a world-space quaternion. + /// // We use the movement plane to rotate around the agent's up axis, + /// // making this code work in both 2D and 3D games. + /// var rotation = movementPlane.value.ToWorldRotation(rotationAngleRad); + /// + /// // Rotate the direction to the next corner around the agent + /// movementState.nextCorner = localTransform.Position + math.mul(rotation, movementState.nextCorner - localTransform.Position); + /// } + /// } + /// </code> + /// + /// There are a few different phases that you can register callbacks for: + /// + /// - BeforeControl: Called before the agent's movement is calculated. At this point, the agent has a valid path, and the next corner that is moving towards has been calculated. + /// - AfterControl: Called after the agent's desired movement is calculated. The agent has stored its desired movement in the <see cref="MovementControl"/> component. Local avoidance has not yet run. + /// - BeforeMovement: Called right before the agent's movement is applied. At this point the agent's final movement (including local avoidance) is stored in the <see cref="ResolvedMovement"/> component, which you may modify. + /// + /// Warning: If any agent has a callback registered here, a sync point will be created for all agents when the callback runs. + /// This can make the simulation not able to utilize multiple threads as effectively. If you have a lot of agents, consider using a custom entity component system instead. + /// But as always, profile first to see if this is actually a problem for your game. + /// + /// The callbacks may be called multiple times per frame, if the fps is low, or if the time scale is high. + /// It may also be called less than once per frame if the fps is very high. + /// Each callback is provided with a dt parameter, which is the time in seconds since the last simulation step. You should prefer using this instead of Time.deltaTime. + /// + /// See: <see cref="canMove"/> + /// See: <see cref="updatePosition"/> + /// See: <see cref="updateRotation"/> + /// + /// Note: This API is unstable. It may change in future versions. + /// </summary> + public ManagedMovementOverrides movementOverrides => new ManagedMovementOverrides(entity, World.DefaultGameObjectInjectionWorld); + + /// <summary>\copydoc Pathfinding::IAstarAI::FinalizeMovement</summary> + void IAstarAI.FinalizeMovement (Vector3 nextPosition, Quaternion nextRotation) { + throw new InvalidOperationException("The FollowerEntity component does not support FinalizeMovement. Use an ECS system to override movement instead, or use the movementOverrides property. If you just want to move the agent to a position, set ai.position or call ai.Teleport."); + } + + /// <summary> + /// Fills buffer with the remaining path. + /// + /// If the agent traverses off-mesh links, the buffer will still contain the whole path. Off-mesh links will be represented by a single line segment. + /// You can use the <see cref="GetRemainingPath(List<Vector3>,List<PathPartWithLinkInfo>,bool)"/> overload to get more detailed information about the different parts of the path. + /// + /// <code> + /// var buffer = new List<Vector3>(); + /// + /// ai.GetRemainingPath(buffer, out bool stale); + /// for (int i = 0; i < buffer.Count - 1; i++) { + /// Debug.DrawLine(buffer[i], buffer[i+1], Color.red); + /// } + /// </code> + /// [Open online documentation to see images] + /// </summary> + /// <param name="buffer">The buffer will be cleared and replaced with the path. The first point is the current position of the agent.</param> + /// <param name="stale">May be true if the path is invalid in some way. For example if the agent has no path or if the agent has detected that some nodes in the path have been destroyed.</param> + public void GetRemainingPath (List<Vector3> buffer, out bool stale) { + GetRemainingPath(buffer, null, out stale); + } + + /// <summary> + /// Fills buffer with the remaining path. + /// + /// <code> + /// var buffer = new List<Vector3>(); + /// var parts = new List<PathPartWithLinkInfo>(); + /// + /// ai.GetRemainingPath(buffer, parts, out bool stale); + /// foreach (var part in parts) { + /// for (int i = part.startIndex; i < part.endIndex; i++) { + /// Debug.DrawLine(buffer[i], buffer[i+1], part.type == Funnel.PartType.NodeSequence ? Color.red : Color.green); + /// } + /// } + /// </code> + /// [Open online documentation to see images] + /// + /// Note: The <see cref="FollowerEntity"/> simplifies its path continuously as it moves along it. This means that the agent may not follow this exact path, if it manages to simplify the path later. + /// Furthermore, the agent will apply a steering behavior on top of this path, to make its movement smoother. + /// </summary> + /// <param name="buffer">The buffer will be cleared and replaced with the path. The first point is the current position of the agent.</param> + /// <param name="partsBuffer">If not null, this list will be filled with information about the different parts of the path. A part is a sequence of nodes or an off-mesh link.</param> + /// <param name="stale">May be true if the path is invalid in some way. For example if the agent has no path or if the agent has detected that some nodes in the path have been destroyed.</param> + public void GetRemainingPath (List<Vector3> buffer, List<PathPartWithLinkInfo> partsBuffer, out bool stale) { + buffer.Clear(); + if (partsBuffer != null) partsBuffer.Clear(); + if (!entityExists) { + buffer.Add(position); + if (partsBuffer != null) partsBuffer.Add(new PathPartWithLinkInfo { startIndex = 0, endIndex = 0 }); + stale = true; + return; + } + + var ms = World.DefaultGameObjectInjectionWorld.EntityManager.GetComponentData<ManagedState>(entity); + stale = false; + if (ms.pathTracer.hasPath) { + var nativeBuffer = new NativeList<float3>(Allocator.Temp); + var scratch = new NativeArray<int>(8, Allocator.Temp); + ms.pathTracer.GetNextCorners(nativeBuffer, int.MaxValue, ref scratch, Allocator.Temp, ms.pathfindingSettings.traversalProvider, ms.activePath); + if (partsBuffer != null) partsBuffer.Add(new PathPartWithLinkInfo(0, nativeBuffer.Length - 1)); + + if (ms.pathTracer.partCount > 1) { + // There are more parts in the path. We need to create a new PathTracer to get the other parts. + // This can be comparatively expensive, since it needs to generate all the other types from scratch. + var pathTracer = ms.pathTracer.Clone(); + while (pathTracer.partCount > 1) { + pathTracer.PopParts(1, ms.pathfindingSettings.traversalProvider, ms.activePath); + var startIndex = nativeBuffer.Length; + if (pathTracer.GetPartType() == Funnel.PartType.NodeSequence) { + pathTracer.GetNextCorners(nativeBuffer, int.MaxValue, ref scratch, Allocator.Temp, ms.pathfindingSettings.traversalProvider, ms.activePath); + if (partsBuffer != null) partsBuffer.Add(new PathPartWithLinkInfo(startIndex, nativeBuffer.Length - 1)); + } else { + // If the link contains destroyed nodes, we cannot get a valid link object. + // In that case, we stop here and mark the path as stale. + if (pathTracer.PartContainsDestroyedNodes()) { + stale = true; + break; + } + // Note: startIndex will refer to the last point in the previous part, and endIndex will refer to the first point in the next part + Assert.IsTrue(startIndex > 0); + if (partsBuffer != null) partsBuffer.Add(new PathPartWithLinkInfo(startIndex - 1, startIndex, pathTracer.GetLinkInfo())); + } + // We need to check if the path is stale after each part because the path tracer may have realized that some nodes are destroyed + stale |= pathTracer.isStale; + } + } + + nativeBuffer.AsUnsafeSpan().Reinterpret<Vector3>().CopyTo(buffer); + } else { + buffer.Add(position); + if (partsBuffer != null) partsBuffer.Add(new PathPartWithLinkInfo { startIndex = 0, endIndex = 0 }); + } + stale |= ms.pathTracer.isStale; + } + + /// <summary>\copydoc Pathfinding::IAstarAI::Move</summary> + public void Move (Vector3 deltaPosition) { + position += deltaPosition; + } + + void IAstarAI.MovementUpdate (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation) { + throw new InvalidOperationException("The FollowerEntity component does not support MovementUpdate. Use an ECS system to override movement instead, or use the movementOverrides property"); + } + + /// <summary>\copydoc Pathfinding::IAstarAI::SearchPath</summary> + public void SearchPath () { + var dest = destination; + if (!float.IsFinite(dest.x)) return; + + SetPath(ABPath.Construct(position, dest, null), false); + } + + void AssertEntityExists () { + if (World.DefaultGameObjectInjectionWorld == null || !World.DefaultGameObjectInjectionWorld.EntityManager.Exists(entity)) throw new System.InvalidOperationException("Entity does not exist. You can only access this if the component is active and enabled."); + } + + /// <summary> + /// True if this component's entity exists. + /// + /// This is typically true if the component is active and enabled and the game is running. + /// + /// See: <see cref="entity"/> + /// </summary> + public bool entityExists => World.DefaultGameObjectInjectionWorld != null && World.DefaultGameObjectInjectionWorld.EntityManager.Exists(entity); + + void CancelCurrentPathRequest () { + if (entityExists) { + var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; + managedStateAccessRW.Update(entityManager); + managedState.CancelCurrentPathRequest(); + } + } + + void ClearPath() => ClearPath(entity); + + static void ClearPath (Entity entity) { + if (entityStorageCache.Update(World.DefaultGameObjectInjectionWorld, entity, out var entityManager, out var storage)) { + agentOffMeshLinkTraversalRO.Update(entityManager); + + if (agentOffMeshLinkTraversalRO.HasComponent(storage)) { + // Agent is traversing an off-mesh link. We must abort this link traversal. + var managedInfo = entityManager.GetComponentData<ManagedAgentOffMeshLinkTraversal>(entity); + if (managedInfo.stateMachine != null) managedInfo.stateMachine.OnAbortTraversingOffMeshLink(); + managedInfo.context.Restore(); + entityManager.RemoveComponent<AgentOffMeshLinkTraversal>(entity); + entityManager.RemoveComponent<ManagedAgentOffMeshLinkTraversal>(entity); + // We need to get the storage info again, because the entity will have been moved to another chunk + entityStorageCache.Update(World.DefaultGameObjectInjectionWorld, entity, out entityManager, out storage); + } + + entityManager.SetComponentEnabled<ReadyToTraverseOffMeshLink>(entity, false); + + managedStateAccessRW.Update(entityManager); + movementStateAccessRW.Update(entityManager); + localTransformAccessRO.Update(entityManager); + movementPlaneAccessRO.Update(entityManager); + resolvedMovementAccessRW.Update(entityManager); + movementControlAccessRW.Update(entityManager); + + ref var movementState = ref movementStateAccessRW[storage]; + ref var localTransform = ref localTransformAccessRO[storage]; + ref var movementPlane = ref movementPlaneAccessRO[storage]; + ref var resolvedMovement = ref resolvedMovementAccessRW[storage]; + ref var controlOutput = ref movementControlAccessRW[storage]; + var managedState = managedStateAccessRW[storage]; + + managedState.ClearPath(); + managedState.CancelCurrentPathRequest(); + movementState.SetPathIsEmpty(localTransform.Position); + + // This emulates what the ControlJob does when the agent has no path. + // This ensures that properties like #desiredVelocity return the correct value immediately after the path has been cleared. + resolvedMovement.targetPoint = localTransform.Position; + resolvedMovement.speed = 0; + resolvedMovement.targetRotation = movementPlane.value.ToPlane(localTransform.Rotation); + controlOutput.endOfPath = movementState.endOfPath; + controlOutput.speed = 0f; + controlOutput.targetPoint = localTransform.Position; + } + } + + /// <summary> + /// Make the AI follow the specified path. + /// + /// In case the path has not been calculated, the script will schedule the path to be calculated. + /// This means the AI may not actually start to follow the path until in a few frames when the path has been calculated. + /// The <see cref="pathPending"/> field will, as usual, return true while the path is being calculated. + /// + /// In case the path has already been calculated, it will immediately replace the current path the AI is following. + /// + /// If you pass null path, then the current path will be cleared and the agent will stop moving. + /// The agent will also abort traversing any off-mesh links it is currently traversing. + /// Note than unless you have also disabled <see cref="canSearch"/>, then the agent will soon recalculate its path and start moving again. + /// + /// Note: Stopping the agent by passing a null path works. But this will stop the agent instantly, and it will not be able to use local avoidance or know its place on the navmesh. + /// Usually it's better to set <see cref="isStopped"/> to false, which will make the agent slow down smoothly. + /// + /// You can disable the automatic path recalculation by setting the <see cref="canSearch"/> field to false. + /// + /// Note: This call will be ignored if the agent is currently traversing an off-mesh link. + /// Furthermore, if the agent starts traversing an off-mesh link, the current path request will be canceled (if one is currently in progress). + /// + /// <code> + /// IEnumerator Start () { + /// var pointToAvoid = enemy.position; + /// // Make the AI flee from an enemy. + /// // The path will be about 20 world units long (the default cost of moving 1 world unit is 1000). + /// var path = FleePath.Construct(ai.position, pointToAvoid, 1000 * 20); + /// ai.SetPath(path); + /// + /// while (!ai.reachedEndOfPath) { + /// yield return null; + /// } + /// } + /// </code> + /// </summary> + /// <param name="path">The path to follow.</param> + /// <param name="updateDestinationFromPath">If true, the \reflink{destination} property will be set to the end point of the path. If false, the previous destination value will be kept. + /// If you pass a path which has no well defined destination before it is calculated (e.g. a MultiTargetPath or RandomPath), then the destination will be first be cleared, but once the path has been calculated, it will be set to the end point of the path.</param> + public void SetPath(Path path, bool updateDestinationFromPath = true) => SetPath(entity, path, updateDestinationFromPath); + + /// <summary>\copydocref{SetPath(Path,bool)}</summary> + public static void SetPath (Entity entity, Path path, bool updateDestinationFromPath = true) { + var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; + if (!entityManager.Exists(entity)) throw new System.InvalidOperationException("Entity does not exist. You can only assign a path if the component is active and enabled."); + + managedStateAccessRW.Update(entityManager); + movementPlaneAccessRO.Update(entityManager); + agentOffMeshLinkTraversalRO.Update(entityManager); + movementStateAccessRW.Update(entityManager); + localTransformAccessRO.Update(entityManager); + destinationPointAccessRW.Update(entityManager); + + var storage = entityManager.GetStorageInfo(entity); + + bool isTraversingOffMeshLink = agentOffMeshLinkTraversalRO.HasComponent(storage); + if (isTraversingOffMeshLink) { + // Agent is traversing an off-mesh link. We ignore any path updates during this time. + // TODO: Race condition when adding off mesh link component? + // TODO: If passing null, should we clear the whole path after the off-mesh link? + return; + } + + if (path == null) { + ClearPath(entity); + return; + } + + var managedState = managedStateAccessRW[storage]; + ref var movementPlane = ref movementPlaneAccessRO[storage]; + ref var movementState = ref movementStateAccessRW[storage]; + ref var localTransform = ref localTransformAccessRO[storage]; + ref var destination = ref destinationPointAccessRW[storage]; + + if (updateDestinationFromPath && path is ABPath abPath) { + // If the user supplies a new ABPath manually, they probably want the agent to move to that point. + // So by default we update the destination to match the path. + if (abPath.endPointKnownBeforeCalculation) { + destination = new DestinationPoint { destination = abPath.originalEndPoint, facingDirection = default }; + } else { + // If the destination is not known, we set it to positive infinity. + // This is the case for MultiTargetPath and RandomPath, for example. + destination = new DestinationPoint { destination = Vector3.positiveInfinity, facingDirection = default }; + } + } + + ManagedState.SetPath(path, managedState, in movementPlane, ref destination); + + if (path.IsDone()) { + agentCylinderShapeAccessRO.Update(entityManager); + movementSettingsAccessRO.Update(entityManager); + readyToTraverseOffMeshLinkRW.Update(entityManager); + + // This remaining part ensures that the path tracer is fully up to date immediately after the path has been assigned. + // So that things like GetRemainingPath, and various properties like reachedDestination are up to date immediately. + managedState.pathTracer.UpdateStart(localTransform.Position, PathTracer.RepairQuality.High, movementPlane.value, managedState.pathfindingSettings.traversalProvider, managedState.activePath); + managedState.pathTracer.UpdateEnd(destination.destination, PathTracer.RepairQuality.High, movementPlane.value, managedState.pathfindingSettings.traversalProvider, managedState.activePath); + + if (movementState.pathTracerVersion != managedState.pathTracer.version) { + if (!nextCornersScratch.IsCreated) nextCornersScratch = new NativeList<float3>(4, Allocator.Persistent); + ref var shape = ref agentCylinderShapeAccessRO[storage]; + ref var movementSettings = ref movementSettingsAccessRO[storage]; + var readyToTraverseOffMeshLink = storage.Chunk.GetEnabledMask(ref readyToTraverseOffMeshLinkRW.handle).GetEnabledRefRW<ReadyToTraverseOffMeshLink>(storage.IndexInChunk); + JobRepairPath.Execute( + ref localTransform, + ref movementState, + ref shape, + ref movementPlane, + ref destination, + readyToTraverseOffMeshLink, + managedState, + in movementSettings, + nextCornersScratch, + ref indicesScratch, + Allocator.Persistent, + false + ); + } + } + } + + /// <summary> + /// Instantly move the agent to a new position. + /// + /// The current path will be cleared by default. + /// + /// This method is preferred for long distance teleports. If you only move the agent a very small distance (so that it is reasonable that it can keep its current path), + /// then setting the <see cref="position"/> property is preferred. + /// Setting the <see cref="position"/> property very far away from the agent could cause the agent to fail to move the full distance, as it can get blocked by the navmesh. + /// + /// See: Works similarly to Unity's NavmeshAgent.Warp. + /// See: <see cref="position"/> + /// See: <see cref="SearchPath"/> + /// </summary> + public void Teleport (Vector3 newPosition, bool clearPath = true) { + if (clearPath) ClearPath(); + + if (entityExists) { + var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; + movementOutputAccessRW.Update(entityManager); + managedStateAccessRW.Update(entityManager); + movementPlaneAccessRO.Update(entityManager); + var storage = entityManager.GetStorageInfo(entity); + ref var movementOutput = ref movementOutputAccessRW[storage]; + movementOutput.lastPosition = newPosition; + managedState.CancelCurrentPathRequest(); + if (AstarPath.active != null) { + // TODO: Should we use the from-above distance metric here? + // This would fail when used on a spherical world and the agent was teleported + // to another part of the sphere. + var nearest = AstarPath.active.GetNearest(newPosition, NNConstraint.Walkable); + if (nearest.node != null) { + var movementPlane = movementPlaneAccessRO[storage]; + managedState.pathTracer.SetFromSingleNode(nearest.node, nearest.position, movementPlane.value); + } + } + + // Note: Since we are starting from a completely new path, + // setting the position will also cause the path tracer to repair the destination. + // Therefore we don't have to also set the destination here. + position = newPosition; + } else { + position = newPosition; + } + } + + void FindComponents () { + tr = transform; + } + + static readonly Color ShapeGizmoColor = new Color(240/255f, 213/255f, 30/255f); + + public override void DrawGizmos () { + if (!Application.isPlaying || !enabled) FindComponents(); + + var color = ShapeGizmoColor; + var destination = this.destination; + var rotation = this.rotation; + var localScale = tr.localScale; + var radius = shape.radius * math.abs(localScale.x); + + if (orientation == OrientationMode.YAxisForward) { + Draw.Circle(position, rotation * Vector3.forward, radius, color); + } else { + Draw.WireCylinder(position, rotation * Vector3.up, localScale.y * shape.height, radius, color); + } + + if (!updateRotation) { + Draw.ArrowheadArc(position, rotation * Vector3.forward, radius * 1.05f, color); + } + + if (!float.IsPositiveInfinity(destination.x) && Application.isPlaying) { + var dir = destinationFacingDirection; + if (dir != Vector3.zero) { + Draw.xz.ArrowheadArc(destination, dir, 0.25f, Color.blue); + } + Draw.xz.Circle(destination, 0.2f, Color.blue); + } + } + + [System.Flags] + enum FollowerEntityMigrations { + MigratePathfindingSettings = 1 << 0, + MigrateMovementPlaneSource = 1 << 1, + MigrateAutoRepathPolicy = 1 << 2, + } + + protected override void OnUpgradeSerializedData (ref Serialization.Migrations migrations, bool unityThread) { + if (migrations.TryMigrateFromLegacyFormat(out var _legacyVersion)) { + // Only 1 version of the previous version format existed for this component + if (this.pathfindingSettings.tagPenalties.Length != 0) migrations.MarkMigrationFinished((int)FollowerEntityMigrations.MigratePathfindingSettings); + } + + if (migrations.AddAndMaybeRunMigration((int)FollowerEntityMigrations.MigratePathfindingSettings, unityThread)) { + if (TryGetComponent<Seeker>(out var seeker)) { + this.pathfindingSettings = new PathRequestSettings { + graphMask = seeker.graphMask, + traversableTags = seeker.traversableTags, + tagPenalties = seeker.tagPenalties, + }; + UnityEngine.Object.DestroyImmediate(seeker); + } else { + this.pathfindingSettings = PathRequestSettings.Default; + } + } + #pragma warning disable 618 + if (migrations.AddAndMaybeRunMigration((int)FollowerEntityMigrations.MigrateMovementPlaneSource, unityThread)) { + this.movementPlaneSource = this.movement.movementPlaneSource; + } + if (migrations.AddAndMaybeRunMigration((int)FollowerEntityMigrations.MigrateAutoRepathPolicy, unityThread)) { + this.autoRepathBacking = new ECS.AutoRepathPolicy(managedState.autoRepath); + } + #pragma warning restore 618 + } + +#if UNITY_EDITOR + /// <summary>\cond IGNORE_IN_DOCS</summary> + + /// <summary> + /// Copies all settings from this component to the entity's components. + /// + /// Note: This is an internal method and you should never need to use it yourself. + /// Typically it is used by the editor to keep the entity's state in sync with the component's state. + /// </summary> + public void SyncWithEntity () { + if (!entityStorageCache.Update(World.DefaultGameObjectInjectionWorld, entity, out var entityManager, out var storage)) return; + + this.position = this.position; + this.autoRepath = this.autoRepath; + movementSettingsAccessRW.Update(entityManager); + managedStateAccessRW.Update(entityManager); + agentCylinderShapeAccessRW.Update(entityManager); + + SyncWithEntity(managedStateAccessRW[storage], ref agentCylinderShapeAccessRW[storage], ref movementSettingsAccessRW[storage]); + + // Structural changes + ToggleComponent<GravityState>(entity, enableGravity, false); + ToggleComponent<OrientationYAxisForward>(entity, orientation == OrientationMode.YAxisForward, false); + this.movementPlaneSource = this.movementPlaneSource; + } + + /// <summary> + /// Copies all settings from this component to the entity's components. + /// + /// Note: This is an internal method and you should never need to use it yourself. + /// </summary> + public void SyncWithEntity (ManagedState managedState, ref AgentCylinderShape shape, ref MovementSettings movementSettings) { + movementSettings = this.movement; + shape = this.shape; + // Copy all fields to the managed state object. + // Don't copy the PathTracer or the onTraverseOffMeshLink, though, since they are not serialized + #pragma warning disable 618 + managedState.autoRepath = this.managedState.autoRepath; + #pragma warning restore 618 + managedState.rvoSettings = this.managedState.rvoSettings; + managedState.enableLocalAvoidance = this.managedState.enableLocalAvoidance; + // Replace this instance of the managed state with the entity component + this.managedState = managedState; + // Note: RVO settings are copied every frame automatically before local avoidance simulations + } + + static List<FollowerEntity> needsSyncWithEntityList = new List<FollowerEntity>(); + + void ISerializationCallbackReceiver.OnBeforeSerialize () {} + + void ISerializationCallbackReceiver.OnAfterDeserialize () { + UpgradeSerializedData(false); + + // This is (among other times) called after an undo or redo event has happened. + // In that case, the entity's state might be out of sync with this component's state, + // so we need to sync the two together. Unfortunately this method is called + // from Unity's separate serialization thread, so we cannot access the entity directly. + // Instead we add this component to a list and make sure to process them in the next + // editor update. + lock (needsSyncWithEntityList) { + needsSyncWithEntityList.Add(this); + if (needsSyncWithEntityList.Count == 1) { + UnityEditor.EditorApplication.update += SyncWithEntities; + } + } + } + + static void SyncWithEntities () { + lock (needsSyncWithEntityList) { + for (int i = 0; i < needsSyncWithEntityList.Count; i++) { + needsSyncWithEntityList[i].SyncWithEntity(); + } + needsSyncWithEntityList.Clear(); + UnityEditor.EditorApplication.update -= SyncWithEntities; + } + } + + /// <summary>\endcond</summary> +#endif + } +} +#else +namespace Pathfinding { + public sealed partial class FollowerEntity : VersionedMonoBehaviour { + public void Start () { + UnityEngine.Debug.LogError("The FollowerEntity component requires at least version 1.0 of the 'Entities' package to be installed. You can install it using the Unity package manager."); + } + + protected override void OnUpgradeSerializedData (ref Serialization.Migrations migrations, bool unityThread) { + // Since most of the code for this component is stripped out, we should just preserve the current state, + // and not try to migrate anything. + // If we don't do this, then the base code will log an error about an unknown migration already being done. + migrations.IgnoreMigrationAttempt(); + } + } +} +#endif diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/FollowerEntity.cs.meta b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/FollowerEntity.cs.meta new file mode 100644 index 0000000..6e40ab6 --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/FollowerEntity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cfe9431ea8ad072f2aecd3041b1524dd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: f2e81a0445323b64f973d2f5b5c56e15, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/IAstarAI.cs b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/IAstarAI.cs new file mode 100644 index 0000000..0c4395f --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/IAstarAI.cs @@ -0,0 +1,475 @@ +using UnityEngine; +using System.Collections.Generic; +using Pathfinding.Util; + +namespace Pathfinding { + /// <summary> + /// Common interface for all movement scripts in the A* Pathfinding Project. + /// See: <see cref="Pathfinding.AIPath"/> + /// See: <see cref="Pathfinding.RichAI"/> + /// See: <see cref="Pathfinding.AILerp"/> + /// </summary> + public interface IAstarAI { + /// <summary> + /// Radius of the agent in world units. + /// This is visualized in the scene view as a yellow cylinder around the character. + /// + /// Note that this does not affect pathfinding in any way. + /// The graph used completely determines where the agent can move. + /// + /// Note: The <see cref="Pathfinding.AILerp"/> script doesn't really have any use of knowing the radius or the height of the character, so this property will always return 0 in that script. + /// </summary> + float radius { get; set; } + + /// <summary> + /// Height of the agent in world units. + /// This is visualized in the scene view as a yellow cylinder around the character. + /// + /// This value is currently only used if an RVOController is attached to the same GameObject, otherwise it is only used for drawing nice gizmos in the scene view. + /// However since the height value is used for some things, the radius field is always visible for consistency and easier visualization of the character. + /// That said, it may be used for something in a future release. + /// + /// Note: The <see cref="Pathfinding.AILerp"/> script doesn't really have any use of knowing the radius or the height of the character, so this property will always return 0 in that script. + /// </summary> + float height { get; set; } + + /// <summary> + /// Position of the agent. + /// In world space. + /// See: <see cref="rotation"/> + /// + /// If you want to move the agent you may use <see cref="Teleport"/> or <see cref="Move"/>. + /// </summary> + Vector3 position { get; } + + /// <summary> + /// Rotation of the agent. + /// In world space. + /// See: <see cref="position"/> + /// </summary> + Quaternion rotation { get; set; } + + /// <summary>Max speed in world units per second</summary> + float maxSpeed { get; set; } + + /// <summary> + /// Actual velocity that the agent is moving with. + /// In world units per second. + /// + /// See: <see cref="desiredVelocity"/> + /// </summary> + Vector3 velocity { get; } + + /// <summary> + /// Velocity that this agent wants to move with. + /// Includes gravity and local avoidance if applicable. + /// In world units per second. + /// + /// See: <see cref="velocity"/> + /// + /// Note: The <see cref="Pathfinding.AILerp"/> movement script doesn't use local avoidance or gravity so this property will always be identical to <see cref="velocity"/> on that component. + /// </summary> + Vector3 desiredVelocity { get; } + + /// <summary> + /// Velocity that this agent wants to move with before taking local avoidance into account. + /// + /// Includes gravity. + /// In world units per second. + /// + /// Setting this property will set the current velocity that the agent is trying to move with, including gravity. + /// This can be useful if you want to make the agent come to a complete stop in a single frame or if you want to modify the velocity in some way. + /// + /// <code> + /// // Set the velocity to zero, but keep the current gravity + /// var newVelocity = new Vector3(0, ai.desiredVelocityWithoutLocalAvoidance.y, 0); + /// + /// ai.desiredVelocityWithoutLocalAvoidance = newVelocity; + /// </code> + /// + /// Note: The <see cref="Pathfinding.AILerp"/> movement script doesn't use local avoidance so this property will always be identical to <see cref="velocity"/> on that component. + /// + /// Warning: Trying to set this property on an AILerp component will throw an exception since its velocity cannot meaningfully be changed abitrarily. + /// + /// If you are not using local avoidance then this property will in almost all cases be identical to <see cref="desiredVelocity"/> plus some noise due to floating point math. + /// + /// See: <see cref="velocity"/> + /// See: <see cref="desiredVelocity"/> + /// See: <see cref="Move"/> + /// See: <see cref="MovementUpdate"/> + /// </summary> + Vector3 desiredVelocityWithoutLocalAvoidance { get; set; } + + /// <summary> + /// Approximate remaining distance along the current path to the end of the path. + /// The RichAI movement script approximates this distance since it is quite expensive to calculate the real distance. + /// However it will be accurate when the agent is within 1 corner of the destination. + /// You can use <see cref="GetRemainingPath"/> to calculate the actual remaining path more precisely. + /// + /// The AIPath and AILerp scripts use a more accurate distance calculation at all times. + /// + /// If the agent does not currently have a path, then positive infinity will be returned. + /// + /// Note: This is the distance to the end of the path, which may or may not be at the <see cref="destination"/>. If the character cannot reach the destination it will try to move as close as possible to it. + /// + /// Warning: Since path requests are asynchronous, there is a small delay between a path request being sent and this value being updated with the new calculated path. + /// + /// See: <see cref="reachedDestination"/> + /// See: <see cref="reachedEndOfPath"/> + /// See: <see cref="pathPending"/> + /// </summary> + float remainingDistance { get; } + + /// <summary> + /// True if the ai has reached the <see cref="destination"/>. + /// This is a best effort calculation to see if the <see cref="destination"/> has been reached. + /// For the AIPath/RichAI scripts, this is when the character is within <see cref="AIPath.endReachedDistance"/> world units from the <see cref="destination"/>. + /// For the AILerp script it is when the character is at the destination (±a very small margin). + /// + /// This value will be updated immediately when the <see cref="destination"/> is changed (in contrast to <see cref="reachedEndOfPath)"/>, however since path requests are asynchronous + /// it will use an approximation until it sees the real path result. What this property does is to check the distance to the end of the current path, and add to that the distance + /// from the end of the path to the <see cref="destination"/> (i.e. is assumes it is possible to move in a straight line between the end of the current path to the destination) and then checks if that total + /// distance is less than <see cref="AIPath.endReachedDistance"/>. This property is therefore only a best effort, but it will work well for almost all use cases. + /// + /// Furthermore it will not report that the destination is reached if the destination is above the head of the character or more than half the <see cref="height"/> of the character below its feet + /// (so if you have a multilevel building, it is important that you configure the <see cref="height"/> of the character correctly). + /// + /// The cases which could be problematic are if an agent is standing next to a very thin wall and the destination suddenly changes to the other side of that thin wall. + /// During the time that it takes for the path to be calculated the agent may see itself as alredy having reached the destination because the destination only moved a very small distance (the wall was thin), + /// even though it may actually be quite a long way around the wall to the other side. + /// + /// In contrast to <see cref="reachedEndOfPath"/>, this property is immediately updated when the <see cref="destination"/> is changed. + /// + /// <code> + /// IEnumerator Start () { + /// ai.destination = somePoint; + /// // Start to search for a path to the destination immediately + /// ai.SearchPath(); + /// // Wait until the agent has reached the destination + /// while (!ai.reachedDestination) { + /// yield return null; + /// } + /// // The agent has reached the destination now + /// } + /// </code> + /// + /// See: <see cref="AIPath.endReachedDistance"/> + /// See: <see cref="remainingDistance"/> + /// See: <see cref="reachedEndOfPath"/> + /// </summary> + bool reachedDestination { get; } + + /// <summary> + /// True if the agent has reached the end of the current path. + /// + /// Note that setting the <see cref="destination"/> does not immediately update the path, nor is there any guarantee that the + /// AI will actually be able to reach the destination that you set. The AI will try to get as close as possible. + /// Often you want to use <see cref="reachedDestination"/> instead which is easier to work with. + /// + /// It is very hard to provide a method for detecting if the AI has reached the <see cref="destination"/> that works across all different games + /// because the destination may not even lie on the navmesh and how that is handled differs from game to game (see also the code snippet in the docs for <see cref="destination"/>). + /// + /// See: <see cref="remainingDistance"/> + /// See: <see cref="reachedDestination"/> + /// </summary> + bool reachedEndOfPath { get; } + + /// <summary> + /// End point of path the agent is currently following. + /// If the agent has no path (or it might not be calculated yet), this will return the <see cref="destination"/> instead. + /// If the agent has no destination it will return the agent's current position. + /// + /// The end of the path is usually identical or very close to the <see cref="destination"/>, but it may differ + /// if the path for example was blocked by a wall so that the agent couldn't get any closer. + /// + /// This is only updated when the path is recalculated. + /// </summary> + Vector3 endOfPath { get; } + + /// <summary> + /// Position in the world that this agent should move to. + /// + /// If no destination has been set yet, then (+infinity, +infinity, +infinity) will be returned. + /// + /// Note that setting this property does not immediately cause the agent to recalculate its path. + /// So it may take some time before the agent starts to move towards this point. + /// Most movement scripts have a repathRate field which indicates how often the agent looks + /// for a new path. You can also call the <see cref="SearchPath"/> method to immediately + /// start to search for a new path. Paths are calculated asynchronously so when an agent starts to + /// search for path it may take a few frames (usually 1 or 2) until the result is available. + /// During this time the <see cref="pathPending"/> property will return true. + /// + /// If you are setting a destination and then want to know when the agent has reached that destination + /// then you could either use <see cref="reachedDestination"/> (recommended) or check both <see cref="pathPending"/> and <see cref="reachedEndOfPath"/>. + /// Check the documentation for the respective fields to learn about their differences. + /// + /// <code> + /// IEnumerator Start () { + /// ai.destination = somePoint; + /// // Start to search for a path to the destination immediately + /// ai.SearchPath(); + /// // Wait until the agent has reached the destination + /// while (!ai.reachedDestination) { + /// yield return null; + /// } + /// // The agent has reached the destination now + /// } + /// </code> + /// <code> + /// IEnumerator Start () { + /// ai.destination = somePoint; + /// // Start to search for a path to the destination immediately + /// // Note that the result may not become available until after a few frames + /// // ai.pathPending will be true while the path is being calculated + /// ai.SearchPath(); + /// // Wait until we know for sure that the agent has calculated a path to the destination we set above + /// while (ai.pathPending || !ai.reachedEndOfPath) { + /// yield return null; + /// } + /// // The agent has reached the destination now + /// } + /// </code> + /// </summary> + Vector3 destination { get; set; } + + /// <summary> + /// Enables or disables recalculating the path at regular intervals. + /// Setting this to false does not stop any active path requests from being calculated or stop it from continuing to follow the current path. + /// + /// Note that this only disables automatic path recalculations. If you call the <see cref="SearchPath()"/> method a path will still be calculated. + /// + /// See: <see cref="canMove"/> + /// See: <see cref="isStopped"/> + /// </summary> + bool canSearch { get; set; } + + /// <summary> + /// Enables or disables movement completely. + /// If you want the agent to stand still, but still react to local avoidance and use gravity: use <see cref="isStopped"/> instead. + /// + /// This is also useful if you want to have full control over when the movement calculations run. + /// Take a look at <see cref="MovementUpdate"/> + /// + /// See: <see cref="canSearch"/> + /// See: <see cref="isStopped"/> + /// </summary> + bool canMove { get; set; } + + /// <summary>True if this agent currently has a path that it follows</summary> + bool hasPath { get; } + + /// <summary>True if a path is currently being calculated</summary> + bool pathPending { get; } + + /// <summary> + /// Gets or sets if the agent should stop moving. + /// If this is set to true the agent will immediately start to slow down as quickly as it can to come to a full stop. + /// The agent will still react to local avoidance and gravity (if applicable), but it will not try to move in any particular direction. + /// + /// The current path of the agent will not be cleared, so when this is set + /// to false again the agent will continue moving along the previous path. + /// + /// This is a purely user-controlled parameter, so for example it is not set automatically when the agent stops + /// moving because it has reached the target. Use <see cref="reachedEndOfPath"/> for that. + /// + /// If this property is set to true while the agent is traversing an off-mesh link (RichAI script only), then the agent will + /// continue traversing the link and stop once it has completed it. + /// + /// Note: This is not the same as the <see cref="canMove"/> setting which some movement scripts have. The <see cref="canMove"/> setting + /// disables movement calculations completely (which among other things makes it not be affected by local avoidance or gravity). + /// For the AILerp movement script which doesn't use gravity or local avoidance anyway changing this property is very similar to + /// changing <see cref="canMove"/>. + /// + /// The <see cref="steeringTarget"/> property will continue to indicate the point which the agent would move towards if it would not be stopped. + /// </summary> + bool isStopped { get; set; } + + /// <summary> + /// Point on the path which the agent is currently moving towards. + /// This is usually a point a small distance ahead of the agent + /// or the end of the path. + /// + /// If the agent does not have a path at the moment, then the agent's current position will be returned. + /// </summary> + Vector3 steeringTarget { get; } + + /// <summary> + /// Called when the agent recalculates its path. + /// This is called both for automatic path recalculations (see <see cref="canSearch)"/> and manual ones (see <see cref="SearchPath)"/>. + /// + /// See: Take a look at the <see cref="Pathfinding.AIDestinationSetter"/> source code for an example of how it can be used. + /// </summary> + System.Action onSearchPath { get; set; } + + /// <summary> + /// The plane the agent is moving in. + /// + /// This is typically the ground plane, which will be the XZ plane in a 3D game, and the XY plane in a 2D game. + /// Ultimately it depends on the graph orientation. + /// + /// If you are doing pathfinding on a spherical world (see spherical) (view in online documentation for working links), the the movement plane will be the tangent plane of the sphere at the agent's position. + /// </summary> + NativeMovementPlane movementPlane { get; } + /// <summary> + /// Fills buffer with the remaining path. + /// + /// <code> + /// var buffer = new List<Vector3>(); + /// + /// ai.GetRemainingPath(buffer, out bool stale); + /// for (int i = 0; i < buffer.Count - 1; i++) { + /// Debug.DrawLine(buffer[i], buffer[i+1], Color.red); + /// } + /// </code> + /// [Open online documentation to see images] + /// </summary> + /// <param name="buffer">The buffer will be cleared and replaced with the path. The first point is the current position of the agent.</param> + /// <param name="stale">May be true if the path is invalid in some way. For example if the agent has no path or (for the RichAI/FollowerEntity components only) if the agent has detected that some nodes in the path have been destroyed.</param> + void GetRemainingPath(List<Vector3> buffer, out bool stale); + + /// <summary> + /// Fills buffer with the remaining path. + /// + /// <code> + /// var buffer = new List<Vector3>(); + /// var parts = new List<PathPartWithLinkInfo>(); + /// + /// ai.GetRemainingPath(buffer, parts, out bool stale); + /// foreach (var part in parts) { + /// for (int i = part.startIndex; i < part.endIndex; i++) { + /// Debug.DrawLine(buffer[i], buffer[i+1], part.type == Funnel.PartType.NodeSequence ? Color.red : Color.green); + /// } + /// } + /// </code> + /// [Open online documentation to see images] + /// + /// Note: The <see cref="AIPath"/> and <see cref="AILerp"/> movement scripts do not know about off-mesh links, so the partsBuffer will always be filled with a single node-sequence part. + /// </summary> + /// <param name="buffer">The buffer will be cleared and replaced with the path. The first point is the current position of the agent.</param> + /// <param name="partsBuffer">If not null, this list will be cleared and filled with information about the different parts of the path. A part is a sequence of nodes or an off-mesh link.</param> + /// <param name="stale">May be true if the path is invalid in some way. For example if the agent has no path or (for the RichAI/FollowerEntity components only) if the agent has detected that some nodes in the path have been destroyed.</param> + void GetRemainingPath(List<Vector3> buffer, List<PathPartWithLinkInfo> partsBuffer, out bool stale); + + /// <summary> + /// Recalculate the current path. + /// You can for example use this if you want very quick reaction times when you have changed the <see cref="destination"/> + /// so that the agent does not have to wait until the next automatic path recalculation (see <see cref="canSearch)"/>. + /// + /// If there is an ongoing path calculation, it will be canceled, so make sure you leave time for the paths to get calculated before calling this function again. + /// A canceled path will show up in the log with the message "Canceled by script" (see <see cref="Seeker.CancelCurrentPathRequest"/>). + /// + /// If no <see cref="destination"/> has been set yet then nothing will be done. + /// + /// Note: The path result may not become available until after a few frames. + /// During the calculation time the <see cref="pathPending"/> property will return true. + /// + /// See: <see cref="pathPending"/> + /// </summary> + void SearchPath(); + + /// <summary> + /// Make the AI follow the specified path. + /// + /// In case the path has not been calculated, the script will call seeker.StartPath to calculate it. + /// This means the AI may not actually start to follow the path until in a few frames when the path has been calculated. + /// The <see cref="pathPending"/> field will as usual return true while the path is being calculated. + /// + /// In case the path has already been calculated it will immediately replace the current path the AI is following. + /// This is useful if you want to replace how the AI calculates its paths. + /// + /// If you pass null as a parameter then the current path will be cleared and the agent will stop moving. + /// Note than unless you have also disabled <see cref="canSearch"/> then the agent will soon recalculate its path and start moving again. + /// + /// You can disable the automatic path recalculation by setting the <see cref="canSearch"/> field to false. + /// + /// Note: This call will be ignored if the agent is currently traversing an off-mesh link. Furthermore, if the agent starts traversing an off-mesh link, the current path request will be canceled (if one is currently in progress). + /// + /// <code> + /// // Disable the automatic path recalculation + /// ai.canSearch = false; + /// var pointToAvoid = enemy.position; + /// // Make the AI flee from the enemy. + /// // The path will be about 20 world units long (the default cost of moving 1 world unit is 1000). + /// var path = FleePath.Construct(ai.position, pointToAvoid, 1000 * 20); + /// ai.SetPath(path); + /// </code> + /// </summary> + /// <param name="path">The path to follow.</param> + /// <param name="updateDestinationFromPath">If true, the \reflink{destination} property will be set to the end point of the path. If false, the previous destination value will be kept.</param> + void SetPath(Path path, bool updateDestinationFromPath = true); + + /// <summary> + /// Instantly move the agent to a new position. + /// This will trigger a path recalculation (if clearPath is true, which is the default) so if you want to teleport the agent and change its <see cref="destination"/> + /// it is recommended that you set the <see cref="destination"/> before calling this method. + /// + /// The current path will be cleared by default. + /// + /// This method is preferred for long distance teleports. If you only move the agent a very small distance (so that it is reasonable that it can keep its current path), + /// then setting the <see cref="position"/> property is preferred. + /// When using the <see cref="FollowerEntity"/> movement script, setting the <see cref="position"/> property when using a long distance teleport could cause the agent to fail to move the full distance, as it can get blocked by the navmesh. + /// + /// See: Works similarly to Unity's NavmeshAgent.Warp. + /// See: <see cref="SearchPath"/> + /// </summary> + void Teleport(Vector3 newPosition, bool clearPath = true); + + /// <summary> + /// Move the agent. + /// + /// This is intended for external movement forces such as those applied by wind, conveyor belts, knockbacks etc. + /// + /// Some movement scripts may ignore this completely (notably the <see cref="AILerp"/> script) if it does not have + /// any concept of being moved externally. + /// + /// For the <see cref="AIPath"/> and <see cref="RichAI"/> movement scripts, the agent will not be moved immediately when calling this method. Instead this offset will be stored and then + /// applied the next time the agent runs its movement calculations (which is usually later this frame or the next frame). + /// If you want to move the agent immediately then call: + /// <code> + /// ai.Move(someVector); + /// ai.FinalizeMovement(ai.position, ai.rotation); + /// </code> + /// + /// The <see cref="FollowerEntity"/> movement script will, on the other hand, move the agent immediately. + /// </summary> + /// <param name="deltaPosition">Direction and distance to move the agent in world space.</param> + void Move(Vector3 deltaPosition); + + /// <summary> + /// Calculate how the character wants to move during this frame. + /// + /// Note that this does not actually move the character. You need to call <see cref="FinalizeMovement"/> for that. + /// This is called automatically unless <see cref="canMove"/> is false. + /// + /// To handle movement yourself you can disable <see cref="canMove"/> and call this method manually. + /// This code will replicate the normal behavior of the component: + /// <code> + /// void Update () { + /// // Disable the AIs own movement code + /// ai.canMove = false; + /// Vector3 nextPosition; + /// Quaternion nextRotation; + /// // Calculate how the AI wants to move + /// ai.MovementUpdate(Time.deltaTime, out nextPosition, out nextRotation); + /// // Modify nextPosition and nextRotation in any way you wish + /// // Actually move the AI + /// ai.FinalizeMovement(nextPosition, nextRotation); + /// } + /// </code> + /// </summary> + /// <param name="deltaTime">time to simulate movement for. Usually set to Time.deltaTime.</param> + /// <param name="nextPosition">the position that the agent wants to move to during this frame.</param> + /// <param name="nextRotation">the rotation that the agent wants to rotate to during this frame.</param> + void MovementUpdate(float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation); + + /// <summary> + /// Move the agent. + /// To be called as the last step when you are handling movement manually. + /// + /// The movement will be clamped to the navmesh if applicable (this is done for the RichAI movement script). + /// + /// See: <see cref="MovementUpdate"/> for a code example. + /// </summary> + void FinalizeMovement(Vector3 nextPosition, Quaternion nextRotation); + } +} diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/IAstarAI.cs.meta b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/IAstarAI.cs.meta new file mode 100644 index 0000000..b7106e3 --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/IAstarAI.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b7438f3f6b9404f05ab7f584f92aa7d5 +timeCreated: 1495013922 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/LocalSpaceRichAI.cs b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/LocalSpaceRichAI.cs new file mode 100644 index 0000000..076f8a4 --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/LocalSpaceRichAI.cs @@ -0,0 +1,73 @@ +using UnityEngine; +namespace Pathfinding.Examples { + using Pathfinding.Util; + + /// <summary> + /// RichAI for local space (pathfinding on moving graphs). + /// + /// What this script does is that it fakes graph movement. + /// It can be seen in the example scene called 'Moving' where + /// a character is pathfinding on top of a moving ship. + /// The graph does not actually move in that example + /// instead there is some 'cheating' going on. + /// + /// When requesting a path, we first transform + /// the start and end positions of the path request + /// into local space for the object we are moving on + /// (e.g the ship in the example scene), then when we get the + /// path back, they will still be in these local coordinates. + /// When following the path, we will every frame transform + /// the coordinates of the waypoints in the path to global + /// coordinates so that we can follow them. + /// + /// At the start of the game (when the graph is scanned) the + /// object we are moving on should be at a valid position on the graph and + /// you should attach the <see cref="Pathfinding.LocalSpaceGraph"/> component to it. The <see cref="Pathfinding.LocalSpaceGraph"/> + /// component will store the position and orientation of the object right there are the start + /// and then we can use that information to transform coordinates back to that region of the graph + /// as if the object had not moved at all. + /// + /// This functionality is only implemented for the RichAI + /// script, however it should not be hard to + /// use the same approach for other movement scripts. + /// </summary> + [HelpURL("https://arongranberg.com/astar/documentation/stable/localspacerichai.html")] + public class LocalSpaceRichAI : RichAI { + /// <summary>Root of the object we are moving on</summary> + public LocalSpaceGraph graph; + + protected override Vector3 ClampPositionToGraph (Vector3 newPosition) { + RefreshTransform(); + // Clamp the new position to the navmesh + // First we need to transform the position to the same space that the graph is in though. + var nearest = AstarPath.active != null? AstarPath.active.GetNearest(graph.transformation.InverseTransform(newPosition)) : new NNInfo(); + float elevation; + + movementPlane.ToPlane(newPosition, out elevation); + return movementPlane.ToWorld(movementPlane.ToPlane(nearest.node != null ? graph.transformation.Transform(nearest.position) : newPosition), elevation); + } + + void RefreshTransform () { + graph.Refresh(); + richPath.transform = graph.transformation; + movementPlane = graph.transformation.ToSimpleMovementPlane(); + } + + protected override void Start () { + RefreshTransform(); + base.Start(); + } + + protected override void CalculatePathRequestEndpoints (out Vector3 start, out Vector3 end) { + RefreshTransform(); + base.CalculatePathRequestEndpoints(out start, out end); + start = graph.transformation.InverseTransform(start); + end = graph.transformation.InverseTransform(end); + } + + protected override void OnUpdate (float dt) { + RefreshTransform(); + base.OnUpdate(dt); + } + } +} diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/LocalSpaceRichAI.cs.meta b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/LocalSpaceRichAI.cs.meta new file mode 100644 index 0000000..0c09569 --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/LocalSpaceRichAI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e342e9f54c9d04f05b77eff70a36605e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: f2e81a0445323b64f973d2f5b5c56e15, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/RichAI.cs b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/RichAI.cs new file mode 100644 index 0000000..e955115 --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/RichAI.cs @@ -0,0 +1,645 @@ +using UnityEngine; +using System.Collections; +using System.Collections.Generic; + +namespace Pathfinding { + using Pathfinding.RVO; + using Pathfinding.Util; + using Pathfinding.Drawing; + + [AddComponentMenu("Pathfinding/AI/RichAI (3D, for navmesh)")] + [UniqueComponent(tag = "ai")] + /// <summary> + /// Advanced AI for navmesh based graphs. + /// + /// See: movementscripts (view in online documentation for working links) + /// </summary> + public partial class RichAI : AIBase, IAstarAI { + /// <summary> + /// Max acceleration of the agent. + /// In world units per second per second. + /// </summary> + public float acceleration = 5; + + /// <summary> + /// Max rotation speed of the agent. + /// In degrees per second. + /// </summary> + public float rotationSpeed = 360; + + /// <summary> + /// How long before reaching the end of the path to start to slow down. + /// A lower value will make the agent stop more abruptly. + /// + /// Note: The agent may require more time to slow down if + /// its maximum <see cref="acceleration"/> is not high enough. + /// + /// If set to zero the agent will not even attempt to slow down. + /// This can be useful if the target point is not a point you want the agent to stop at + /// but it might for example be the player and you want the AI to slam into the player. + /// + /// Note: A value of zero will behave differently from a small but non-zero value (such as 0.0001). + /// When it is non-zero the agent will still respect its <see cref="acceleration"/> when determining if it needs + /// to slow down, but if it is zero it will disable that check. + /// This is useful if the <see cref="destination"/> is not a point where you want the agent to stop. + /// + /// \htmlonly <video class="tinyshadow" controls="true" loop="true"><source src="images/richai_slowdown_time.mp4" type="video/mp4" /></video> \endhtmlonly + /// </summary> + public float slowdownTime = 0.5f; + + /// <summary> + /// Force to avoid walls with. + /// The agent will try to steer away from walls slightly. + /// + /// See: <see cref="wallDist"/> + /// </summary> + public float wallForce = 3; + + /// <summary> + /// Walls within this range will be used for avoidance. + /// Setting this to zero disables wall avoidance and may improve performance slightly + /// + /// See: <see cref="wallForce"/> + /// </summary> + public float wallDist = 1; + + /// <summary> + /// Use funnel simplification. + /// On tiled navmesh maps, but sometimes on normal ones as well, it can be good to simplify + /// the funnel as a post-processing step to make the paths straighter. + /// + /// This has a moderate performance impact during frames when a path calculation is completed. + /// + /// The RichAI script uses its own internal funnel algorithm, so you never + /// need to attach the FunnelModifier component. + /// + /// [Open online documentation to see images] + /// + /// See: <see cref="Pathfinding.FunnelModifier"/> + /// </summary> + public bool funnelSimplification = false; + + /// <summary> + /// Slow down when not facing the target direction. + /// Incurs at a small performance overhead. + /// + /// This setting only has an effect if <see cref="enableRotation"/> is enabled. + /// </summary> + public bool slowWhenNotFacingTarget = true; + + /// <summary> + /// Prevent the velocity from being too far away from the forward direction of the character. + /// If the character is ordered to move in the opposite direction from where it is facing + /// then enabling this will cause it to make a small loop instead of turning on the spot. + /// + /// This setting only has an effect if <see cref="slowWhenNotFacingTarget"/> is enabled. + /// </summary> + public bool preventMovingBackwards = false; + + /// <summary> + /// Called when the agent starts to traverse an off-mesh link. + /// Register to this callback to handle off-mesh links in a custom way. + /// + /// If this event is set to null then the agent will fall back to traversing + /// off-mesh links using a very simple linear interpolation. + /// + /// <code> + /// void OnEnable () { + /// ai = GetComponent<RichAI>(); + /// if (ai != null) ai.onTraverseOffMeshLink += TraverseOffMeshLink; + /// } + /// + /// void OnDisable () { + /// if (ai != null) ai.onTraverseOffMeshLink -= TraverseOffMeshLink; + /// } + /// + /// IEnumerator TraverseOffMeshLink (RichSpecial link) { + /// // Traverse the link over 1 second + /// float startTime = Time.time; + /// + /// while (Time.time < startTime + 1) { + /// transform.position = Vector3.Lerp(link.first.position, link.second.position, Time.time - startTime); + /// yield return null; + /// } + /// transform.position = link.second.position; + /// } + /// </code> + /// </summary> + public System.Func<RichSpecial, IEnumerator> onTraverseOffMeshLink; + + /// <summary>Holds the current path that this agent is following</summary> + protected readonly RichPath richPath = new RichPath(); + + protected bool delayUpdatePath; + protected bool lastCorner; + + /// <summary>Internal state used for filtering out noise in the agent's rotation</summary> + Vector2 rotationFilterState; + Vector2 rotationFilterState2; + + /// <summary>Distance to <see cref="steeringTarget"/> in the movement plane</summary> + protected float distanceToSteeringTarget = float.PositiveInfinity; + + protected readonly List<Vector3> nextCorners = new List<Vector3>(); + protected readonly List<Vector3> wallBuffer = new List<Vector3>(); + + public bool traversingOffMeshLink { get; protected set; } + + /// <summary>\copydoc Pathfinding::IAstarAI::remainingDistance</summary> + public float remainingDistance { + get { + return distanceToSteeringTarget + Vector3.Distance(steeringTarget, richPath.Endpoint); + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::reachedEndOfPath</summary> + public bool reachedEndOfPath { get { return approachingPathEndpoint && distanceToSteeringTarget < endReachedDistance; } } + + /// <summary>\copydoc Pathfinding::IAstarAI::reachedDestination</summary> + public override bool reachedDestination { + get { + if (!reachedEndOfPath) return false; + // Distance from our position to the current steering target + + // Distance from the steering target to the end of the path + + // distance from the end of the path to the destination. + // Note that most distance checks are done only in the movement plane (which means in most cases that the y coordinate differences are discarded). + // This is because those coordinates are often not very accurate. + // A separate check is done below to make sure that the destination y coordinate is correct + if (distanceToSteeringTarget + movementPlane.ToPlane(steeringTarget - richPath.Endpoint).magnitude + movementPlane.ToPlane(destination - richPath.Endpoint).magnitude > endReachedDistance) return false; + + // Don't do height checks in 2D mode + if (orientation != OrientationMode.YAxisForward) { + // Check if the destination is above the head of the character or far below the feet of it + float yDifference; + movementPlane.ToPlane(destination - position, out yDifference); + var h = tr.localScale.y * height; + if (yDifference > h || yDifference < -h*0.5) return false; + } + + return true; + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::hasPath</summary> + public bool hasPath { get { return richPath.GetCurrentPart() != null; } } + + /// <summary>\copydoc Pathfinding::IAstarAI::pathPending</summary> + public bool pathPending { get { return waitingForPathCalculation || delayUpdatePath; } } + + /// <summary>\copydoc Pathfinding::IAstarAI::steeringTarget</summary> + public Vector3 steeringTarget { get; protected set; } + + /// <summary>\copydoc Pathfinding::IAstarAI::radius</summary> + float IAstarAI.radius { get { return radius; } set { radius = value; } } + + /// <summary>\copydoc Pathfinding::IAstarAI::height</summary> + float IAstarAI.height { get { return height; } set { height = value; } } + + /// <summary>\copydoc Pathfinding::IAstarAI::maxSpeed</summary> + float IAstarAI.maxSpeed { get { return maxSpeed; } set { maxSpeed = value; } } + + /// <summary>\copydoc Pathfinding::IAstarAI::canSearch</summary> + bool IAstarAI.canSearch { get { return canSearch; } set { canSearch = value; } } + + /// <summary>\copydoc Pathfinding::IAstarAI::canMove</summary> + bool IAstarAI.canMove { get { return canMove; } set { canMove = value; } } + + /// <summary>\copydoc Pathfinding::IAstarAI::movementPlane</summary> + NativeMovementPlane IAstarAI.movementPlane => new NativeMovementPlane(movementPlane); + + /// <summary> + /// True if approaching the last waypoint in the current part of the path. + /// Path parts are separated by off-mesh links. + /// + /// See: <see cref="approachingPathEndpoint"/> + /// </summary> + public bool approachingPartEndpoint { + get { + return lastCorner && nextCorners.Count == 1; + } + } + + /// <summary> + /// True if approaching the last waypoint of all parts in the current path. + /// Path parts are separated by off-mesh links. + /// + /// See: <see cref="approachingPartEndpoint"/> + /// </summary> + public bool approachingPathEndpoint { + get { + return approachingPartEndpoint && richPath.IsLastPart; + } + } + + /// <summary>\copydoc Pathfinding::IAstarAI::endOfPath</summary> + public override Vector3 endOfPath { + get { + if (hasPath) return richPath.Endpoint; + if (float.IsFinite(destination.x)) return destination; + return position; + } + } + + public override Quaternion rotation { + get { + return base.rotation; + } + set { + base.rotation = value; + // Make the agent keep this rotation instead of just rotating back to whatever it used before + rotationFilterState = Vector2.zero; + rotationFilterState2 = Vector2.zero; + } + } + + /// <summary> + /// \copydoc Pathfinding::IAstarAI::Teleport + /// + /// When setting transform.position directly the agent + /// will be clamped to the part of the navmesh it can + /// reach, so it may not end up where you wanted it to. + /// This ensures that the agent can move to any part of the navmesh. + /// </summary> + public override void Teleport (Vector3 newPosition, bool clearPath = true) { + base.Teleport(ClampPositionToGraph(newPosition), clearPath); + } + + protected virtual Vector3 ClampPositionToGraph (Vector3 newPosition) { + // Clamp the new position to the navmesh + var nearest = AstarPath.active != null? AstarPath.active.GetNearest(newPosition) : new NNInfo(); + float elevation; + + movementPlane.ToPlane(newPosition, out elevation); + return movementPlane.ToWorld(movementPlane.ToPlane(nearest.node != null ? nearest.position : newPosition), elevation); + } + + /// <summary>Called when the component is disabled</summary> + protected override void OnDisable () { + base.OnDisable(); + traversingOffMeshLink = false; + // Stop the off mesh link traversal coroutine + StopAllCoroutines(); + rotationFilterState = Vector2.zero; + rotationFilterState2 = Vector2.zero; + } + + protected override bool shouldRecalculatePath { + get { + // Don't automatically recalculate the path in the middle of an off-mesh link + return base.shouldRecalculatePath && !traversingOffMeshLink; + } + } + + public override void SearchPath () { + // Calculate paths after the current off-mesh link has been completed + if (traversingOffMeshLink) { + delayUpdatePath = true; + } else { + base.SearchPath(); + } + } + + protected override void OnPathComplete (Path p) { + waitingForPathCalculation = false; + p.Claim(this); + + if (p.error) { + p.Release(this); + return; + } + + if (traversingOffMeshLink) { + delayUpdatePath = true; + } else { + // The RandomPath and MultiTargetPath do not have a well defined destination that could have been + // set before the paths were calculated. So we instead set the destination here so that some properties + // like #reachedDestination and #remainingDistance work correctly. + if (p is ABPath abPath && !abPath.endPointKnownBeforeCalculation) { + destination = abPath.originalEndPoint; + } + + richPath.Initialize(seeker, p, true, funnelSimplification); + + // Check if we have already reached the end of the path + // We need to do this here to make sure that the #reachedEndOfPath + // property is up to date. + var part = richPath.GetCurrentPart() as RichFunnel; + if (part != null) { + if (updatePosition) simulatedPosition = tr.position; + + // Note: UpdateTarget has some side effects like setting the nextCorners list and the lastCorner field + var localPosition = movementPlane.ToPlane(UpdateTarget(part)); + + // Target point + steeringTarget = nextCorners[0]; + Vector2 targetPoint = movementPlane.ToPlane(steeringTarget); + distanceToSteeringTarget = (targetPoint - localPosition).magnitude; + + if (lastCorner && nextCorners.Count == 1 && distanceToSteeringTarget <= endReachedDistance) { + NextPart(); + } + } + } + p.Release(this); + } + + protected override void ClearPath () { + CancelCurrentPathRequest(); + richPath.Clear(); + lastCorner = false; + delayUpdatePath = false; + distanceToSteeringTarget = float.PositiveInfinity; + } + + /// <summary> + /// Declare that the AI has completely traversed the current part. + /// This will skip to the next part, or call OnTargetReached if this was the last part + /// </summary> + protected void NextPart () { + if (!richPath.CompletedAllParts) { + if (!richPath.IsLastPart) lastCorner = false; + richPath.NextPart(); + if (richPath.CompletedAllParts) { + OnTargetReached(); + } + } + } + + /// <summary>\copydocref{IAstarAI.GetRemainingPath(List<Vector3>,bool)}</summary> + public void GetRemainingPath (List<Vector3> buffer, out bool stale) { + richPath.GetRemainingPath(buffer, null, simulatedPosition, out stale); + } + + /// <summary>\copydocref{IAstarAI.GetRemainingPath(List<Vector3>,List<PathPartWithLinkInfo>,bool)}</summary> + public void GetRemainingPath (List<Vector3> buffer, List<PathPartWithLinkInfo> partsBuffer, out bool stale) { + richPath.GetRemainingPath(buffer, partsBuffer, simulatedPosition, out stale); + } + + /// <summary> + /// Called when the end of the path is reached. + /// + /// Deprecated: Avoid overriding this method. Instead poll the <see cref="reachedDestination"/> or <see cref="reachedEndOfPath"/> properties. + /// </summary> + protected virtual void OnTargetReached () { + } + + protected virtual Vector3 UpdateTarget (RichFunnel fn) { + nextCorners.Clear(); + + // This method assumes simulatedPosition is up to date as our current position. + // We read and write to tr.position as few times as possible since doing so + // is much slower than to read and write from/to a local/member variable. + bool requiresRepath; + Vector3 position = fn.Update(simulatedPosition, nextCorners, 2, out lastCorner, out requiresRepath); + + if (requiresRepath && !waitingForPathCalculation && canSearch) { + // TODO: What if canSearch is false? How do we notify other scripts that might be handling the path calculation that a new path needs to be calculated? + SearchPath(); + } + + return position; + } + + /// <summary>Called during either Update or FixedUpdate depending on if rigidbodies are used for movement or not</summary> + protected override void MovementUpdateInternal (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation) { + if (updatePosition) simulatedPosition = tr.position; + if (updateRotation) simulatedRotation = tr.rotation; + + RichPathPart currentPart = richPath.GetCurrentPart(); + + if (currentPart is RichSpecial) { + // Start traversing the off mesh link if we haven't done it yet + if (!traversingOffMeshLink && !richPath.CompletedAllParts) { + StartCoroutine(TraverseSpecial(currentPart as RichSpecial)); + } + + nextPosition = steeringTarget = simulatedPosition; + nextRotation = rotation; + } else { + var funnel = currentPart as RichFunnel; + + // Check if we have a valid path to follow and some other script has not stopped the character + bool stopped = isStopped || (reachedDestination && whenCloseToDestination == CloseToDestinationMode.Stop); + if (rvoController != null) rvoDensityBehavior.Update(rvoController.enabled, reachedDestination, ref stopped, ref rvoController.priorityMultiplier, ref rvoController.flowFollowingStrength, simulatedPosition); + + if (funnel != null && !stopped) { + TraverseFunnel(funnel, deltaTime, out nextPosition, out nextRotation); + } else { + // Unknown, null path part, or the character is stopped + // Slow down as quickly as possible + velocity2D -= Vector2.ClampMagnitude(velocity2D, acceleration * deltaTime); + FinalMovement(simulatedPosition, deltaTime, float.PositiveInfinity, 1f, out nextPosition, out nextRotation); + if (funnel == null || isStopped) { + steeringTarget = simulatedPosition; + } + } + } + } + + void TraverseFunnel (RichFunnel fn, float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation) { + // Clamp the current position to the navmesh + // and update the list of upcoming corners in the path + // and store that in the 'nextCorners' field + var position3D = UpdateTarget(fn); + float elevation; + Vector2 position = movementPlane.ToPlane(position3D, out elevation); + + // Only find nearby walls every 5th frame to improve performance + if (Time.frameCount % 5 == 0 && wallForce > 0 && wallDist > 0) { + wallBuffer.Clear(); + fn.FindWalls(wallBuffer, wallDist); + } + + // Target point + steeringTarget = nextCorners[0]; + Vector2 targetPoint = movementPlane.ToPlane(steeringTarget); + // Direction to target + Vector2 dir = targetPoint - position; + + // Normalized direction to the target + Vector2 normdir = VectorMath.Normalize(dir, out distanceToSteeringTarget); + // Calculate force from walls + Vector2 wallForceVector = CalculateWallForce(position, elevation, normdir); + Vector2 targetVelocity; + + if (approachingPartEndpoint) { + targetVelocity = slowdownTime > 0 ? Vector2.zero : normdir * maxSpeed; + + // Reduce the wall avoidance force as we get closer to our target + wallForceVector *= System.Math.Min(distanceToSteeringTarget/0.5f, 1); + + if (distanceToSteeringTarget <= endReachedDistance) { + // Reached the end of the path or an off mesh link + NextPart(); + } + } else { + var nextNextCorner = nextCorners.Count > 1 ? movementPlane.ToPlane(nextCorners[1]) : position + 2*dir; + targetVelocity = (nextNextCorner - targetPoint).normalized * maxSpeed; + } + + var forwards = movementPlane.ToPlane(simulatedRotation * (orientation == OrientationMode.YAxisForward ? Vector3.up : Vector3.forward)); + + // Update the velocity using the acceleration + Vector2 accel = MovementUtilities.CalculateAccelerationToReachPoint(targetPoint - position, targetVelocity, velocity2D, acceleration, rotationSpeed, maxSpeed, forwards); + velocity2D += (accel + wallForceVector*wallForce)*deltaTime; + + // Distance to the end of the path (almost as the crow flies) + var distanceToEndOfPath = distanceToSteeringTarget + Vector3.Distance(steeringTarget, fn.exactEnd); + + // How fast to move depending on the distance to the destination. + // Move slower as the character gets closer to the destination. + // This is always a value between 0 and 1. + var speedLimitFactor = distanceToEndOfPath < maxSpeed * slowdownTime? Mathf.Sqrt(distanceToEndOfPath / (maxSpeed * slowdownTime)) : 1; + + FinalMovement(position3D, deltaTime, distanceToEndOfPath, speedLimitFactor, out nextPosition, out nextRotation); + } + + void FinalMovement (Vector3 position3D, float deltaTime, float distanceToEndOfPath, float speedLimitFactor, out Vector3 nextPosition, out Quaternion nextRotation) { + var forwards = movementPlane.ToPlane(simulatedRotation * (orientation == OrientationMode.YAxisForward ? Vector3.up : Vector3.forward)); + + ApplyGravity(deltaTime); + + velocity2D = MovementUtilities.ClampVelocity(velocity2D, maxSpeed, speedLimitFactor, slowWhenNotFacingTarget && enableRotation, preventMovingBackwards, forwards); + bool avoidingAnyAgents = false; + + if (rvoController != null && rvoController.enabled) { + // Send a message to the RVOController that we want to move + // with this velocity. In the next simulation step, this + // velocity will be processed and it will be fed back to the + // rvo controller and finally it will be used by this script + // when calling the CalculateMovementDelta method below + + // Make sure that we don't move further than to the end point + // of the path. If the RVO simulation FPS is low and we did + // not do this, the agent might overshoot the target a lot. + var rvoTarget = position3D + movementPlane.ToWorld(Vector2.ClampMagnitude(velocity2D, distanceToEndOfPath)); + rvoController.SetTarget(rvoTarget, velocity2D.magnitude, maxSpeed, endOfPath); + avoidingAnyAgents = rvoController.AvoidingAnyAgents; + } + + // Direction and distance to move during this frame + var deltaPosition = lastDeltaPosition = CalculateDeltaToMoveThisFrame(position3D, distanceToEndOfPath, deltaTime); + + if (enableRotation) { + // Rotate towards the direction we are moving in + // Filter out noise in the movement direction + // This is especially important when the agent is almost standing still and when using local avoidance + float noiseThreshold = radius * tr.localScale.x * 0.2f; + float rotationSpeedFactor = MovementUtilities.FilterRotationDirection(ref rotationFilterState, ref rotationFilterState2, deltaPosition, noiseThreshold, deltaTime, avoidingAnyAgents); + nextRotation = SimulateRotationTowards(rotationFilterState, rotationSpeed * deltaTime * rotationSpeedFactor, rotationSpeed * deltaTime); + } else { + nextRotation = simulatedRotation; + } + + nextPosition = position3D + movementPlane.ToWorld(deltaPosition, verticalVelocity * deltaTime); + } + + protected override Vector3 ClampToNavmesh (Vector3 position, out bool positionChanged) { + if (richPath != null) { + var funnel = richPath.GetCurrentPart() as RichFunnel; + if (funnel != null) { + var clampedPosition = funnel.ClampToNavmesh(position); + + // Inform the RVO system about the edges of the navmesh which will allow + // it to better keep inside the navmesh in the first place. + if (rvoController != null && rvoController.enabled) rvoController.SetObstacleQuery(funnel.CurrentNode); + + // We cannot simply check for equality because some precision may be lost + // if any coordinate transformations are used. + var difference = movementPlane.ToPlane(clampedPosition - position); + float sqrDifference = difference.sqrMagnitude; + if (sqrDifference > 0.001f*0.001f) { + // The agent was outside the navmesh. Remove that component of the velocity + // so that the velocity only goes along the direction of the wall, not into it + velocity2D -= difference * Vector2.Dot(difference, velocity2D) / sqrDifference; + positionChanged = true; + // Return the new position, but ignore any changes in the y coordinate from the ClampToNavmesh method as the y coordinates in the navmesh are rarely very accurate + return position + movementPlane.ToWorld(difference); + } + } + } + + positionChanged = false; + return position; + } + + Vector2 CalculateWallForce (Vector2 position, float elevation, Vector2 directionToTarget) { + if (wallForce <= 0 || wallDist <= 0) return Vector2.zero; + + float wLeft = 0; + float wRight = 0; + + var position3D = movementPlane.ToWorld(position, elevation); + for (int i = 0; i < wallBuffer.Count; i += 2) { + Vector3 closest = VectorMath.ClosestPointOnSegment(wallBuffer[i], wallBuffer[i+1], position3D); + float dist = (closest-position3D).sqrMagnitude; + + if (dist > wallDist*wallDist) continue; + + Vector2 tang = movementPlane.ToPlane(wallBuffer[i+1]-wallBuffer[i]).normalized; + + // Using the fact that all walls are laid out clockwise (looking from inside the obstacle) + // Then left and right (ish) can be figured out like this + float dot = Vector2.Dot(directionToTarget, tang); + float weight = 1 - System.Math.Max(0, (2*(dist / (wallDist*wallDist))-1)); + if (dot > 0) wRight = System.Math.Max(wRight, dot * weight); + else wLeft = System.Math.Max(wLeft, -dot * weight); + } + + Vector2 normal = new Vector2(directionToTarget.y, -directionToTarget.x); + return normal*(wRight-wLeft); + } + + /// <summary>Traverses an off-mesh link</summary> + protected virtual IEnumerator TraverseSpecial (RichSpecial link) { + traversingOffMeshLink = true; + // The current path part is a special part, for example a link + // Movement during this part of the path is handled by the TraverseSpecial coroutine + velocity2D = Vector3.zero; + var offMeshLinkCoroutine = onTraverseOffMeshLink != null? onTraverseOffMeshLink(link) : TraverseOffMeshLinkFallback(link); + yield return StartCoroutine(offMeshLinkCoroutine); + + // Off-mesh link traversal completed + traversingOffMeshLink = false; + NextPart(); + + // If a path completed during the time we traversed the special connection, we need to recalculate it + if (delayUpdatePath) { + delayUpdatePath = false; + // TODO: What if canSearch is false? How do we notify other scripts that might be handling the path calculation that a new path needs to be calculated? + if (canSearch) SearchPath(); + } + } + + /// <summary> + /// Fallback for traversing off-mesh links in case <see cref="onTraverseOffMeshLink"/> is not set. + /// This will do a simple linear interpolation along the link. + /// </summary> + protected IEnumerator TraverseOffMeshLinkFallback (RichSpecial link) { + float duration = maxSpeed > 0 ? Vector3.Distance(link.second.position, link.first.position) / maxSpeed : 1; + float startTime = Time.time; + + while (true) { + var pos = Vector3.Lerp(link.first.position, link.second.position, Mathf.InverseLerp(startTime, startTime + duration, Time.time)); + if (updatePosition) tr.position = pos; + else simulatedPosition = pos; + + if (Time.time >= startTime + duration) break; + yield return null; + } + } + + protected static readonly Color GizmoColorPath = new Color(8.0f/255, 78.0f/255, 194.0f/255); + + public override void DrawGizmos () { + base.DrawGizmos(); + + if (tr != null) { + Vector3 lastPosition = position; + for (int i = 0; i < nextCorners.Count; lastPosition = nextCorners[i], i++) { + Draw.Line(lastPosition, nextCorners[i], GizmoColorPath); + } + } + } + } +} diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/RichAI.cs.meta b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/RichAI.cs.meta new file mode 100644 index 0000000..d2bc561 --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/RichAI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ce11ea984e202491d9271f53021d8b89 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: f2e81a0445323b64f973d2f5b5c56e15, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/RichPath.cs b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/RichPath.cs new file mode 100644 index 0000000..268a34e --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/RichPath.cs @@ -0,0 +1,797 @@ +using UnityEngine; +using System.Collections.Generic; +using Pathfinding.Util; +using UnityEngine.Assertions; + +namespace Pathfinding { + public class RichPath { + int currentPart; + readonly List<RichPathPart> parts = new List<RichPathPart>(); + + public Seeker seeker; + + /// <summary> + /// Transforms points from path space to world space. + /// If null the identity transform will be used. + /// + /// This is used when the world position of the agent does not match the + /// corresponding position on the graph. This is the case in the example + /// scene called 'Moving'. + /// + /// See: <see cref="Pathfinding.Examples.LocalSpaceRichAI"/> + /// </summary> + public ITransform transform; + + public RichPath () { + Clear(); + } + + public void Clear () { + parts.Clear(); + currentPart = 0; + Endpoint = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + } + + /// <summary>Use this for initialization.</summary> + /// <param name="seeker">Optionally provide in order to take tag penalties into account. May be null if you do not use a Seeker\</param> + /// <param name="path">Path to follow</param> + /// <param name="mergePartEndpoints">If true, then adjacent parts that the path is split up in will + /// try to use the same start/end points. For example when using a link on a navmesh graph + /// Instead of first following the path to the center of the node where the link is and then + /// follow the link, the path will be adjusted to go to the exact point where the link starts + /// which usually makes more sense.</param> + /// <param name="simplificationMode">The path can optionally be simplified. This can be a bit expensive for long paths.</param> + public void Initialize (Seeker seeker, Path path, bool mergePartEndpoints, bool simplificationMode) { + if (path.error) throw new System.ArgumentException("Path has an error"); + + List<GraphNode> nodes = path.path; + if (nodes.Count == 0) throw new System.ArgumentException("Path traverses no nodes"); + + this.seeker = seeker; + // Release objects back to object pool + // Yeah, I know, it's casting... but this won't be called much + for (int i = 0; i < parts.Count; i++) { + var funnelPart = parts[i] as RichFunnel; + var specialPart = parts[i] as RichSpecial; + if (funnelPart != null) ObjectPool<RichFunnel>.Release(ref funnelPart); + else if (specialPart != null) ObjectPool<RichSpecial>.Release(ref specialPart); + } + + Clear(); + + // Initialize new + Endpoint = path.vectorPath[path.vectorPath.Count-1]; + + //Break path into parts + for (int i = 0; i < nodes.Count; i++) { + if (nodes[i] is TriangleMeshNode) { + var graph = AstarData.GetGraph(nodes[i]) as NavmeshBase; + if (graph == null) throw new System.Exception("Found a TriangleMeshNode that was not in a NavmeshBase graph"); + + RichFunnel f = ObjectPool<RichFunnel>.Claim().Initialize(this, graph); + + f.funnelSimplification = simplificationMode; + + int sIndex = i; + uint currentGraphIndex = nodes[sIndex].GraphIndex; + + + for (; i < nodes.Count; i++) { + if (nodes[i].GraphIndex != currentGraphIndex && !(nodes[i] is NodeLink3Node)) { + break; + } + } + i--; + + if (sIndex == 0) { + f.exactStart = path.vectorPath[0]; + } else { + f.exactStart = (Vector3)nodes[mergePartEndpoints ? sIndex-1 : sIndex].position; + } + + if (i == nodes.Count-1) { + f.exactEnd = path.vectorPath[path.vectorPath.Count-1]; + } else { + f.exactEnd = (Vector3)nodes[mergePartEndpoints ? i+1 : i].position; + } + + f.BuildFunnelCorridor(nodes, sIndex, i); + + parts.Add(f); + } else if (nodes[i] is LinkNode nl) { + int sIndex = i; + uint currentGraphIndex = nodes[sIndex].GraphIndex; + + while (i < nodes.Count && nodes[i].GraphIndex == currentGraphIndex) i++; + i--; + + if (i - sIndex > 1) { + throw new System.Exception("NodeLink2 path length greater than two (2) nodes. " + (i - sIndex)); + } else if (i - sIndex == 0) { + // The link is a single node. + // Just ignore it. It can happen in very rare circumstances with some path types. + // For example, a RandomPath can stop at the first node of a node link, without including the other end of the link + continue; + } + Assert.AreEqual(nl.linkConcrete, (nodes[i] as LinkNode).linkConcrete); + + RichSpecial rps = ObjectPool<RichSpecial>.Claim().Initialize(nl.linkConcrete.GetTracer(nl)); + parts.Add(rps); + } else if (!(nodes[i] is PointNode)) { + // Some other graph type which we do not have support for + throw new System.InvalidOperationException("The RichAI movment script can only be used on recast/navmesh graphs. A node of type " + nodes[i].GetType().Name + " was in the path."); + } + } + } + + public Vector3 Endpoint { get; private set; } + + /// <summary>True if we have completed (called NextPart for) the last part in the path</summary> + public bool CompletedAllParts { + get { + return currentPart >= parts.Count; + } + } + + /// <summary>True if we are traversing the last part of the path</summary> + public bool IsLastPart { + get { + return currentPart >= parts.Count - 1; + } + } + + public void NextPart () { + currentPart = Mathf.Min(currentPart + 1, parts.Count); + } + + public RichPathPart GetCurrentPart () { + if (parts.Count == 0) return null; + return currentPart < parts.Count ? parts[currentPart] : parts[parts.Count - 1]; + } + + /// <summary> + /// Replaces the buffer with the remaining path. + /// See: <see cref="Pathfinding.IAstarAI.GetRemainingPath"/> + /// </summary> + public void GetRemainingPath (List<Vector3> buffer, List<PathPartWithLinkInfo> partsBuffer, Vector3 currentPosition, out bool requiresRepath) { + buffer.Clear(); + buffer.Add(currentPosition); + requiresRepath = false; + for (int i = currentPart; i < parts.Count; i++) { + var part = parts[i]; + if (part is RichFunnel funnel) { + bool lastCorner; + var startIndex = buffer.Count; + if (i != 0) buffer.Add(funnel.exactStart); + funnel.Update(i == 0 ? currentPosition : funnel.exactStart, buffer, int.MaxValue, out lastCorner, out requiresRepath); + if (partsBuffer != null) partsBuffer.Add(new PathPartWithLinkInfo(startIndex, buffer.Count-1)); + if (requiresRepath) { + return; + } + } else if (part is RichSpecial rs) { + // By adding all points above the link will look like just a stright line, which is reasonable + // The part's start/end indices refer to the last point in previous part and first point in the next part, respectively + if (partsBuffer != null) partsBuffer.Add(new PathPartWithLinkInfo(buffer.Count-1, buffer.Count, rs.nodeLink)); + } + } + } + } + + public abstract class RichPathPart : Pathfinding.Util.IAstarPooledObject { + public abstract void OnEnterPool(); + } + + public class RichFunnel : RichPathPart { + readonly List<Vector3> left; + readonly List<Vector3> right; + List<TriangleMeshNode> nodes; + public Vector3 exactStart; + public Vector3 exactEnd; + NavmeshBase graph; + int currentNode; + Vector3 currentPosition; + int checkForDestroyedNodesCounter; + RichPath path; + int[] triBuffer = new int[3]; + + /// <summary>Post process the funnel corridor or not</summary> + public bool funnelSimplification = true; + + public RichFunnel () { + left = Pathfinding.Util.ListPool<Vector3>.Claim(); + right = Pathfinding.Util.ListPool<Vector3>.Claim(); + nodes = new List<TriangleMeshNode>(); + this.graph = null; + } + + /// <summary>Works like a constructor, but can be used even for pooled objects. Returns this for easy chaining</summary> + public RichFunnel Initialize (RichPath path, NavmeshBase graph) { + if (graph == null) throw new System.ArgumentNullException("graph"); + if (this.graph != null) throw new System.InvalidOperationException("Trying to initialize an already initialized object. " + graph); + + this.graph = graph; + this.path = path; + return this; + } + + public override void OnEnterPool () { + left.Clear(); + right.Clear(); + nodes.Clear(); + graph = null; + currentNode = 0; + checkForDestroyedNodesCounter = 0; + } + + public TriangleMeshNode CurrentNode { + get { + var node = nodes[currentNode]; + if (!node.Destroyed) { + return node; + } + return null; + } + } + + /// <summary> + /// Build a funnel corridor from a node list slice. + /// The nodes are assumed to be of type TriangleMeshNode. + /// </summary> + /// <param name="nodes">Nodes to build the funnel corridor from</param> + /// <param name="start">Start index in the nodes list</param> + /// <param name="end">End index in the nodes list, this index is inclusive</param> + public void BuildFunnelCorridor (List<GraphNode> nodes, int start, int end) { + //Make sure start and end points are on the correct nodes + exactStart = (nodes[start] as MeshNode).ClosestPointOnNode(exactStart); + exactEnd = (nodes[end] as MeshNode).ClosestPointOnNode(exactEnd); + + left.Clear(); + right.Clear(); + left.Add(exactStart); + right.Add(exactStart); + + this.nodes.Clear(); + + if (funnelSimplification) { + List<GraphNode> tmp = ListPool<GraphNode>.Claim(end-start); + + var tagPenalties = path.seeker != null ? path.seeker.tagPenalties : Path.ZeroTagPenalties; + var traversableTags = path.seeker != null ? path.seeker.traversableTags : -1; + + Funnel.Simplify(new Funnel.PathPart { + startIndex = start, + endIndex = end, + startPoint = exactStart, + endPoint = exactEnd, + type = Funnel.PartType.NodeSequence, + }, graph, nodes, tmp, tagPenalties, traversableTags); + + if (this.nodes.Capacity < tmp.Count) this.nodes.Capacity = tmp.Count; + + for (int i = 0; i < tmp.Count; i++) { + // Guaranteed to be TriangleMeshNodes since they are all in the same graph + var node = tmp[i] as TriangleMeshNode; + if (node != null) this.nodes.Add(node); + } + + ListPool<GraphNode>.Release(ref tmp); + } else { + if (this.nodes.Capacity < end-start) this.nodes.Capacity = (end-start); + for (int i = start; i <= end; i++) { + // Guaranteed to be TriangleMeshNodes since they are all in the same graph + var node = nodes[i] as TriangleMeshNode; + if (node != null) this.nodes.Add(node); + } + } + + for (int i = 0; i < this.nodes.Count-1; i++) { + if (this.nodes[i].GetPortal(this.nodes[i+1], out var leftP, out var rightP)) { + left.Add(leftP); + right.Add(rightP); + } else { + // Can happen in case custom connections have been added + left.Add((Vector3)this.nodes[i].position); + right.Add((Vector3)this.nodes[i].position); + left.Add((Vector3)this.nodes[i+1].position); + right.Add((Vector3)this.nodes[i+1].position); + } + } + + left.Add(exactEnd); + right.Add(exactEnd); + } + + /// <summary> + /// Split funnel at node index splitIndex and throw the nodes up to that point away and replace with prefix. + /// Used when the AI has happened to get sidetracked and entered a node outside the funnel. + /// </summary> + void UpdateFunnelCorridor (int splitIndex, List<TriangleMeshNode> prefix) { + nodes.RemoveRange(0, splitIndex); + nodes.InsertRange(0, prefix); + + left.Clear(); + right.Clear(); + left.Add(exactStart); + right.Add(exactStart); + + for (int i = 0; i < nodes.Count-1; i++) { + if (nodes[i].GetPortal(nodes[i+1], out var leftP, out var rightP)) { + left.Add(leftP); + right.Add(rightP); + } + } + + left.Add(exactEnd); + right.Add(exactEnd); + } + + /// <summary>True if any node in the path is destroyed</summary> + bool CheckForDestroyedNodes () { + // Loop through all nodes and check if they are destroyed + // If so, we really need a recalculation of our path quickly + // since there might be an obstacle blocking our path after + // a graph update or something similar + for (int i = 0, t = nodes.Count; i < t; i++) { + if (nodes[i].Destroyed) { + return true; + } + } + return false; + } + + /// <summary> + /// Approximate distance (as the crow flies) to the endpoint of this path part. + /// See: <see cref="exactEnd"/> + /// </summary> + public float DistanceToEndOfPath { + get { + var currentNode = CurrentNode; + Vector3 closestOnNode = currentNode != null? currentNode.ClosestPointOnNode(currentPosition) : currentPosition; + return (exactEnd - closestOnNode).magnitude; + } + } + + /// <summary> + /// Clamps the position to the navmesh and repairs the path if the agent has moved slightly outside it. + /// You should not call this method with anything other than the agent's position. + /// </summary> + public Vector3 ClampToNavmesh (Vector3 position) { + if (path.transform != null) position = path.transform.InverseTransform(position); + UnityEngine.Assertions.Assert.IsFalse(float.IsNaN(position.x)); + ClampToNavmeshInternal(ref position); + if (path.transform != null) position = path.transform.Transform(position); + UnityEngine.Assertions.Assert.IsFalse(float.IsNaN(position.x)); + return position; + } + + /// <summary> + /// Find the next points to move towards and clamp the position to the navmesh. + /// + /// Returns: The position of the agent clamped to make sure it is inside the navmesh. + /// </summary> + /// <param name="position">The position of the agent.</param> + /// <param name="buffer">Will be filled with up to numCorners points which are the next points in the path towards the target.</param> + /// <param name="numCorners">See buffer.</param> + /// <param name="lastCorner">True if the buffer contains the end point of the path.</param> + /// <param name="requiresRepath">True if nodes along the path have been destroyed and a path recalculation is necessary.</param> + public Vector3 Update (Vector3 position, List<Vector3> buffer, int numCorners, out bool lastCorner, out bool requiresRepath) { + if (path.transform != null) position = path.transform.InverseTransform(position); + UnityEngine.Assertions.Assert.IsFalse(float.IsNaN(position.x)); + + lastCorner = false; + requiresRepath = false; + + // Only check for destroyed nodes every 10 frames + if (checkForDestroyedNodesCounter >= 10) { + checkForDestroyedNodesCounter = 0; + requiresRepath |= CheckForDestroyedNodes(); + } else { + checkForDestroyedNodesCounter++; + } + + bool nodesDestroyed = ClampToNavmeshInternal(ref position); + + currentPosition = position; + + if (nodesDestroyed) { + // Some nodes on the path have been destroyed + // we need to recalculate the path immediately + requiresRepath = true; + lastCorner = false; + buffer.Add(position); + } else if (!FindNextCorners(position, currentNode, buffer, numCorners, out lastCorner)) { + Debug.LogError("Failed to find next corners in the path"); + buffer.Add(position); + } + + if (path.transform != null) { + for (int i = 0; i < buffer.Count; i++) { + buffer[i] = path.transform.Transform(buffer[i]); + } + + position = path.transform.Transform(position); + UnityEngine.Assertions.Assert.IsFalse(float.IsNaN(position.x)); + } + + return position; + } + + /// <summary>Cached object to avoid unnecessary allocations</summary> + static Queue<TriangleMeshNode> navmeshClampQueue = new Queue<TriangleMeshNode>(); + /// <summary>Cached object to avoid unnecessary allocations</summary> + static List<TriangleMeshNode> navmeshClampList = new List<TriangleMeshNode>(); + /// <summary>Cached object to avoid unnecessary allocations</summary> + static Dictionary<TriangleMeshNode, TriangleMeshNode> navmeshClampDict = new Dictionary<TriangleMeshNode, TriangleMeshNode>(); + + /// <summary> + /// Searches for the node the agent is inside. + /// This will also clamp the position to the navmesh + /// and repair the funnel cooridor if the agent moves slightly outside it. + /// + /// Returns: True if nodes along the path have been destroyed so that a path recalculation is required + /// </summary> + bool ClampToNavmeshInternal (ref Vector3 position) { + var previousNode = nodes[currentNode]; + + if (previousNode.Destroyed) { + return true; + } + + // Check if we are in the same node as we were in during the last frame and otherwise do a more extensive search + if (previousNode.ContainsPoint(position)) { + return false; + } + + // This part of the code is relatively seldom called + // Most of the time we are still on the same node as during the previous frame + + var que = navmeshClampQueue; + var allVisited = navmeshClampList; + var parent = navmeshClampDict; + previousNode.TemporaryFlag1 = true; + parent[previousNode] = null; + que.Enqueue(previousNode); + allVisited.Add(previousNode); + + float bestDistance = float.PositiveInfinity; + Vector3 bestPoint = position; + TriangleMeshNode bestNode = null; + + while (que.Count > 0) { + var node = que.Dequeue(); + + // Snap to the closest point in XZ space (keep the Y coordinate) + // If we would have snapped to the closest point in 3D space, the agent + // might slow down when traversing slopes + var closest = node.ClosestPointOnNodeXZ(position); + var dist = VectorMath.MagnitudeXZ(closest - position); + + // Check if this node is any closer than the previous best node. + // Allow for a small margin to both avoid floating point errors and to allow + // moving past very small local minima. + if (dist <= bestDistance * 1.05f + 0.001f) { + if (dist < bestDistance) { + bestDistance = dist; + bestPoint = closest; + bestNode = node; + } + + for (int i = 0; i < node.connections.Length; i++) { + if (!node.connections[i].isOutgoing) continue; + var neighbour = node.connections[i].node as TriangleMeshNode; + if (neighbour != null && !neighbour.TemporaryFlag1) { + neighbour.TemporaryFlag1 = true; + parent[neighbour] = node; + que.Enqueue(neighbour); + allVisited.Add(neighbour); + } + } + } + } + + UnityEngine.Assertions.Assert.IsNotNull(bestNode); + + for (int i = 0; i < allVisited.Count; i++) allVisited[i].TemporaryFlag1 = false; + allVisited.ClearFast(); + + var closestNodeInPath = nodes.IndexOf(bestNode); + + // Move the x and z coordinates of the chararacter but not the y coordinate + // because the navmesh surface may not line up with the ground + position.x = bestPoint.x; + position.z = bestPoint.z; + + // Check if the closest node + // was on the path already or if we need to adjust it + if (closestNodeInPath == -1) { + // Reuse this list, because why not. + var prefix = navmeshClampList; + + while (closestNodeInPath == -1) { + prefix.Add(bestNode); + bestNode = parent[bestNode]; + closestNodeInPath = nodes.IndexOf(bestNode); + } + + // We have found a node containing the position, but it is outside the funnel + // Recalculate the funnel to include this node + exactStart = position; + UpdateFunnelCorridor(closestNodeInPath, prefix); + + prefix.ClearFast(); + + // Restart from the first node in the updated path + currentNode = 0; + } else { + currentNode = closestNodeInPath; + } + + parent.Clear(); + // Do a quick check to see if the next node in the path has been destroyed + // If that is the case then we should plan a new path immediately + return currentNode + 1 < nodes.Count && nodes[currentNode+1].Destroyed; + } + + /// <summary> + /// Fill wallBuffer with all navmesh wall segments close to the current position. + /// A wall segment is a node edge which is not shared by any other neighbour node, i.e an outer edge on the navmesh. + /// </summary> + public void FindWalls (List<Vector3> wallBuffer, float range) { + FindWalls(currentNode, wallBuffer, currentPosition, range); + } + + void FindWalls (int nodeIndex, List<Vector3> wallBuffer, Vector3 position, float range) { + if (range <= 0) return; + + bool negAbort = false; + bool posAbort = false; + + range *= range; + + position.y = 0; + //Looping as 0,-1,1,-2,2,-3,3,-4,4 etc. Avoids code duplication by keeping it to one loop instead of two + for (int i = 0; !negAbort || !posAbort; i = i < 0 ? -i : -i-1) { + if (i < 0 && negAbort) continue; + if (i > 0 && posAbort) continue; + + if (i < 0 && nodeIndex+i < 0) { + negAbort = true; + continue; + } + + if (i > 0 && nodeIndex+i >= nodes.Count) { + posAbort = true; + continue; + } + + TriangleMeshNode prev = nodeIndex+i-1 < 0 ? null : nodes[nodeIndex+i-1]; + TriangleMeshNode node = nodes[nodeIndex+i]; + TriangleMeshNode next = nodeIndex+i+1 >= nodes.Count ? null : nodes[nodeIndex+i+1]; + + if (node.Destroyed) { + break; + } + + if ((node.ClosestPointOnNodeXZ(position)-position).sqrMagnitude > range) { + if (i < 0) negAbort = true; + else posAbort = true; + continue; + } + + for (int j = 0; j < 3; j++) triBuffer[j] = 0; + + for (int j = 0; j < node.connections.Length; j++) { + var other = node.connections[j].node as TriangleMeshNode; + if (other == null) continue; + + int va = -1; + for (int a = 0; a < 3; a++) { + for (int b = 0; b < 3; b++) { + if (node.GetVertex(a) == other.GetVertex((b+1) % 3) && node.GetVertex((a+1) % 3) == other.GetVertex(b)) { + va = a; + a = 3; + break; + } + } + } + if (va == -1) { + //No direct connection + } else { + triBuffer[va] = other == prev || other == next ? 2 : 1; + } + } + + for (int j = 0; j < 3; j++) { + //Tribuffer values + // 0 : Navmesh border, outer edge + // 1 : Inner edge, to node inside funnel + // 2 : Inner edge, to node outside funnel + if (triBuffer[j] == 0) { + //Add edge to list of walls + wallBuffer.Add((Vector3)node.GetVertex(j)); + wallBuffer.Add((Vector3)node.GetVertex((j+1) % 3)); + } + } + } + + if (path.transform != null) { + for (int i = 0; i < wallBuffer.Count; i++) { + wallBuffer[i] = path.transform.Transform(wallBuffer[i]); + } + } + } + + bool FindNextCorners (Vector3 origin, int startIndex, List<Vector3> funnelPath, int numCorners, out bool lastCorner) { + lastCorner = false; + + if (left == null) throw new System.Exception("left list is null"); + if (right == null) throw new System.Exception("right list is null"); + if (funnelPath == null) throw new System.ArgumentNullException("funnelPath"); + + if (left.Count != right.Count) throw new System.ArgumentException("left and right lists must have equal length"); + + int diagonalCount = left.Count; + + if (diagonalCount == 0) throw new System.ArgumentException("no diagonals"); + + if (diagonalCount-startIndex < 3) { + //Direct path + funnelPath.Add(left[diagonalCount-1]); + lastCorner = true; + return true; + } + +#if ASTARDEBUG + for (int i = startIndex; i < left.Count-1; i++) { + Debug.DrawLine(left[i], left[i+1], Color.red); + Debug.DrawLine(right[i], right[i+1], Color.magenta); + Debug.DrawRay(right[i], Vector3.up, Color.magenta); + } + for (int i = 0; i < left.Count; i++) { + Debug.DrawLine(right[i], left[i], Color.cyan); + } +#endif + + //Remove identical vertices + while (left[startIndex+1] == left[startIndex+2] && right[startIndex+1] == right[startIndex+2]) { + //System.Console.WriteLine ("Removing identical left and right"); + //left.RemoveAt (1); + //right.RemoveAt (1); + startIndex++; + + if (diagonalCount-startIndex <= 3) { + return false; + } + } + + Vector3 swPoint = left[startIndex+2]; + if (swPoint == left[startIndex+1]) { + swPoint = right[startIndex+2]; + } + + + //Test + while (VectorMath.IsColinearXZ(origin, left[startIndex+1], right[startIndex+1]) || VectorMath.RightOrColinearXZ(left[startIndex+1], right[startIndex+1], swPoint) == VectorMath.RightOrColinearXZ(left[startIndex+1], right[startIndex+1], origin)) { +#if ASTARDEBUG + Debug.DrawLine(left[startIndex+1], right[startIndex+1], new Color(0, 0, 0, 0.5F)); + Debug.DrawLine(origin, swPoint, new Color(0, 0, 0, 0.5F)); +#endif + //left.RemoveAt (1); + //right.RemoveAt (1); + startIndex++; + + if (diagonalCount-startIndex < 3) { + //Debug.Log ("#2 " + left.Count + " - " + startIndex + " = " + (left.Count-startIndex)); + //Direct path + funnelPath.Add(left[diagonalCount-1]); + lastCorner = true; + return true; + } + + swPoint = left[startIndex+2]; + if (swPoint == left[startIndex+1]) { + swPoint = right[startIndex+2]; + } + } + + + //funnelPath.Add (origin); + + Vector3 portalApex = origin; + Vector3 portalLeft = left[startIndex+1]; + Vector3 portalRight = right[startIndex+1]; + + int apexIndex = startIndex+0; + int rightIndex = startIndex+1; + int leftIndex = startIndex+1; + + for (int i = startIndex+2; i < diagonalCount; i++) { + if (funnelPath.Count >= numCorners) { + return true; + } + + if (funnelPath.Count > 2000) { + Debug.LogWarning("Avoiding infinite loop. Remove this check if you have this long paths."); + break; + } + + Vector3 pLeft = left[i]; + Vector3 pRight = right[i]; + + /*Debug.DrawLine (portalApex,portalLeft,Color.red); + * Debug.DrawLine (portalApex,portalRight,Color.yellow); + * Debug.DrawLine (portalApex,left,Color.cyan); + * Debug.DrawLine (portalApex,right,Color.cyan);*/ + + if (VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalRight, pRight) >= 0) { + if (portalApex == portalRight || VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalLeft, pRight) <= 0) { + portalRight = pRight; + rightIndex = i; + } else { + funnelPath.Add(portalLeft); + portalApex = portalLeft; + apexIndex = leftIndex; + + portalLeft = portalApex; + portalRight = portalApex; + + leftIndex = apexIndex; + rightIndex = apexIndex; + + i = apexIndex; + + continue; + } + } + + if (VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalLeft, pLeft) <= 0) { + if (portalApex == portalLeft || VectorMath.SignedTriangleAreaTimes2XZ(portalApex, portalRight, pLeft) >= 0) { + portalLeft = pLeft; + leftIndex = i; + } else { + funnelPath.Add(portalRight); + portalApex = portalRight; + apexIndex = rightIndex; + + portalLeft = portalApex; + portalRight = portalApex; + + leftIndex = apexIndex; + rightIndex = apexIndex; + + i = apexIndex; + + continue; + } + } + } + + lastCorner = true; + funnelPath.Add(left[diagonalCount-1]); + + return true; + } + } + + public struct FakeTransform { + public Vector3 position; + public Quaternion rotation; + } + + public class RichSpecial : RichPathPart { + public OffMeshLinks.OffMeshLinkTracer nodeLink; + public FakeTransform first => new FakeTransform { position = nodeLink.relativeStart, rotation = nodeLink.isReverse ? nodeLink.link.end.rotation : nodeLink.link.start.rotation }; + public FakeTransform second => new FakeTransform { position = nodeLink.relativeEnd, rotation = nodeLink.isReverse ? nodeLink.link.start.rotation : nodeLink.link.end.rotation }; + public bool reverse => nodeLink.isReverse; + + public override void OnEnterPool () { + nodeLink = default; + } + + /// <summary>Works like a constructor, but can be used even for pooled objects. Returns this for easy chaining</summary> + public RichSpecial Initialize (OffMeshLinks.OffMeshLinkTracer nodeLink) { + this.nodeLink = nodeLink; + return this; + } + } +} diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/RichPath.cs.meta b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/RichPath.cs.meta new file mode 100644 index 0000000..bad8489 --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/RichPath.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6865b0d3859fe4641ad0839b829e00d2 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/Seeker.cs b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/Seeker.cs new file mode 100644 index 0000000..41d40ff --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/Seeker.cs @@ -0,0 +1,709 @@ +using UnityEngine; +using System.Collections.Generic; +using Pathfinding.Util; +using UnityEngine.Profiling; + +namespace Pathfinding { + using Pathfinding.Drawing; + + /// <summary> + /// Handles path calls for a single unit. + /// + /// This is a component which is meant to be attached to a single unit (AI, Robot, Player, whatever) to handle its pathfinding calls. + /// It also handles post-processing of paths using modifiers. + /// + /// See: calling-pathfinding (view in online documentation for working links) + /// See: modifiers (view in online documentation for working links) + /// </summary> + [AddComponentMenu("Pathfinding/Seeker")] + [HelpURL("https://arongranberg.com/astar/documentation/stable/seeker.html")] + public class Seeker : VersionedMonoBehaviour { + /// <summary> + /// Enables drawing of the last calculated path using Gizmos. + /// The path will show up in green. + /// + /// See: OnDrawGizmos + /// </summary> + public bool drawGizmos = true; + + /// <summary> + /// Enables drawing of the non-postprocessed path using Gizmos. + /// The path will show up in orange. + /// + /// Requires that <see cref="drawGizmos"/> is true. + /// + /// This will show the path before any post processing such as smoothing is applied. + /// + /// See: drawGizmos + /// See: OnDrawGizmos + /// </summary> + public bool detailedGizmos; + + /// <summary>Path modifier which tweaks the start and end points of a path</summary> + [HideInInspector] + public StartEndModifier startEndModifier = new StartEndModifier(); + + /// <summary> + /// The tags which the Seeker can traverse. + /// + /// Note: This field is a bitmask. + /// See: bitmasks (view in online documentation for working links) + /// </summary> + [HideInInspector] + public int traversableTags = -1; + + /// <summary> + /// Penalties for each tag. + /// Tag 0 which is the default tag, will have added a penalty of tagPenalties[0]. + /// These should only be positive values since the A* algorithm cannot handle negative penalties. + /// + /// The length of this array should be exactly 32, one for each tag. + /// + /// See: Pathfinding.Path.tagPenalties + /// </summary> + [HideInInspector] + public int[] tagPenalties = new int[32]; + + /// <summary> + /// Graphs that this Seeker can use. + /// This field determines which graphs will be considered when searching for the start and end nodes of a path. + /// It is useful in numerous situations, for example if you want to make one graph for small units and one graph for large units. + /// + /// This is a bitmask so if you for example want to make the agent only use graph index 3 then you can set this to: + /// <code> seeker.graphMask = 1 << 3; </code> + /// + /// See: bitmasks (view in online documentation for working links) + /// + /// Note that this field only stores which graph indices that are allowed. This means that if the graphs change their ordering + /// then this mask may no longer be correct. + /// + /// If you know the name of the graph you can use the <see cref="Pathfinding.GraphMask.FromGraphName"/> method: + /// <code> + /// GraphMask mask1 = GraphMask.FromGraphName("My Grid Graph"); + /// GraphMask mask2 = GraphMask.FromGraphName("My Other Grid Graph"); + /// + /// NNConstraint nn = NNConstraint.Walkable; + /// + /// nn.graphMask = mask1 | mask2; + /// + /// // Find the node closest to somePoint which is either in 'My Grid Graph' OR in 'My Other Grid Graph' + /// var info = AstarPath.active.GetNearest(somePoint, nn); + /// </code> + /// + /// Some overloads of the <see cref="StartPath"/> methods take a graphMask parameter. If those overloads are used then they + /// will override the graph mask for that path request. + /// + /// [Open online documentation to see images] + /// + /// See: multiple-agent-types (view in online documentation for working links) + /// </summary> + [HideInInspector] + public GraphMask graphMask = GraphMask.everything; + + /// <summary> + /// Custom traversal provider to calculate which nodes are traversable and their penalties. + /// + /// This can be used to override the built-in pathfinding logic. + /// + /// <code> + /// seeker.traversalProvider = new MyCustomTraversalProvider(); + /// </code> + /// + /// See: traversal_provider (view in online documentation for working links) + /// </summary> + public ITraversalProvider traversalProvider; + + /// <summary>Used for serialization backwards compatibility</summary> + [UnityEngine.Serialization.FormerlySerializedAs("graphMask")] + int graphMaskCompatibility = -1; + + /// <summary> + /// Callback for when a path is completed. + /// Movement scripts should register to this delegate. + /// A temporary callback can also be set when calling StartPath, but that delegate will only be called for that path + /// + /// <code> + /// public void Start () { + /// // Assumes a Seeker component is attached to the GameObject + /// Seeker seeker = GetComponent<Seeker>(); + /// + /// // seeker.pathCallback is a OnPathDelegate, we add the function OnPathComplete to it so it will be called whenever a path has finished calculating on that seeker + /// seeker.pathCallback += OnPathComplete; + /// } + /// + /// public void OnPathComplete (Path p) { + /// Debug.Log("This is called when a path is completed on the seeker attached to this GameObject"); + /// } + /// </code> + /// + /// Deprecated: Pass a callback every time to the StartPath method instead, or use ai.SetPath+ai.pathPending on the movement script. You can cache it in your own script if you want to avoid the GC allocation of creating a new delegate. + /// </summary> + [System.Obsolete("Pass a callback every time to the StartPath method instead, or use ai.SetPath+ai.pathPending on the movement script. You can cache it in your own script if you want to avoid the GC allocation of creating a new delegate.")] + public OnPathDelegate pathCallback; + + /// <summary>Called before pathfinding is started</summary> + public OnPathDelegate preProcessPath; + + /// <summary>Called after a path has been calculated, right before modifiers are executed.</summary> + public OnPathDelegate postProcessPath; + +#if UNITY_EDITOR + /// <summary>Used for drawing gizmos</summary> + [System.NonSerialized] + List<Vector3> lastCompletedVectorPath; + + /// <summary>Used for drawing gizmos</summary> + [System.NonSerialized] + List<GraphNode> lastCompletedNodePath; +#endif + + /// <summary>The current path</summary> + [System.NonSerialized] + protected Path path; + + /// <summary>Previous path. Used to draw gizmos</summary> + [System.NonSerialized] + private Path prevPath; + + /// <summary>Cached delegate to avoid allocating one every time a path is started</summary> + private readonly OnPathDelegate onPathDelegate; + /// <summary>Cached delegate to avoid allocating one every time a path is started</summary> + private readonly OnPathDelegate onPartialPathDelegate; + + /// <summary>Temporary callback only called for the current path. This value is set by the StartPath functions</summary> + private OnPathDelegate tmpPathCallback; + + /// <summary>The path ID of the last path queried</summary> + protected uint lastPathID; + + /// <summary>Internal list of all modifiers</summary> + readonly List<IPathModifier> modifiers = new List<IPathModifier>(); + + public enum ModifierPass { + PreProcess, + // An obsolete item occupied index 1 previously + PostProcess = 2, + } + + public Seeker () { + onPathDelegate = OnPathComplete; + onPartialPathDelegate = OnPartialPathComplete; + } + + /// <summary>Initializes a few variables</summary> + protected override void Awake () { + base.Awake(); + startEndModifier.Awake(this); + } + + /// <summary> + /// Path that is currently being calculated or was last calculated. + /// You should rarely have to use this. Instead get the path when the path callback is called. + /// + /// See: <see cref="StartPath"/> + /// </summary> + public Path GetCurrentPath() => path; + + /// <summary> + /// Stop calculating the current path request. + /// If this Seeker is currently calculating a path it will be canceled. + /// The callback (usually to a method named OnPathComplete) will soon be called + /// with a path that has the 'error' field set to true. + /// + /// This does not stop the character from moving, it just aborts + /// the path calculation. + /// </summary> + /// <param name="pool">If true then the path will be pooled when the pathfinding system is done with it.</param> + public void CancelCurrentPathRequest (bool pool = true) { + if (!IsDone()) { + path.FailWithError("Canceled by script (Seeker.CancelCurrentPathRequest)"); + if (pool) { + // Make sure the path has had its reference count incremented and decremented once. + // If this is not done the system will think no pooling is used at all and will not pool the path. + // The particular object that is used as the parameter (in this case 'path') doesn't matter at all + // it just has to be *some* object. + path.Claim(path); + path.Release(path); + } + } + } + + /// <summary> + /// Cleans up some variables. + /// Releases any eventually claimed paths. + /// Calls OnDestroy on the <see cref="startEndModifier"/>. + /// + /// See: <see cref="ReleaseClaimedPath"/> + /// See: <see cref="startEndModifier"/> + /// </summary> + void OnDestroy () { + ReleaseClaimedPath(); + startEndModifier.OnDestroy(this); + } + + /// <summary> + /// Releases the path used for gizmos (if any). + /// The seeker keeps the latest path claimed so it can draw gizmos. + /// In some cases this might not be desireable and you want it released. + /// In that case, you can call this method to release it (not that path gizmos will then not be drawn). + /// + /// If you didn't understand anything from the description above, you probably don't need to use this method. + /// + /// See: pooling (view in online documentation for working links) + /// </summary> + void ReleaseClaimedPath () { + if (prevPath != null) { + prevPath.Release(this, true); + prevPath = null; + } + } + + /// <summary>Called by modifiers to register themselves</summary> + public void RegisterModifier (IPathModifier modifier) { + modifiers.Add(modifier); + + // Sort the modifiers based on their specified order + modifiers.Sort((a, b) => a.Order.CompareTo(b.Order)); + } + + /// <summary>Called by modifiers when they are disabled or destroyed</summary> + public void DeregisterModifier (IPathModifier modifier) { + modifiers.Remove(modifier); + } + + /// <summary> + /// Post Processes the path. + /// This will run any modifiers attached to this GameObject on the path. + /// This is identical to calling RunModifiers(ModifierPass.PostProcess, path) + /// See: <see cref="RunModifiers"/> + /// </summary> + public void PostProcess (Path path) { + RunModifiers(ModifierPass.PostProcess, path); + } + + /// <summary>Runs modifiers on a path</summary> + public void RunModifiers (ModifierPass pass, Path path) { + if (pass == ModifierPass.PreProcess) { + if (preProcessPath != null) preProcessPath(path); + + for (int i = 0; i < modifiers.Count; i++) modifiers[i].PreProcess(path); + } else if (pass == ModifierPass.PostProcess) { + Profiler.BeginSample("Running Path Modifiers"); + // Call delegates if they exist + if (postProcessPath != null) postProcessPath(path); + + // Loop through all modifiers and apply post processing + for (int i = 0; i < modifiers.Count; i++) modifiers[i].Apply(path); + Profiler.EndSample(); + } + } + + /// <summary> + /// Is the current path done calculating. + /// Returns true if the current <see cref="path"/> has been returned or if the <see cref="path"/> is null. + /// + /// Note: Do not confuse this with Pathfinding.Path.IsDone. They usually return the same value, but not always. + /// The path might be completely calculated, but has not yet been processed by the Seeker. + /// + /// Inside the OnPathComplete callback this method will return true. + /// + /// Version: Before version 4.2.13 this would return false inside the OnPathComplete callback. However, this behaviour was unintuitive. + /// </summary> + public bool IsDone() => path == null || path.PipelineState >= PathState.Returning; + + /// <summary>Called when a path has completed</summary> + void OnPathComplete (Path path) { + OnPathComplete(path, true, true); + } + + /// <summary> + /// Called when a path has completed. + /// Will post process it and return it by calling <see cref="tmpPathCallback"/> and <see cref="pathCallback"/> + /// </summary> + void OnPathComplete (Path p, bool runModifiers, bool sendCallbacks) { + if (p != null && p != path && sendCallbacks) { + return; + } + + if (this == null || p == null || p != path) + return; + + if (!path.error && runModifiers) { + // This will send the path for post processing to modifiers attached to this Seeker + RunModifiers(ModifierPass.PostProcess, path); + } + + if (sendCallbacks) { + p.Claim(this); + +#if UNITY_EDITOR + lastCompletedNodePath = p.path; + lastCompletedVectorPath = p.vectorPath; +#endif + + #pragma warning disable 618 + if (tmpPathCallback == null && pathCallback == null) { +#if UNITY_EDITOR + // This checks for a common error that people make when they upgrade from an older version + // This will be removed in a future version to avoid the slight performance cost. + if (TryGetComponent<IAstarAI>(out var ai)) { + Debug.LogWarning("A path was calculated, but no callback was specified when calling StartPath. If you wanted a movement script to use this path, use <b>ai.SetPath</b> instead of calling StartPath on the Seeker directly. The path will be forwarded to the attached movement script, but this behavior will be removed in the future.", this); + ai.SetPath(p); + } +#endif + } else { + // This will send the path to the callback (if any) specified when calling StartPath + if (tmpPathCallback != null) { + tmpPathCallback(p); + } + + // This will send the path to any script which has registered to the callback + if (pathCallback != null) { + pathCallback(p); + } + } + #pragma warning restore 618 + + // Note: it is important that #prevPath is kept alive (i.e. not pooled) + // if we are drawing gizmos. + // It is also important that #path is kept alive since it can be returned + // from the GetCurrentPath method. + // Since #path will be copied to #prevPath it is sufficient that #prevPath + // is kept alive until it is replaced. + + // Recycle the previous path to reduce the load on the GC + if (prevPath != null) { + prevPath.Release(this, true); + } + + prevPath = p; + } + } + + /// <summary> + /// Called for each path in a MultiTargetPath. + /// Only post processes the path, does not return it. + /// </summary> + void OnPartialPathComplete (Path p) { + OnPathComplete(p, true, false); + } + + /// <summary>Called once for a MultiTargetPath. Only returns the path, does not post process.</summary> + void OnMultiPathComplete (Path p) { + OnPathComplete(p, false, true); + } + + /// <summary> + /// Queue a path to be calculated. + /// Since this method does not take a callback parameter, you should set the <see cref="pathCallback"/> field before calling this method. + /// + /// <code> + /// void Start () { + /// // Get the seeker component attached to this GameObject + /// var seeker = GetComponent<Seeker>(); + /// + /// // Schedule a new path request from the current position to a position 10 units forward. + /// // When the path has been calculated, the OnPathComplete method will be called, unless it was canceled by another path request + /// seeker.StartPath(transform.position, transform.position + Vector3.forward * 10, OnPathComplete); + /// + /// // Note that the path is NOT calculated at this point + /// // It has just been queued for calculation + /// } + /// + /// void OnPathComplete (Path path) { + /// // The path is now calculated! + /// + /// if (path.error) { + /// Debug.LogError("Path failed: " + path.errorLog); + /// return; + /// } + /// + /// // Cast the path to the path type we were using + /// var abPath = path as ABPath; + /// + /// // Draw the path in the scene view for 10 seconds + /// for (int i = 0; i < abPath.vectorPath.Count - 1; i++) { + /// Debug.DrawLine(abPath.vectorPath[i], abPath.vectorPath[i+1], Color.red, 10); + /// } + /// } + /// </code> + /// + /// Deprecated: Use <see cref="StartPath(Vector3,Vector3,OnPathDelegate)"/> instead. + /// </summary> + /// <param name="start">The start point of the path</param> + /// <param name="end">The end point of the path</param> + [System.Obsolete("Use the overload that takes a callback instead")] + public Path StartPath (Vector3 start, Vector3 end) { + return StartPath(start, end, null); + } + + /// <summary> + /// Queue a path to be calculated. + /// + /// The callback will be called when the path has been calculated (which may be several frames into the future). + /// Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) + /// + /// <code> + /// void Start () { + /// // Get the seeker component attached to this GameObject + /// var seeker = GetComponent<Seeker>(); + /// + /// // Schedule a new path request from the current position to a position 10 units forward. + /// // When the path has been calculated, the OnPathComplete method will be called, unless it was canceled by another path request + /// seeker.StartPath(transform.position, transform.position + Vector3.forward * 10, OnPathComplete); + /// + /// // Note that the path is NOT calculated at this point + /// // It has just been queued for calculation + /// } + /// + /// void OnPathComplete (Path path) { + /// // The path is now calculated! + /// + /// if (path.error) { + /// Debug.LogError("Path failed: " + path.errorLog); + /// return; + /// } + /// + /// // Cast the path to the path type we were using + /// var abPath = path as ABPath; + /// + /// // Draw the path in the scene view for 10 seconds + /// for (int i = 0; i < abPath.vectorPath.Count - 1; i++) { + /// Debug.DrawLine(abPath.vectorPath[i], abPath.vectorPath[i+1], Color.red, 10); + /// } + /// } + /// </code> + /// </summary> + /// <param name="start">The start point of the path</param> + /// <param name="end">The end point of the path</param> + /// <param name="callback">The function to call when the path has been calculated. If you don't want a callback (e.g. if you instead poll path.IsDone or use a similar method) you can set this to null.</param> + public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback) { + return StartPath(ABPath.Construct(start, end, null), callback); + } + + /// <summary> + /// Queue a path to be calculated. + /// + /// The callback will be called when the path has been calculated (which may be several frames into the future). + /// Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) + /// + /// <code> + /// // Schedule a path search that will only start searching the graphs with index 0 and 3 + /// seeker.StartPath(startPoint, endPoint, null, 1 << 0 | 1 << 3); + /// </code> + /// </summary> + /// <param name="start">The start point of the path</param> + /// <param name="end">The end point of the path</param> + /// <param name="callback">The function to call when the path has been calculated. If you don't want a callback (e.g. if you instead poll path.IsDone or use a similar method) you can set this to null.</param> + /// <param name="graphMask">Mask used to specify which graphs should be searched for close nodes. See #Pathfinding.NNConstraint.graphMask. This will override #graphMask for this path request.</param> + public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback, GraphMask graphMask) { + return StartPath(ABPath.Construct(start, end, null), callback, graphMask); + } + + /// <summary> + /// Queue a path to be calculated. + /// + /// Version: Since 4.1.x this method will no longer overwrite the graphMask on the path unless it is explicitly passed as a parameter (see other overloads of this method). + /// + /// This overload takes no callback parameter. Instead, it is expected that you poll the path for completion, or block until it is completed. + /// + /// See: <see cref="IsDone"/> + /// See: <see cref="Path.WaitForPath"/> + /// See: <see cref="Path.BlockUntilCalculated"/> + /// + /// However, <see cref="Path.IsDone"/> should not be used with the Seeker component. This is because while the path itself may be calculated, the Seeker may not have had time to run post processing modifiers on the path yet. + /// </summary> + /// <param name="p">The path to start calculating</param> + public Path StartPath (Path p) { + return StartPath(p, null); + } + + /// <summary> + /// Queue a path to be calculated. + /// + /// The callback will be called when the path has been calculated (which may be several frames into the future). + /// The callback will not be called if a new path request is started before this path request has been calculated. + /// </summary> + /// <param name="p">The path to start calculating</param> + /// <param name="callback">The function to call when the path has been calculated. If you don't want a callback (e.g. if you instead poll path.IsDone or use a similar method) you can set this to null.</param> + public Path StartPath (Path p, OnPathDelegate callback) { + // Set the graph mask only if the user has not changed it from the default value. + // This is not perfect as the user may have wanted it to be precisely -1 + // however it is the best detection that I can do. + // The non-default check is primarily for compatibility reasons to avoid breaking peoples existing code. + // The StartPath overloads with an explicit graphMask field should be used instead to set the graphMask. + if (p.nnConstraint.graphMask == -1) p.nnConstraint.graphMask = graphMask; + StartPathInternal(p, callback); + return p; + } + + /// <summary> + /// Call this function to start calculating a path. + /// + /// The callback will be called when the path has been calculated (which may be several frames into the future). + /// The callback will not be called if a new path request is started before this path request has been calculated. + /// </summary> + /// <param name="p">The path to start calculating</param> + /// <param name="callback">The function to call when the path has been calculated. If you don't want a callback (e.g. if you instead poll path.IsDone or use a similar method) you can set this to null.</param> + /// <param name="graphMask">Mask used to specify which graphs should be searched for close nodes. See #Pathfinding.GraphMask. This will override #graphMask for this path request.</param> + public Path StartPath (Path p, OnPathDelegate callback, GraphMask graphMask) { + p.nnConstraint.graphMask = graphMask; + StartPathInternal(p, callback); + return p; + } + + /// <summary>Internal method to start a path and mark it as the currently active path</summary> + void StartPathInternal (Path p, OnPathDelegate callback) { + var mtp = p as MultiTargetPath; + if (mtp != null) { + // TODO: Allocation, cache + var callbacks = new OnPathDelegate[mtp.targetPoints.Length]; + + for (int i = 0; i < callbacks.Length; i++) { + callbacks[i] = onPartialPathDelegate; + } + + mtp.callbacks = callbacks; + p.callback += OnMultiPathComplete; + } else { + p.callback += onPathDelegate; + } + + p.enabledTags = traversableTags; + p.tagPenalties = tagPenalties; + if (traversalProvider != null) p.traversalProvider = traversalProvider; + + // Cancel a previously requested path is it has not been processed yet and also make sure that it has not been recycled and used somewhere else + if (path != null && path.PipelineState <= PathState.Processing && path.CompleteState != PathCompleteState.Error && lastPathID == path.pathID) { + path.FailWithError("Canceled path because a new one was requested.\n"+ + "This happens when a new path is requested from the seeker when one was already being calculated.\n" + + "For example if a unit got a new order, you might request a new path directly instead of waiting for the now" + + " invalid path to be calculated. Which is probably what you want.\n" + + "If you are getting this a lot, you might want to consider how you are scheduling path requests."); + // No callback will be sent for the canceled path + } + + // Set p as the active path + path = p; + tmpPathCallback = callback; + + // Save the path id so we can make sure that if we cancel a path (see above) it should not have been recycled yet. + lastPathID = path.pathID; + + // Pre process the path + RunModifiers(ModifierPass.PreProcess, path); + + // Send the request to the pathfinder + AstarPath.StartPath(path); + } + + /// <summary> + /// Starts a Multi Target Path from one start point to multiple end points. + /// A Multi Target Path will search for all the end points in one search and will return all paths if pathsForAll is true, or only the shortest one if pathsForAll is false. + /// + /// callback and <see cref="pathCallback"/> will be called when the path has completed. Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) + /// + /// See: Pathfinding.MultiTargetPath + /// See: MultiTargetPathExample.cs (view in online documentation for working links) "Example of how to use multi-target-paths" + /// + /// <code> + /// var endPoints = new Vector3[] { + /// transform.position + Vector3.forward * 5, + /// transform.position + Vector3.right * 10, + /// transform.position + Vector3.back * 15 + /// }; + /// // Start a multi target path, where endPoints is a Vector3[] array. + /// // The pathsForAll parameter specifies if a path to every end point should be searched for + /// // or if it should only try to find the shortest path to any end point. + /// var path = seeker.StartMultiTargetPath(transform.position, endPoints, pathsForAll: true, callback: null); + /// path.BlockUntilCalculated(); + /// + /// if (path.error) { + /// Debug.LogError("Error calculating path: " + path.errorLog); + /// return; + /// } + /// + /// Debug.Log("The closest target was index " + path.chosenTarget); + /// + /// // Draw the path to all targets + /// foreach (var subPath in path.vectorPaths) { + /// for (int i = 0; i < subPath.Count - 1; i++) { + /// Debug.DrawLine(subPath[i], subPath[i+1], Color.green, 10); + /// } + /// } + /// + /// // Draw the path to the closest target + /// for (int i = 0; i < path.vectorPath.Count - 1; i++) { + /// Debug.DrawLine(path.vectorPath[i], path.vectorPath[i+1], Color.red, 10); + /// } + /// </code> + /// </summary> + /// <param name="start">The start point of the path</param> + /// <param name="endPoints">The end points of the path</param> + /// <param name="pathsForAll">Indicates whether or not a path to all end points should be searched for or only to the closest one</param> + /// <param name="callback">The function to call when the path has been calculated. If you don't want a callback (e.g. if you instead poll path.IsDone or use a similar method) you can set this to null.</param> + /// <param name="graphMask">Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask.</param> + public MultiTargetPath StartMultiTargetPath (Vector3 start, Vector3[] endPoints, bool pathsForAll, OnPathDelegate callback, int graphMask = -1) { + MultiTargetPath p = MultiTargetPath.Construct(start, endPoints, null, null); + + p.pathsForAll = pathsForAll; + StartPath(p, callback, graphMask); + return p; + } + + /// <summary> + /// Starts a Multi Target Path from multiple start points to a single target point. + /// A Multi Target Path will search from all start points to the target point in one search and will return all paths if pathsForAll is true, or only the shortest one if pathsForAll is false. + /// + /// callback and <see cref="pathCallback"/> will be called when the path has completed. Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) + /// + /// See: Pathfinding.MultiTargetPath + /// See: MultiTargetPathExample.cs (view in online documentation for working links) "Example of how to use multi-target-paths" + /// </summary> + /// <param name="startPoints">The start points of the path</param> + /// <param name="end">The end point of the path</param> + /// <param name="pathsForAll">Indicates whether or not a path from all start points should be searched for or only to the closest one</param> + /// <param name="callback">The function to call when the path has been calculated. If you don't want a callback (e.g. if you instead poll path.IsDone or use a similar method) you can set this to null.</param> + /// <param name="graphMask">Mask used to specify which graphs should be searched for close nodes. See Pathfinding.NNConstraint.graphMask.</param> + public MultiTargetPath StartMultiTargetPath (Vector3[] startPoints, Vector3 end, bool pathsForAll, OnPathDelegate callback, int graphMask = -1) { + MultiTargetPath p = MultiTargetPath.Construct(startPoints, end, null, null); + + p.pathsForAll = pathsForAll; + StartPath(p, callback, graphMask); + return p; + } + +#if UNITY_EDITOR + /// <summary>Draws gizmos for the Seeker</summary> + public override void DrawGizmos () { + if (lastCompletedNodePath == null || !drawGizmos) { + return; + } + + if (detailedGizmos && lastCompletedNodePath != null) { + using (Draw.WithColor(new Color(0.7F, 0.5F, 0.1F, 0.5F))) { + for (int i = 0; i < lastCompletedNodePath.Count-1; i++) { + Draw.Line((Vector3)lastCompletedNodePath[i].position, (Vector3)lastCompletedNodePath[i+1].position); + } + } + } + + if (lastCompletedVectorPath != null) { + using (Draw.WithColor(new Color(0, 1F, 0, 1F))) { + for (int i = 0; i < lastCompletedVectorPath.Count-1; i++) { + Draw.Line(lastCompletedVectorPath[i], lastCompletedVectorPath[i+1]); + } + } + } + } +#endif + + protected override void OnUpgradeSerializedData (ref Serialization.Migrations migrations, bool unityThread) { + if (graphMaskCompatibility != -1) { + graphMask = graphMaskCompatibility; + graphMaskCompatibility = -1; + } + base.OnUpgradeSerializedData(ref migrations, unityThread); + } + } +} diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/Seeker.cs.meta b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/Seeker.cs.meta new file mode 100644 index 0000000..30f5e18 --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/Seeker.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 373b52eb9bf8c40f785bb6947a1aee66 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 2c41d544537d6ee4a8ecd487b2ac9724, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/TurnBasedAI.cs b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/TurnBasedAI.cs new file mode 100644 index 0000000..2bce7cf --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/TurnBasedAI.cs @@ -0,0 +1,25 @@ +using UnityEngine; +using System.Collections.Generic; + +namespace Pathfinding.Examples { + /// <summary>Helper script in the example scene 'Turn Based'</summary> + [HelpURL("https://arongranberg.com/astar/documentation/stable/turnbasedai.html")] + public class TurnBasedAI : VersionedMonoBehaviour { + public int movementPoints = 2; + public BlockManager blockManager; + public SingleNodeBlocker blocker; + public GraphNode targetNode; + public BlockManager.TraversalProvider traversalProvider; + + void Start () { + blocker.BlockAtCurrentPosition(); + } + + protected override void Awake () { + base.Awake(); + // Set the traversal provider to block all nodes that are blocked by a SingleNodeBlocker + // except the SingleNodeBlocker owned by this AI (we don't want to be blocked by ourself) + traversalProvider = new BlockManager.TraversalProvider(blockManager, BlockManager.BlockMode.AllExceptSelector, new List<SingleNodeBlocker>() { blocker }); + } + } +} diff --git a/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/TurnBasedAI.cs.meta b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/TurnBasedAI.cs.meta new file mode 100644 index 0000000..4fa7210 --- /dev/null +++ b/Other/AstarPathfindingDemo/Packages/com.arongranberg.astar/Core/AI/TurnBasedAI.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8f95b80c439d6408b9afac9d013922e4 +timeCreated: 1453035991 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: |