Compare commits
4 Commits
master
...
feat/AR_Ar
Author | SHA1 | Date | |
---|---|---|---|
![]() |
19abc598af | ||
![]() |
d7b24a1c60 | ||
![]() |
42527078f7 | ||
![]() |
690e3fbd0b |
2
.gitignore
vendored
2
.gitignore
vendored
@ -78,4 +78,4 @@ crashlytics-build.properties
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/unity
|
||||
|
||||
IOT/docs/doxygen output/*
|
||||
IOT/docs/doxygen output/*
|
34
AR/.gitattributes
vendored
34
AR/.gitattributes
vendored
@ -1,36 +1,4 @@
|
||||
# 3D models
|
||||
*.3dm filter=lfs diff=lfs merge=lfs -text
|
||||
*.3ds filter=lfs diff=lfs merge=lfs -text
|
||||
*.blend filter=lfs diff=lfs merge=lfs -text
|
||||
*.c4d filter=lfs diff=lfs merge=lfs -text
|
||||
*.collada filter=lfs diff=lfs merge=lfs -text
|
||||
*.dae filter=lfs diff=lfs merge=lfs -text
|
||||
*.dxf filter=lfs diff=lfs merge=lfs -text
|
||||
*.fbx filter=lfs diff=lfs merge=lfs -text
|
||||
*.jas filter=lfs diff=lfs merge=lfs -text
|
||||
*.lws filter=lfs diff=lfs merge=lfs -text
|
||||
*.lxo filter=lfs diff=lfs merge=lfs -text
|
||||
*.ma filter=lfs diff=lfs merge=lfs -text
|
||||
*.max filter=lfs diff=lfs merge=lfs -text
|
||||
*.mb filter=lfs diff=lfs merge=lfs -text
|
||||
*.obj filter=lfs diff=lfs merge=lfs -text
|
||||
*.ply filter=lfs diff=lfs merge=lfs -text
|
||||
*.skp filter=lfs diff=lfs merge=lfs -text
|
||||
*.stl filter=lfs diff=lfs merge=lfs -text
|
||||
*.ztl filter=lfs diff=lfs merge=lfs -text
|
||||
# Audio
|
||||
*.aif filter=lfs diff=lfs merge=lfs -text
|
||||
*.aiff filter=lfs diff=lfs merge=lfs -text
|
||||
*.it filter=lfs diff=lfs merge=lfs -text
|
||||
*.mod filter=lfs diff=lfs merge=lfs -text
|
||||
*.mp3 filter=lfs diff=lfs merge=lfs -text
|
||||
*.ogg filter=lfs diff=lfs merge=lfs -text
|
||||
*.s3m filter=lfs diff=lfs merge=lfs -text
|
||||
*.wav filter=lfs diff=lfs merge=lfs -text
|
||||
*.xm filter=lfs diff=lfs merge=lfs -text
|
||||
# Fonts
|
||||
*.otf filter=lfs diff=lfs merge=lfs -text
|
||||
*.ttf filter=lfs diff=lfs merge=lfs -text
|
||||
|
||||
|
||||
# Collapse Unity-generated files on GitHub
|
||||
*.asset linguist-generated
|
||||
|
2
AR/Assets/AstarPathfindingProject.meta
generated
Normal file
2
AR/Assets/AstarPathfindingProject.meta
generated
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6942e1e80e8b54fde9147e843f1bec4f
|
@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "AstarPathfindingProject",
|
||||
"references": [],
|
||||
"optionalUnityReferences": [],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": false
|
||||
}
|
7
AR/Assets/AstarPathfindingProject/AstarPathfindingProject.asmdef.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/AstarPathfindingProject.asmdef.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: efa45043feb7e4147a305b73b5cea642
|
||||
AssemblyDefinitionImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
9
AR/Assets/AstarPathfindingProject/Behaviors.meta
generated
Normal file
9
AR/Assets/AstarPathfindingProject/Behaviors.meta
generated
Normal file
@ -0,0 +1,9 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5eeb3c5df5ca840d3ae6b93e6b207d74
|
||||
folderAsset: yes
|
||||
timeCreated: 1497206641
|
||||
licenseType: Pro
|
||||
DefaultImporter:
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@ -0,0 +1,39 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
|
||||
namespace Pathfinding {
|
||||
/// <summary>
|
||||
/// Sets the destination of an AI to the position of a specified object.
|
||||
/// This component should be attached to a GameObject together with a movement script such as AIPath, RichAI or AILerp.
|
||||
/// This component will then make the AI move towards the <see cref="target"/> set on this component.
|
||||
///
|
||||
/// See: <see cref="Pathfinding.IAstarAI.destination"/>
|
||||
///
|
||||
/// [Open online documentation to see images]
|
||||
/// </summary>
|
||||
[UniqueComponent(tag = "ai.destination")]
|
||||
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_a_i_destination_setter.php")]
|
||||
public class AIDestinationSetter : VersionedMonoBehaviour {
|
||||
/// <summary>The object that the AI should move to</summary>
|
||||
public Transform target;
|
||||
IAstarAI ai;
|
||||
|
||||
void OnEnable () {
|
||||
ai = GetComponent<IAstarAI>();
|
||||
// Update the destination right before searching for a path as well.
|
||||
// This is enough in theory, but this script will also update the destination every
|
||||
// frame as the destination is used for debugging and may be used for other things by other
|
||||
// scripts as well. So it makes sense that it is up to date every frame.
|
||||
if (ai != null) ai.onSearchPath += Update;
|
||||
}
|
||||
|
||||
void OnDisable () {
|
||||
if (ai != null) ai.onSearchPath -= Update;
|
||||
}
|
||||
|
||||
/// <summary>Updates the AI's destination every frame</summary>
|
||||
void Update () {
|
||||
if (target != null && ai != null) ai.destination = target.position;
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Behaviors/AIDestinationSetter.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Behaviors/AIDestinationSetter.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c9679e68a0f1144e79c664d9a11ca121
|
||||
timeCreated: 1495015523
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
59
AR/Assets/AstarPathfindingProject/Behaviors/Patrol.cs
Normal file
59
AR/Assets/AstarPathfindingProject/Behaviors/Patrol.cs
Normal file
@ -0,0 +1,59 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
|
||||
namespace Pathfinding {
|
||||
/// <summary>
|
||||
/// Simple patrol behavior.
|
||||
/// This will set the destination on the agent so that it moves through the sequence of objects in the <see cref="targets"/> array.
|
||||
/// Upon reaching a target it will wait for <see cref="delay"/> seconds.
|
||||
///
|
||||
/// See: <see cref="Pathfinding.AIDestinationSetter"/>
|
||||
/// See: <see cref="Pathfinding.AIPath"/>
|
||||
/// See: <see cref="Pathfinding.RichAI"/>
|
||||
/// See: <see cref="Pathfinding.AILerp"/>
|
||||
/// </summary>
|
||||
[UniqueComponent(tag = "ai.destination")]
|
||||
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_patrol.php")]
|
||||
public class Patrol : VersionedMonoBehaviour {
|
||||
/// <summary>Target points to move to in order</summary>
|
||||
public Transform[] targets;
|
||||
|
||||
/// <summary>Time in seconds to wait at each target</summary>
|
||||
public float delay = 0;
|
||||
|
||||
/// <summary>Current target index</summary>
|
||||
int index;
|
||||
|
||||
IAstarAI agent;
|
||||
float switchTime = float.PositiveInfinity;
|
||||
|
||||
protected override void Awake () {
|
||||
base.Awake();
|
||||
agent = GetComponent<IAstarAI>();
|
||||
}
|
||||
|
||||
/// <summary>Update is called once per frame</summary>
|
||||
void Update () {
|
||||
if (targets.Length == 0) return;
|
||||
|
||||
bool search = false;
|
||||
|
||||
// Note: using reachedEndOfPath and pathPending instead of reachedDestination here because
|
||||
// if the destination cannot be reached by the agent, we don't want it to get stuck, we just want it to get as close as possible and then move on.
|
||||
if (agent.reachedEndOfPath && !agent.pathPending && float.IsPositiveInfinity(switchTime)) {
|
||||
switchTime = Time.time + delay;
|
||||
}
|
||||
|
||||
if (Time.time >= switchTime) {
|
||||
index = index + 1;
|
||||
search = true;
|
||||
switchTime = float.PositiveInfinity;
|
||||
}
|
||||
|
||||
index = index % targets.Length;
|
||||
agent.destination = targets[index].position;
|
||||
|
||||
if (search) agent.SearchPath();
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Behaviors/Patrol.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Behaviors/Patrol.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 22e6c29e32504465faa943c537d8029b
|
||||
timeCreated: 1495286303
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
1998
AR/Assets/AstarPathfindingProject/CHANGELOG.md
Normal file
1998
AR/Assets/AstarPathfindingProject/CHANGELOG.md
Normal file
File diff suppressed because it is too large
Load Diff
7
AR/Assets/AstarPathfindingProject/CHANGELOG.md.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/CHANGELOG.md.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e271255bdfe8941f9ab0acccbb14dd82
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
2
AR/Assets/AstarPathfindingProject/Core.meta
generated
Normal file
2
AR/Assets/AstarPathfindingProject/Core.meta
generated
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b6b8abb917bca4ce0ad1b26452b3c58d
|
2
AR/Assets/AstarPathfindingProject/Core/AI.meta
generated
Normal file
2
AR/Assets/AstarPathfindingProject/Core/AI.meta
generated
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5ab9be352d07b44e68ad7c1a03eef3a5
|
774
AR/Assets/AstarPathfindingProject/Core/AI/AIBase.cs
Normal file
774
AR/Assets/AstarPathfindingProject/Core/AI/AIBase.cs
Normal file
@ -0,0 +1,774 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using UnityEngine.Serialization;
|
||||
|
||||
namespace Pathfinding {
|
||||
using Pathfinding.RVO;
|
||||
using Pathfinding.Util;
|
||||
|
||||
/// <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>\copydoc Pathfinding::IAstarAI::radius</summary>
|
||||
public float radius = 0.5f;
|
||||
|
||||
/// <summary>\copydoc Pathfinding::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 \reflink{autoRepath.interval}.
|
||||
/// See: \reflink{AutoRepathPolicy}
|
||||
/// </summary>
|
||||
public float repathRate {
|
||||
get {
|
||||
return this.autoRepath.interval;
|
||||
}
|
||||
set {
|
||||
this.autoRepath.interval = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// \copydoc Pathfinding::IAstarAI::canSearch
|
||||
/// Deprecated: This has been superseded by \reflink{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>\copydoc Pathfinding::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>
|
||||
/// 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 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>
|
||||
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>
|
||||
/// 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 IMovementPlane movementPlane = GraphTransform.identityTransform;
|
||||
|
||||
/// <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>Last frame index when <see cref="prevPosition1"/> was updated</summary>
|
||||
protected int prevFrame;
|
||||
|
||||
/// <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;
|
||||
|
||||
[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>
|
||||
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 {
|
||||
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::destination</summary>
|
||||
public Vector3 destination { get; set; }
|
||||
|
||||
/// <summary>\copydoc Pathfinding::IAstarAI::velocity</summary>
|
||||
public Vector3 velocity {
|
||||
get {
|
||||
return lastDeltaTime > 0.000001f ? (prevPosition1 - prevPosition2) / lastDeltaTime : Vector3.zero;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Velocity that this agent wants to move with.
|
||||
/// Includes gravity and local avoidance if applicable.
|
||||
/// </summary>
|
||||
public Vector3 desiredVelocity { get { return lastDeltaTime > 0.00001f ? movementPlane.ToWorld(lastDeltaPosition / lastDeltaTime, verticalVelocity) : Vector3.zero; } }
|
||||
|
||||
/// <summary>\copydoc Pathfinding::IAstarAI::isStopped</summary>
|
||||
public bool isStopped { get; set; }
|
||||
|
||||
/// <summary>\copydoc Pathfinding::IAstarAI::onSearchPath</summary>
|
||||
public System.Action onSearchPath { get; set; }
|
||||
|
||||
/// <summary>True if the path should be automatically recalculated as soon as possible</summary>
|
||||
protected virtual bool shouldRecalculatePath {
|
||||
get {
|
||||
return !waitingForPathCalculation && autoRepath.ShouldRecalculatePath((IAstarAI)this);
|
||||
}
|
||||
}
|
||||
|
||||
protected AIBase () {
|
||||
// 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>
|
||||
/// 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;
|
||||
seeker = GetComponent<Seeker>();
|
||||
// Find attached movement components
|
||||
controller = GetComponent<CharacterController>();
|
||||
rigid = GetComponent<Rigidbody>();
|
||||
rigid2D = GetComponent<Rigidbody2D>();
|
||||
}
|
||||
|
||||
/// <summary>Called when the component is enabled</summary>
|
||||
protected virtual void OnEnable () {
|
||||
FindComponents();
|
||||
// Make sure we receive callbacks when paths are calculated
|
||||
seeker.pathCallback += OnPathComplete;
|
||||
Init();
|
||||
}
|
||||
|
||||
/// <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>\copydoc Pathfinding::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 (clearPath) SearchPath();
|
||||
}
|
||||
|
||||
protected void CancelCurrentPathRequest () {
|
||||
waitingForPathCalculation = false;
|
||||
// Abort calculation of the current path
|
||||
if (seeker != null) seeker.CancelCurrentPathRequest();
|
||||
}
|
||||
|
||||
protected virtual void OnDisable () {
|
||||
ClearPath();
|
||||
|
||||
// Make sure we no longer receive callbacks when paths complete
|
||||
seeker.pathCallback -= OnPathComplete;
|
||||
|
||||
velocity2D = Vector3.zero;
|
||||
accumulatedMovementDelta = Vector3.zero;
|
||||
verticalVelocity = 0f;
|
||||
lastDeltaTime = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called every frame.
|
||||
/// If no rigidbodies are used then all movement happens here.
|
||||
/// </summary>
|
||||
protected virtual void Update () {
|
||||
if (shouldRecalculatePath) SearchPath();
|
||||
|
||||
// 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 (rigid == null && rigid2D == null && canMove) {
|
||||
Vector3 nextPosition;
|
||||
Quaternion nextRotation;
|
||||
MovementUpdate(Time.deltaTime, out nextPosition, out nextRotation);
|
||||
FinalizeMovement(nextPosition, nextRotation);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called every physics update.
|
||||
/// If rigidbodies are used then all movement happens here.
|
||||
/// </summary>
|
||||
protected virtual void FixedUpdate () {
|
||||
if (!(rigid == null && rigid2D == null) && canMove) {
|
||||
Vector3 nextPosition;
|
||||
Quaternion nextRotation;
|
||||
MovementUpdate(Time.fixedDeltaTime, out nextPosition, out nextRotation);
|
||||
FinalizeMovement(nextPosition, nextRotation);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>\copydoc Pathfinding::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>\copydoc Pathfinding::IAstarAI::SearchPath</summary>
|
||||
public virtual void SearchPath () {
|
||||
if (float.IsPositiveInfinity(destination.x)) return;
|
||||
if (onSearchPath != null) onSearchPath();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/// <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 <see cref="SetPath(null)"/>
|
||||
///
|
||||
/// See: <see cref="SetPath"/>
|
||||
/// See: <see cref="isStopped"/>
|
||||
/// </summary>
|
||||
protected abstract void ClearPath();
|
||||
|
||||
/// <summary>\copydoc Pathfinding::IAstarAI::SetPath</summary>
|
||||
public void SetPath (Path path) {
|
||||
if (path == null) {
|
||||
CancelCurrentPathRequest();
|
||||
ClearPath();
|
||||
} else if (path.PipelineState == PathState.Created) {
|
||||
// Path has not started calculation yet
|
||||
waitingForPathCalculation = true;
|
||||
seeker.CancelCurrentPathRequest();
|
||||
seeker.StartPath(path);
|
||||
autoRepath.DidRecalculatePath(destination);
|
||||
} else if (path.PipelineState == PathState.Returned) {
|
||||
// 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();
|
||||
else throw new System.ArgumentException("If you calculate the path using seeker.StartPath then this script will pick up the calculated path anyway as it listens for all paths the Seeker finishes calculating. You should not call SetPath in that case.");
|
||||
|
||||
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 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 (Vector2 position, float distanceToEndOfPath, float 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);
|
||||
}
|
||||
|
||||
/// <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="maxDegrees">Maximum number of degrees to rotate this frame.</param>
|
||||
protected Quaternion SimulateRotationTowards (Vector2 direction, float maxDegrees) {
|
||||
if (direction != Vector2.zero) {
|
||||
Quaternion targetRotation = Quaternion.LookRotation(movementPlane.ToWorld(direction, 0), movementPlane.ToWorld(Vector2.zero, 1));
|
||||
// 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, maxDegrees);
|
||||
}
|
||||
return simulatedRotation;
|
||||
}
|
||||
|
||||
/// <summary>\copydoc Pathfinding::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 () {
|
||||
var currentFrame = Time.frameCount;
|
||||
|
||||
if (currentFrame != prevFrame) prevPosition2 = prevPosition1;
|
||||
prevPosition1 = position;
|
||||
prevFrame = currentFrame;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// 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) {
|
||||
RaycastHit hit;
|
||||
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 hit, 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 hit.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);
|
||||
|
||||
protected virtual void OnDrawGizmos () {
|
||||
if (!Application.isPlaying || !enabled) FindComponents();
|
||||
|
||||
var color = ShapeGizmoColor;
|
||||
if (orientation == OrientationMode.YAxisForward) {
|
||||
Draw.Gizmos.Cylinder(position, Vector3.forward, 0, radius * tr.localScale.x, color);
|
||||
} else {
|
||||
Draw.Gizmos.Cylinder(position, rotation * Vector3.up, tr.localScale.y * height, radius * tr.localScale.x, color);
|
||||
}
|
||||
|
||||
if (!float.IsPositiveInfinity(destination.x) && Application.isPlaying) Draw.Gizmos.CircleXZ(destination, 0.2f, Color.blue);
|
||||
|
||||
autoRepath.DrawGizmos((IAstarAI)this);
|
||||
}
|
||||
|
||||
protected override void Reset () {
|
||||
ResetShape();
|
||||
base.Reset();
|
||||
}
|
||||
|
||||
void ResetShape () {
|
||||
var cc = GetComponent<CharacterController>();
|
||||
|
||||
if (cc != null) {
|
||||
radius = cc.radius;
|
||||
height = Mathf.Max(radius*2, cc.height);
|
||||
}
|
||||
}
|
||||
|
||||
protected override int OnUpgradeSerializedData (int version, bool unityThread) {
|
||||
if (unityThread && !float.IsNaN(centerOffsetCompatibility)) {
|
||||
height = centerOffsetCompatibility*2;
|
||||
ResetShape();
|
||||
centerOffsetCompatibility = float.NaN;
|
||||
}
|
||||
#pragma warning disable 618
|
||||
if (unityThread && targetCompatibility != null) target = targetCompatibility;
|
||||
#pragma warning restore 618
|
||||
if (version <= 3) {
|
||||
repathRate = repathRateCompatibility;
|
||||
canSearch = canSearchCompability;
|
||||
}
|
||||
return 5;
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/AI/AIBase.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/AI/AIBase.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a08f67bbe580e4ddfaebd06363c9cc97
|
||||
timeCreated: 1496932372
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 100
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
701
AR/Assets/AstarPathfindingProject/Core/AI/AILerp.cs
Normal file
701
AR/Assets/AstarPathfindingProject/Core/AI/AILerp.cs
Normal file
@ -0,0 +1,701 @@
|
||||
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"/>.
|
||||
///
|
||||
/// \ingroup movementscripts
|
||||
/// </summary>
|
||||
[RequireComponent(typeof(Seeker))]
|
||||
[AddComponentMenu("Pathfinding/AI/AILerp (2D,3D)")]
|
||||
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_a_i_lerp.php")]
|
||||
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 \reflink{autoRepath.interval}.
|
||||
/// See: \reflink{AutoRepathPolicy}
|
||||
/// </summary>
|
||||
public float repathRate {
|
||||
get {
|
||||
return this.autoRepath.interval;
|
||||
}
|
||||
set {
|
||||
this.autoRepath.interval = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// \copydoc Pathfinding::IAstarAI::canSearch
|
||||
/// Deprecated: This has been superseded by \reflink{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>
|
||||
/// 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>
|
||||
/// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 Mathf.Max(interpolator.remainingDistance, 0);
|
||||
}
|
||||
set {
|
||||
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 interpolator = 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"/>
|
||||
/// See: <see cref="RepeatTrySearchPath"/>
|
||||
/// </summary>
|
||||
protected virtual void Start () {
|
||||
startHasRun = true;
|
||||
Init();
|
||||
}
|
||||
|
||||
/// <summary>Called when the component is enabled</summary>
|
||||
protected virtual void OnEnable () {
|
||||
// Make sure we receive callbacks when paths complete
|
||||
seeker.pathCallback += 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();
|
||||
// Make sure we no longer receive callbacks when paths complete
|
||||
seeker.pathCallback -= OnPathComplete;
|
||||
}
|
||||
|
||||
/// <summary>\copydoc Pathfinding::IAstarAI::GetRemainingPath</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;
|
||||
}
|
||||
|
||||
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((IAstarAI)this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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));
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// </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;
|
||||
|
||||
// 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;
|
||||
interpolator.SetPath(null);
|
||||
}
|
||||
|
||||
/// <summary>\copydoc Pathfinding::IAstarAI::SetPath</summary>
|
||||
public void SetPath (Path path) {
|
||||
if (path == null) {
|
||||
ClearPath();
|
||||
} else if (path.PipelineState == PathState.Created) {
|
||||
// Path has not started calculation yet
|
||||
canSearchAgain = false;
|
||||
seeker.CancelCurrentPathRequest();
|
||||
seeker.StartPath(path);
|
||||
autoRepath.DidRecalculatePath(destination);
|
||||
} else if (path.PipelineState == PathState.Returned) {
|
||||
// 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();
|
||||
else throw new System.ArgumentException("If you calculate the path using seeker.StartPath then this script will pick up the calculated path anyway as it listens for all paths the Seeker finishes calculating. You should not call SetPath in that case.");
|
||||
|
||||
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;
|
||||
|
||||
interpolator.SetPath(path.vectorPath);
|
||||
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>
|
||||
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 int OnUpgradeSerializedData (int version, bool unityThread) {
|
||||
#pragma warning disable 618
|
||||
if (unityThread && targetCompatibility != null) target = targetCompatibility;
|
||||
#pragma warning restore 618
|
||||
|
||||
if (version <= 3) {
|
||||
repathRate = repathRateCompatibility;
|
||||
canSearch = canSearchCompability;
|
||||
}
|
||||
return 4;
|
||||
}
|
||||
|
||||
public virtual void OnDrawGizmos () {
|
||||
tr = transform;
|
||||
autoRepath.DrawGizmos((IAstarAI)this);
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/AI/AILerp.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/AI/AILerp.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 847a14d4dc9cc43679ab34fc78e0182f
|
||||
timeCreated: 1454879612
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
491
AR/Assets/AstarPathfindingProject/Core/AI/AIPath.cs
Normal file
491
AR/Assets/AstarPathfindingProject/Core/AI/AIPath.cs
Normal file
@ -0,0 +1,491 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding {
|
||||
using Pathfinding.RVO;
|
||||
using Pathfinding.Util;
|
||||
|
||||
/// <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 <see cref="Update"/> or <see cref="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 <see cref="Update"/> (or <see cref="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="Pathfinding.Seeker"/> component which should be attached to the same GameObject as this script.
|
||||
/// Since this script will when waking up register to the <see cref="Pathfinding.Seeker.pathCallback"/> delegate this script will be notified every time a new path is calculated by the <see cref="OnPathComplete"/> method being called.
|
||||
/// It may take one or sometimes multiple frames for the path to be calculated, but finally the <see cref="OnPathComplete"/> method will be called and the current path that the AI is following will be replaced.
|
||||
/// </summary>
|
||||
[AddComponentMenu("Pathfinding/AI/AIPath (2D,3D)")]
|
||||
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>
|
||||
/// Distance to the end point to consider the end of path to be reached.
|
||||
/// When the end is within this distance then <see cref="OnTargetReached"/> will be called and <see cref="reachedEndOfPath"/> will return true.
|
||||
/// </summary>
|
||||
public float endReachedDistance = 0.2F;
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
public bool slowWhenNotFacingTarget = true;
|
||||
|
||||
/// <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="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>
|
||||
/// 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>Helper which calculates points along the current path</summary>
|
||||
protected PathInterpolator interpolator = 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 {
|
||||
get {
|
||||
return interpolator.valid ? interpolator.remainingDistance + movementPlane.ToPlane(interpolator.position - position).magnitude : float.PositiveInfinity;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>\copydoc Pathfinding::IAstarAI::reachedDestination</summary>
|
||||
public 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
|
||||
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::reachedEndOfPath</summary>
|
||||
public bool reachedEndOfPath { get; protected set; }
|
||||
|
||||
/// <summary>\copydoc Pathfinding::IAstarAI::hasPath</summary>
|
||||
public bool hasPath {
|
||||
get {
|
||||
return interpolator.valid;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>\copydoc Pathfinding::IAstarAI::pathPending</summary>
|
||||
public bool pathPending {
|
||||
get {
|
||||
return waitingForPathCalculation;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>\copydoc Pathfinding::IAstarAI::steeringTarget</summary>
|
||||
public Vector3 steeringTarget {
|
||||
get {
|
||||
return interpolator.valid ? interpolator.position : position;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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; } }
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>\copydoc Pathfinding::IAstarAI::GetRemainingPath</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);
|
||||
}
|
||||
|
||||
protected override void OnDisable () {
|
||||
base.OnDisable();
|
||||
|
||||
// Release current path so that it can be pooled
|
||||
if (path != null) path.Release(this);
|
||||
path = null;
|
||||
interpolator.SetPath(null);
|
||||
reachedEndOfPath = 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.
|
||||
///
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public virtual void OnTargetReached () {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when a requested path has been calculated.
|
||||
/// A path is first requested by <see cref="UpdatePath"/>, 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;
|
||||
|
||||
// Make sure the path contains at least 2 points
|
||||
if (path.vectorPath.Count == 1) path.vectorPath.Add(path.vectorPath[0]);
|
||||
interpolator.SetPath(path.vectorPath);
|
||||
|
||||
var graph = path.path.Count > 0 ? AstarData.GetGraph(path.path[0]) as ITransformedGraph : null;
|
||||
movementPlane = graph != null ? graph.transform : (orientation == OrientationMode.YAxisForward ? new GraphTransform(Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(-90, 270, 90), Vector3.one)) : GraphTransform.identityTransform);
|
||||
|
||||
// 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();
|
||||
if (path != null) path.Release(this);
|
||||
path = null;
|
||||
interpolator.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;
|
||||
|
||||
// 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
|
||||
float distanceToEnd = dir.magnitude + Mathf.Max(0, interpolator.remainingDistance);
|
||||
|
||||
// Check if we have reached the target
|
||||
var prevTargetReached = reachedEndOfPath;
|
||||
reachedEndOfPath = distanceToEnd <= endReachedDistance && interpolator.valid;
|
||||
if (!prevTargetReached && reachedEndOfPath) OnTargetReached();
|
||||
float slowdown;
|
||||
|
||||
// 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 (interpolator.valid && !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.
|
||||
slowdown = distanceToEnd < slowdownDistance? Mathf.Sqrt(distanceToEnd / slowdownDistance) : 1;
|
||||
|
||||
if (reachedEndOfPath && whenCloseToDestination == CloseToDestinationMode.Stop) {
|
||||
// Slow down as quickly as possible
|
||||
velocity2D -= Vector2.ClampMagnitude(velocity2D, currentAcceleration * deltaTime);
|
||||
} else {
|
||||
velocity2D += MovementUtilities.CalculateAccelerationToReachPoint(dir, dir.normalized*maxSpeed, velocity2D, currentAcceleration, rotationSpeed, maxSpeed, forwards) * deltaTime;
|
||||
}
|
||||
} else {
|
||||
slowdown = 1;
|
||||
// Slow down as quickly as possible
|
||||
velocity2D -= Vector2.ClampMagnitude(velocity2D, currentAcceleration * deltaTime);
|
||||
}
|
||||
|
||||
velocity2D = MovementUtilities.ClampVelocity(velocity2D, maxSpeed, slowdown, slowWhenNotFacingTarget && enableRotation, forwards);
|
||||
|
||||
ApplyGravity(deltaTime);
|
||||
|
||||
|
||||
// Set how much the agent wants to move during this frame
|
||||
var delta2D = lastDeltaPosition = CalculateDeltaToMoveThisFrame(movementPlane.ToPlane(currentPosition), distanceToEnd, deltaTime);
|
||||
nextPosition = currentPosition + movementPlane.ToWorld(delta2D, verticalVelocity * lastDeltaTime);
|
||||
CalculateNextRotation(slowdown, out nextRotation);
|
||||
}
|
||||
|
||||
protected virtual void CalculateNextRotation (float slowdown, out Quaternion nextRotation) {
|
||||
if (lastDeltaTime > 0.00001f && enableRotation) {
|
||||
Vector2 desiredRotationDirection;
|
||||
desiredRotationDirection = velocity2D;
|
||||
|
||||
// Rotate towards the direction we are moving in.
|
||||
// Don't rotate when we are very close to the target.
|
||||
var currentRotationSpeed = rotationSpeed * Mathf.Max(0, (slowdown - 0.3f) / 0.7f);
|
||||
nextRotation = SimulateRotationTowards(desiredRotationDirection, currentRotationSpeed * lastDeltaTime);
|
||||
} else {
|
||||
// TODO: simulatedRotation
|
||||
nextRotation = rotation;
|
||||
}
|
||||
}
|
||||
|
||||
static NNConstraint cachedNNConstraint = NNConstraint.Default;
|
||||
protected override Vector3 ClampToNavmesh (Vector3 position, out bool positionChanged) {
|
||||
if (constrainInsideGraph) {
|
||||
cachedNNConstraint.tags = seeker.traversableTags;
|
||||
cachedNNConstraint.graphMask = seeker.graphMask;
|
||||
cachedNNConstraint.distanceXZ = true;
|
||||
var clampedPosition = AstarPath.active.GetNearest(position, cachedNNConstraint).position;
|
||||
|
||||
// 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);
|
||||
|
||||
protected override void OnDrawGizmos () {
|
||||
base.OnDrawGizmos();
|
||||
if (alwaysDrawGizmos) OnDrawGizmosInternal();
|
||||
}
|
||||
|
||||
protected override void OnDrawGizmosSelected () {
|
||||
base.OnDrawGizmosSelected();
|
||||
if (!alwaysDrawGizmos) OnDrawGizmosInternal();
|
||||
}
|
||||
|
||||
void OnDrawGizmosInternal () {
|
||||
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) * (UnityEditor.Selection.gameObjects.Length == 1 ? 1 : 0);
|
||||
|
||||
if (alpha > 0) {
|
||||
// Make sure the scene view is repainted while the gizmos are visible
|
||||
if (!alwaysDrawGizmos) UnityEditor.SceneView.RepaintAll();
|
||||
Draw.Gizmos.Line(position, steeringTarget, GizmoColor * new Color(1, 1, 1, alpha));
|
||||
Gizmos.matrix = Matrix4x4.TRS(position, transform.rotation * (orientation == OrientationMode.YAxisForward ? Quaternion.Euler(-90, 0, 0) : Quaternion.identity), Vector3.one);
|
||||
Draw.Gizmos.CircleXZ(Vector3.zero, pickNextWaypointDist, GizmoColor * new Color(1, 1, 1, alpha));
|
||||
Draw.Gizmos.CircleXZ(Vector3.zero, slowdownDistance, Color.Lerp(GizmoColor, Color.red, 0.5f) * new Color(1, 1, 1, alpha));
|
||||
Draw.Gizmos.CircleXZ(Vector3.zero, endReachedDistance, Color.Lerp(GizmoColor, Color.red, 0.8f) * new Color(1, 1, 1, alpha));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
protected override int OnUpgradeSerializedData (int version, bool unityThread) {
|
||||
// Approximately convert from a damping value to a degrees per second value.
|
||||
if (version < 1) rotationSpeed *= 90;
|
||||
return base.OnUpgradeSerializedData(version, unityThread);
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/AI/AIPath.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/AI/AIPath.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f6eb1402c17e84a9282a7f0f62eb584f
|
||||
timeCreated: 1491225739
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
392
AR/Assets/AstarPathfindingProject/Core/AI/IAstarAI.cs
Normal file
392
AR/Assets/AstarPathfindingProject/Core/AI/IAstarAI.cs
Normal file
@ -0,0 +1,392 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
|
||||
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: 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"/>
|
||||
/// </summary>
|
||||
Vector3 desiredVelocity { get; }
|
||||
|
||||
/// <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="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>
|
||||
/// 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>
|
||||
/// 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 script 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>
|
||||
/// 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.
|
||||
/// Note that if you calculate the path using seeker.StartPath then this script will already pick it up because it is listening for
|
||||
/// all paths that the Seeker finishes calculating. In that case you do not need to call this function.
|
||||
///
|
||||
/// 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.
|
||||
///
|
||||
/// <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);
|
||||
///
|
||||
/// // If you want to make use of properties like ai.reachedDestination or ai.remainingDistance or similar
|
||||
/// // you should also set the destination property to something reasonable.
|
||||
/// // Since the agent's own path recalculation is disabled, setting this will not affect how the paths are calculated.
|
||||
/// // ai.destination = ...
|
||||
/// </code>
|
||||
/// </summary>
|
||||
void SetPath(Path path);
|
||||
|
||||
/// <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.
|
||||
///
|
||||
/// 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 AILerp script) if it does not have
|
||||
/// any concept of being moved externally.
|
||||
///
|
||||
/// 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>
|
||||
/// </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);
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/AI/IAstarAI.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/AI/IAstarAI.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b7438f3f6b9404f05ab7f584f92aa7d5
|
||||
timeCreated: 1495013922
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@ -0,0 +1,4 @@
|
||||
|
||||
// This file has been removed from the project. Since UnityPackages cannot
|
||||
// delete files, only replace them, this message is left here to prevent old
|
||||
// files from causing compiler errors
|
7
AR/Assets/AstarPathfindingProject/Core/AI/NavmeshController.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/AI/NavmeshController.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 20549335d45df4a329ece093b865221b
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
507
AR/Assets/AstarPathfindingProject/Core/AI/Seeker.cs
Normal file
507
AR/Assets/AstarPathfindingProject/Core/AI/Seeker.cs
Normal file
@ -0,0 +1,507 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
#if UNITY_5_5_OR_NEWER
|
||||
using UnityEngine.Profiling;
|
||||
#endif
|
||||
|
||||
namespace Pathfinding {
|
||||
/// <summary>
|
||||
/// Handles path calls for a single unit.
|
||||
/// \ingroup relevant
|
||||
/// 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.
|
||||
///
|
||||
/// [Open online documentation to see images]
|
||||
///
|
||||
/// See: calling-pathfinding (view in online documentation for working links)
|
||||
/// See: modifiers (view in online documentation for working links)
|
||||
/// </summary>
|
||||
[AddComponentMenu("Pathfinding/Seeker")]
|
||||
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_seeker.php")]
|
||||
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.
|
||||
///
|
||||
/// Note: This array should always have a length of 32 otherwise the system will ignore it.
|
||||
///
|
||||
/// 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.Default;
|
||||
///
|
||||
/// 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>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.\n
|
||||
/// A temporary callback can also be set when calling StartPath, but that delegate will only be called for that path
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>Used for drawing gizmos</summary>
|
||||
[System.NonSerialized]
|
||||
List<Vector3> lastCompletedVectorPath;
|
||||
|
||||
/// <summary>Used for drawing gizmos</summary>
|
||||
[System.NonSerialized]
|
||||
List<GraphNode> lastCompletedNodePath;
|
||||
|
||||
/// <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>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;
|
||||
}
|
||||
|
||||
/// <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: pathCallback
|
||||
/// </summary>
|
||||
public Path GetCurrentPath () {
|
||||
return 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>
|
||||
public 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: RunModifiers
|
||||
/// \since Added in 3.2
|
||||
/// </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
|
||||
/// since the path might be completely calculated, but it has not yet been processed by the Seeker.
|
||||
///
|
||||
/// \since Added in 3.0.8
|
||||
/// Version: Behaviour changed in 3.2
|
||||
/// </summary>
|
||||
public bool IsDone () {
|
||||
return path == null || path.PipelineState >= PathState.Returned;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when a path has completed.
|
||||
/// This should have been implemented as optional parameter values, but that didn't seem to work very well with delegates (the values weren't the default ones)
|
||||
/// See: OnPathComplete(Path,bool,bool)
|
||||
/// </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);
|
||||
|
||||
lastCompletedNodePath = p.path;
|
||||
lastCompletedVectorPath = p.vectorPath;
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 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>
|
||||
/// Returns a new path instance.
|
||||
/// The path will be taken from the path pool if path recycling is turned on.\n
|
||||
/// This path can be sent to <see cref="StartPath(Path,OnPathDelegate,int)"/> with no change, but if no change is required <see cref="StartPath(Vector3,Vector3,OnPathDelegate)"/> does just that.
|
||||
/// <code>
|
||||
/// var seeker = GetComponent<Seeker>();
|
||||
/// Path p = seeker.GetNewPath (transform.position, transform.position+transform.forward*100);
|
||||
/// // Disable heuristics on just this path for example
|
||||
/// p.heuristic = Heuristic.None;
|
||||
/// seeker.StartPath (p, OnPathComplete);
|
||||
/// </code>
|
||||
/// Deprecated: Use ABPath.Construct(start, end, null) instead.
|
||||
/// </summary>
|
||||
[System.Obsolete("Use ABPath.Construct(start, end, null) instead")]
|
||||
public ABPath GetNewPath (Vector3 start, Vector3 end) {
|
||||
// Construct a path with start and end points
|
||||
return ABPath.Construct(start, end, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Call this function to start calculating a path.
|
||||
/// Since this method does not take a callback parameter, you should set the <see cref="pathCallback"/> field before calling this method.
|
||||
/// </summary>
|
||||
/// <param name="start">The start point of the path</param>
|
||||
/// <param name="end">The end point of the path</param>
|
||||
public Path StartPath (Vector3 start, Vector3 end) {
|
||||
return StartPath(start, end, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Call this function to start calculating a path.
|
||||
///
|
||||
/// callback 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)
|
||||
/// </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</param>
|
||||
public Path StartPath (Vector3 start, Vector3 end, OnPathDelegate callback) {
|
||||
return StartPath(ABPath.Construct(start, end, null), callback);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Call this function to start calculating a path.
|
||||
///
|
||||
/// callback 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)
|
||||
/// </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</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>
|
||||
/// 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.
|
||||
///
|
||||
/// Version: Since 3.8.3 this method works properly if a MultiTargetPath is used.
|
||||
/// It now behaves identically to the StartMultiTargetPath(MultiTargetPath) method.
|
||||
///
|
||||
/// 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).
|
||||
/// </summary>
|
||||
/// <param name="p">The path to start calculating</param>
|
||||
/// <param name="callback">The function to call when the path has been calculated</param>
|
||||
public Path StartPath (Path p, OnPathDelegate callback = null) {
|
||||
// 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.
|
||||
///
|
||||
/// Version: Since 3.8.3 this method works properly if a MultiTargetPath is used.
|
||||
/// It now behaves identically to the StartMultiTargetPath(MultiTargetPath) method.
|
||||
/// </summary>
|
||||
/// <param name="p">The path to start calculating</param>
|
||||
/// <param name="callback">The function to call when the path has been calculated</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) {
|
||||
p.callback += onPathDelegate;
|
||||
|
||||
p.enabledTags = traversableTags;
|
||||
p.tagPenalties = tagPenalties;
|
||||
|
||||
// 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>Draws gizmos for the Seeker</summary>
|
||||
public void OnDrawGizmos () {
|
||||
if (lastCompletedNodePath == null || !drawGizmos) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (detailedGizmos) {
|
||||
Gizmos.color = new Color(0.7F, 0.5F, 0.1F, 0.5F);
|
||||
|
||||
if (lastCompletedNodePath != null) {
|
||||
for (int i = 0; i < lastCompletedNodePath.Count-1; i++) {
|
||||
Gizmos.DrawLine((Vector3)lastCompletedNodePath[i].position, (Vector3)lastCompletedNodePath[i+1].position);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Gizmos.color = new Color(0, 1F, 0, 1F);
|
||||
|
||||
if (lastCompletedVectorPath != null) {
|
||||
for (int i = 0; i < lastCompletedVectorPath.Count-1; i++) {
|
||||
Gizmos.DrawLine(lastCompletedVectorPath[i], lastCompletedVectorPath[i+1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected override int OnUpgradeSerializedData (int version, bool unityThread) {
|
||||
if (graphMaskCompatibility != -1) {
|
||||
Debug.Log("Loaded " + graphMaskCompatibility + " " + graphMask.value);
|
||||
graphMask = graphMaskCompatibility;
|
||||
graphMaskCompatibility = -1;
|
||||
}
|
||||
return base.OnUpgradeSerializedData(version, unityThread);
|
||||
}
|
||||
}
|
||||
}
|
7
AR/Assets/AstarPathfindingProject/Core/AI/Seeker.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/AI/Seeker.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 373b52eb9bf8c40f785bb6947a1aee66
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
25
AR/Assets/AstarPathfindingProject/Core/AI/TurnBasedAI.cs
Normal file
25
AR/Assets/AstarPathfindingProject/Core/AI/TurnBasedAI.cs
Normal file
@ -0,0 +1,25 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding.Examples {
|
||||
/// <summary>Helper script in the example scene 'Turn Based'</summary>
|
||||
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_examples_1_1_turn_based_a_i.php")]
|
||||
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 });
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/AI/TurnBasedAI.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/AI/TurnBasedAI.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8f95b80c439d6408b9afac9d013922e4
|
||||
timeCreated: 1453035991
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
733
AR/Assets/AstarPathfindingProject/Core/AstarData.cs
Normal file
733
AR/Assets/AstarPathfindingProject/Core/AstarData.cs
Normal file
@ -0,0 +1,733 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using Pathfinding.WindowsStore;
|
||||
using Pathfinding.Serialization;
|
||||
#if UNITY_WINRT && !UNITY_EDITOR
|
||||
//using MarkerMetro.Unity.WinLegacy.IO;
|
||||
//using MarkerMetro.Unity.WinLegacy.Reflection;
|
||||
#endif
|
||||
|
||||
namespace Pathfinding {
|
||||
[System.Serializable]
|
||||
/// <summary>
|
||||
/// Stores the navigation graphs for the A* Pathfinding System.
|
||||
/// \ingroup relevant
|
||||
///
|
||||
/// An instance of this class is assigned to AstarPath.data, from it you can access all graphs loaded through the <see cref="graphs"/> variable.\n
|
||||
/// This class also handles a lot of the high level serialization.
|
||||
/// </summary>
|
||||
public class AstarData {
|
||||
/// <summary>Shortcut to AstarPath.active</summary>
|
||||
public static AstarPath active {
|
||||
get {
|
||||
return AstarPath.active;
|
||||
}
|
||||
}
|
||||
|
||||
#region Fields
|
||||
/// <summary>
|
||||
/// Shortcut to the first NavMeshGraph.
|
||||
/// Updated at scanning time
|
||||
/// </summary>
|
||||
public NavMeshGraph navmesh { get; private set; }
|
||||
|
||||
#if !ASTAR_NO_GRID_GRAPH
|
||||
/// <summary>
|
||||
/// Shortcut to the first GridGraph.
|
||||
/// Updated at scanning time
|
||||
/// </summary>
|
||||
public GridGraph gridGraph { get; private set; }
|
||||
#endif
|
||||
|
||||
#if !ASTAR_NO_POINT_GRAPH
|
||||
/// <summary>
|
||||
/// Shortcut to the first PointGraph.
|
||||
/// Updated at scanning time
|
||||
/// </summary>
|
||||
public PointGraph pointGraph { get; private set; }
|
||||
#endif
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// All supported graph types.
|
||||
/// Populated through reflection search
|
||||
/// </summary>
|
||||
public System.Type[] graphTypes { get; private set; }
|
||||
|
||||
#if ASTAR_FAST_NO_EXCEPTIONS || UNITY_WINRT || UNITY_WEBGL
|
||||
/// <summary>
|
||||
/// Graph types to use when building with Fast But No Exceptions for iPhone.
|
||||
/// If you add any custom graph types, you need to add them to this hard-coded list.
|
||||
/// </summary>
|
||||
public static readonly System.Type[] DefaultGraphTypes = new System.Type[] {
|
||||
#if !ASTAR_NO_GRID_GRAPH
|
||||
typeof(GridGraph),
|
||||
#endif
|
||||
#if !ASTAR_NO_POINT_GRAPH
|
||||
typeof(PointGraph),
|
||||
#endif
|
||||
typeof(NavMeshGraph),
|
||||
};
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// All graphs this instance holds.
|
||||
/// This will be filled only after deserialization has completed.
|
||||
/// May contain null entries if graph have been removed.
|
||||
/// </summary>
|
||||
[System.NonSerialized]
|
||||
public NavGraph[] graphs = new NavGraph[0];
|
||||
|
||||
//Serialization Settings
|
||||
|
||||
/// <summary>
|
||||
/// Serialized data for all graphs and settings.
|
||||
/// Stored as a base64 encoded string because otherwise Unity's Undo system would sometimes corrupt the byte data (because it only stores deltas).
|
||||
///
|
||||
/// This can be accessed as a byte array from the <see cref="data"/> property.
|
||||
///
|
||||
/// \since 3.6.1
|
||||
/// </summary>
|
||||
[SerializeField]
|
||||
string dataString;
|
||||
|
||||
/// <summary>
|
||||
/// Data from versions from before 3.6.1.
|
||||
/// Used for handling upgrades
|
||||
/// \since 3.6.1
|
||||
/// </summary>
|
||||
[SerializeField]
|
||||
[UnityEngine.Serialization.FormerlySerializedAs("data")]
|
||||
private byte[] upgradeData;
|
||||
|
||||
/// <summary>Serialized data for all graphs and settings</summary>
|
||||
private byte[] data {
|
||||
get {
|
||||
// Handle upgrading from earlier versions than 3.6.1
|
||||
if (upgradeData != null && upgradeData.Length > 0) {
|
||||
data = upgradeData;
|
||||
upgradeData = null;
|
||||
}
|
||||
return dataString != null? System.Convert.FromBase64String(dataString) : null;
|
||||
}
|
||||
set {
|
||||
dataString = value != null? System.Convert.ToBase64String(value) : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serialized data for cached startup.
|
||||
/// If set, on start the graphs will be deserialized from this file.
|
||||
/// </summary>
|
||||
public TextAsset file_cachedStartup;
|
||||
|
||||
/// <summary>
|
||||
/// Serialized data for cached startup.
|
||||
///
|
||||
/// Deprecated: Deprecated since 3.6, AstarData.file_cachedStartup is now used instead
|
||||
/// </summary>
|
||||
public byte[] data_cachedStartup;
|
||||
|
||||
/// <summary>
|
||||
/// Should graph-data be cached.
|
||||
/// Caching the startup means saving the whole graphs - not only the settings - to a file (<see cref="file_cachedStartup)"/> which can
|
||||
/// be loaded when the game starts. This is usually much faster than scanning the graphs when the game starts. This is configured from the editor under the "Save & Load" tab.
|
||||
///
|
||||
/// See: save-load-graphs (view in online documentation for working links)
|
||||
/// </summary>
|
||||
[SerializeField]
|
||||
public bool cacheStartup;
|
||||
|
||||
//End Serialization Settings
|
||||
|
||||
List<bool> graphStructureLocked = new List<bool>();
|
||||
|
||||
#endregion
|
||||
|
||||
public byte[] GetData () {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void SetData (byte[] data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
/// <summary>Loads the graphs from memory, will load cached graphs if any exists</summary>
|
||||
public void Awake () {
|
||||
graphs = new NavGraph[0];
|
||||
|
||||
if (cacheStartup && file_cachedStartup != null) {
|
||||
LoadFromCache();
|
||||
} else {
|
||||
DeserializeGraphs();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prevent the graph structure from changing during the time this lock is held.
|
||||
/// This prevents graphs from being added or removed and also prevents graphs from being serialized or deserialized.
|
||||
/// This is used when e.g an async scan is happening to ensure that for example a graph that is being scanned is not destroyed.
|
||||
///
|
||||
/// Each call to this method *must* be paired with exactly one call to <see cref="UnlockGraphStructure"/>.
|
||||
/// The calls may be nested.
|
||||
/// </summary>
|
||||
internal void LockGraphStructure (bool allowAddingGraphs = false) {
|
||||
graphStructureLocked.Add(allowAddingGraphs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Allows the graph structure to change again.
|
||||
/// See: <see cref="LockGraphStructure"/>
|
||||
/// </summary>
|
||||
internal void UnlockGraphStructure () {
|
||||
if (graphStructureLocked.Count == 0) throw new System.InvalidOperationException();
|
||||
graphStructureLocked.RemoveAt(graphStructureLocked.Count - 1);
|
||||
}
|
||||
|
||||
PathProcessor.GraphUpdateLock AssertSafe (bool onlyAddingGraph = false) {
|
||||
if (graphStructureLocked.Count > 0) {
|
||||
bool allowAdding = true;
|
||||
for (int i = 0; i < graphStructureLocked.Count; i++) allowAdding &= graphStructureLocked[i];
|
||||
if (!(onlyAddingGraph && allowAdding)) throw new System.InvalidOperationException("Graphs cannot be added, removed or serialized while the graph structure is locked. This is the case when a graph is currently being scanned and when executing graph updates and work items.\nHowever as a special case, graphs can be added inside work items.");
|
||||
}
|
||||
|
||||
// Pause the pathfinding threads
|
||||
var graphLock = active.PausePathfinding();
|
||||
if (!active.IsInsideWorkItem) {
|
||||
// Make sure all graph updates and other callbacks are done
|
||||
// Only do this if this code is not being called from a work item itself as that would cause a recursive wait that could never complete.
|
||||
// There are some valid cases when this can happen. For example it may be necessary to add a new graph inside a work item.
|
||||
active.FlushWorkItems();
|
||||
|
||||
// Paths that are already calculated and waiting to be returned to the Seeker component need to be
|
||||
// processed immediately as their results usually depend on graphs that currently exist. If this was
|
||||
// not done then after destroying a graph one could get a path result with destroyed nodes in it.
|
||||
active.pathReturnQueue.ReturnPaths(false);
|
||||
}
|
||||
return graphLock;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calls the callback with every node in all graphs.
|
||||
/// This is the easiest way to iterate through every existing node.
|
||||
///
|
||||
/// <code>
|
||||
/// AstarPath.active.data.GetNodes(node => {
|
||||
/// Debug.Log("I found a node at position " + (Vector3)node.position);
|
||||
/// });
|
||||
/// </code>
|
||||
///
|
||||
/// See: <see cref="Pathfinding.NavGraph.GetNodes"/> for getting the nodes of a single graph instead of all.
|
||||
/// See: graph-updates (view in online documentation for working links)
|
||||
/// </summary>
|
||||
public void GetNodes (System.Action<GraphNode> callback) {
|
||||
for (int i = 0; i < graphs.Length; i++) {
|
||||
if (graphs[i] != null) graphs[i].GetNodes(callback);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates shortcuts to the first graph of different types.
|
||||
/// Hard coding references to some graph types is not really a good thing imo. I want to keep it dynamic and flexible.
|
||||
/// But these references ease the use of the system, so I decided to keep them.
|
||||
/// </summary>
|
||||
public void UpdateShortcuts () {
|
||||
navmesh = (NavMeshGraph)FindGraphOfType(typeof(NavMeshGraph));
|
||||
|
||||
#if !ASTAR_NO_GRID_GRAPH
|
||||
gridGraph = (GridGraph)FindGraphOfType(typeof(GridGraph));
|
||||
#endif
|
||||
|
||||
#if !ASTAR_NO_POINT_GRAPH
|
||||
pointGraph = (PointGraph)FindGraphOfType(typeof(PointGraph));
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>Load from data from <see cref="file_cachedStartup"/></summary>
|
||||
public void LoadFromCache () {
|
||||
var graphLock = AssertSafe();
|
||||
|
||||
if (file_cachedStartup != null) {
|
||||
var bytes = file_cachedStartup.bytes;
|
||||
DeserializeGraphs(bytes);
|
||||
|
||||
GraphModifier.TriggerEvent(GraphModifier.EventType.PostCacheLoad);
|
||||
} else {
|
||||
Debug.LogError("Can't load from cache since the cache is empty");
|
||||
}
|
||||
graphLock.Release();
|
||||
}
|
||||
|
||||
#region Serialization
|
||||
|
||||
/// <summary>
|
||||
/// Serializes all graphs settings to a byte array.
|
||||
/// See: DeserializeGraphs(byte[])
|
||||
/// </summary>
|
||||
public byte[] SerializeGraphs () {
|
||||
return SerializeGraphs(SerializeSettings.Settings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serializes all graphs settings and optionally node data to a byte array.
|
||||
/// See: DeserializeGraphs(byte[])
|
||||
/// See: Pathfinding.Serialization.SerializeSettings
|
||||
/// </summary>
|
||||
public byte[] SerializeGraphs (SerializeSettings settings) {
|
||||
uint checksum;
|
||||
|
||||
return SerializeGraphs(settings, out checksum);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Main serializer function.
|
||||
/// Serializes all graphs to a byte array
|
||||
/// A similar function exists in the AstarPathEditor.cs script to save additional info
|
||||
/// </summary>
|
||||
public byte[] SerializeGraphs (SerializeSettings settings, out uint checksum) {
|
||||
var graphLock = AssertSafe();
|
||||
var sr = new AstarSerializer(this, settings, active.gameObject);
|
||||
|
||||
sr.OpenSerialize();
|
||||
sr.SerializeGraphs(graphs);
|
||||
sr.SerializeExtraInfo();
|
||||
byte[] bytes = sr.CloseSerialize();
|
||||
checksum = sr.GetChecksum();
|
||||
#if ASTARDEBUG
|
||||
Debug.Log("Got a whole bunch of data, "+bytes.Length+" bytes");
|
||||
#endif
|
||||
graphLock.Release();
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <summary>Deserializes graphs from <see cref="data"/></summary>
|
||||
public void DeserializeGraphs () {
|
||||
if (data != null) {
|
||||
DeserializeGraphs(data);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Destroys all graphs and sets graphs to null</summary>
|
||||
void ClearGraphs () {
|
||||
if (graphs == null) return;
|
||||
for (int i = 0; i < graphs.Length; i++) {
|
||||
if (graphs[i] != null) {
|
||||
((IGraphInternals)graphs[i]).OnDestroy();
|
||||
graphs[i].active = null;
|
||||
}
|
||||
}
|
||||
graphs = new NavGraph[0];
|
||||
UpdateShortcuts();
|
||||
}
|
||||
|
||||
public void OnDestroy () {
|
||||
ClearGraphs();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes graphs from the specified byte array.
|
||||
/// An error will be logged if deserialization fails.
|
||||
/// </summary>
|
||||
public void DeserializeGraphs (byte[] bytes) {
|
||||
var graphLock = AssertSafe();
|
||||
|
||||
ClearGraphs();
|
||||
DeserializeGraphsAdditive(bytes);
|
||||
graphLock.Release();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes graphs from the specified byte array additively.
|
||||
/// An error will be logged if deserialization fails.
|
||||
/// This function will add loaded graphs to the current ones.
|
||||
/// </summary>
|
||||
public void DeserializeGraphsAdditive (byte[] bytes) {
|
||||
var graphLock = AssertSafe();
|
||||
|
||||
try {
|
||||
if (bytes != null) {
|
||||
var sr = new AstarSerializer(this, active.gameObject);
|
||||
|
||||
if (sr.OpenDeserialize(bytes)) {
|
||||
DeserializeGraphsPartAdditive(sr);
|
||||
sr.CloseDeserialize();
|
||||
} else {
|
||||
Debug.Log("Invalid data file (cannot read zip).\nThe data is either corrupt or it was saved using a 3.0.x or earlier version of the system");
|
||||
}
|
||||
} else {
|
||||
throw new System.ArgumentNullException("bytes");
|
||||
}
|
||||
active.VerifyIntegrity();
|
||||
} catch (System.Exception e) {
|
||||
Debug.LogError("Caught exception while deserializing data.\n"+e);
|
||||
graphs = new NavGraph[0];
|
||||
}
|
||||
|
||||
UpdateShortcuts();
|
||||
graphLock.Release();
|
||||
}
|
||||
|
||||
/// <summary>Helper function for deserializing graphs</summary>
|
||||
void DeserializeGraphsPartAdditive (AstarSerializer sr) {
|
||||
if (graphs == null) graphs = new NavGraph[0];
|
||||
|
||||
var gr = new List<NavGraph>(graphs);
|
||||
|
||||
// Set an offset so that the deserializer will load
|
||||
// the graphs with the correct graph indexes
|
||||
sr.SetGraphIndexOffset(gr.Count);
|
||||
|
||||
if (graphTypes == null) FindGraphTypes();
|
||||
gr.AddRange(sr.DeserializeGraphs(graphTypes));
|
||||
graphs = gr.ToArray();
|
||||
|
||||
sr.DeserializeEditorSettingsCompatibility();
|
||||
sr.DeserializeExtraInfo();
|
||||
|
||||
//Assign correct graph indices.
|
||||
for (int i = 0; i < graphs.Length; i++) {
|
||||
if (graphs[i] == null) continue;
|
||||
graphs[i].GetNodes(node => node.GraphIndex = (uint)i);
|
||||
}
|
||||
|
||||
for (int i = 0; i < graphs.Length; i++) {
|
||||
for (int j = i+1; j < graphs.Length; j++) {
|
||||
if (graphs[i] != null && graphs[j] != null && graphs[i].guid == graphs[j].guid) {
|
||||
Debug.LogWarning("Guid Conflict when importing graphs additively. Imported graph will get a new Guid.\nThis message is (relatively) harmless.");
|
||||
graphs[i].guid = Pathfinding.Util.Guid.NewGuid();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sr.PostDeserialization();
|
||||
active.hierarchicalGraph.RecalculateIfNecessary();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Find all graph types supported in this build.
|
||||
/// Using reflection, the assembly is searched for types which inherit from NavGraph.
|
||||
/// </summary>
|
||||
public void FindGraphTypes () {
|
||||
#if !ASTAR_FAST_NO_EXCEPTIONS && !UNITY_WINRT && !UNITY_WEBGL
|
||||
var graphList = new List<System.Type>();
|
||||
foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) {
|
||||
System.Type[] types = null;
|
||||
try {
|
||||
types = assembly.GetTypes();
|
||||
} catch {
|
||||
// Ignore type load exceptions and things like that.
|
||||
// We might not be able to read all assemblies for some reason, but hopefully the relevant types exist in the assemblies that we can read
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var type in types) {
|
||||
#if NETFX_CORE && !UNITY_EDITOR
|
||||
System.Type baseType = type.GetTypeInfo().BaseType;
|
||||
#else
|
||||
var baseType = type.BaseType;
|
||||
#endif
|
||||
while (baseType != null) {
|
||||
if (System.Type.Equals(baseType, typeof(NavGraph))) {
|
||||
graphList.Add(type);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
#if NETFX_CORE && !UNITY_EDITOR
|
||||
baseType = baseType.GetTypeInfo().BaseType;
|
||||
#else
|
||||
baseType = baseType.BaseType;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
graphTypes = graphList.ToArray();
|
||||
|
||||
#if ASTARDEBUG
|
||||
Debug.Log("Found "+graphTypes.Length+" graph types");
|
||||
#endif
|
||||
#else
|
||||
graphTypes = DefaultGraphTypes;
|
||||
#endif
|
||||
}
|
||||
|
||||
#region GraphCreation
|
||||
/// <summary>
|
||||
/// Returns: A System.Type which matches the specified type string. If no mathing graph type was found, null is returned
|
||||
///
|
||||
/// Deprecated:
|
||||
/// </summary>
|
||||
[System.Obsolete("If really necessary. Use System.Type.GetType instead.")]
|
||||
public System.Type GetGraphType (string type) {
|
||||
for (int i = 0; i < graphTypes.Length; i++) {
|
||||
if (graphTypes[i].Name == type) {
|
||||
return graphTypes[i];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of a graph of type type. If no matching graph type was found, an error is logged and null is returned
|
||||
/// Returns: The created graph
|
||||
/// See: <see cref="CreateGraph(System.Type)"/>
|
||||
///
|
||||
/// Deprecated:
|
||||
/// </summary>
|
||||
[System.Obsolete("Use CreateGraph(System.Type) instead")]
|
||||
public NavGraph CreateGraph (string type) {
|
||||
Debug.Log("Creating Graph of type '"+type+"'");
|
||||
|
||||
for (int i = 0; i < graphTypes.Length; i++) {
|
||||
if (graphTypes[i].Name == type) {
|
||||
return CreateGraph(graphTypes[i]);
|
||||
}
|
||||
}
|
||||
Debug.LogError("Graph type ("+type+") wasn't found");
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new graph instance of type type
|
||||
/// See: <see cref="CreateGraph(string)"/>
|
||||
/// </summary>
|
||||
internal NavGraph CreateGraph (System.Type type) {
|
||||
var graph = System.Activator.CreateInstance(type) as NavGraph;
|
||||
|
||||
graph.active = active;
|
||||
return graph;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a graph of type type to the <see cref="graphs"/> array
|
||||
///
|
||||
/// Deprecated:
|
||||
/// </summary>
|
||||
[System.Obsolete("Use AddGraph(System.Type) instead")]
|
||||
public NavGraph AddGraph (string type) {
|
||||
NavGraph graph = null;
|
||||
|
||||
for (int i = 0; i < graphTypes.Length; i++) {
|
||||
if (graphTypes[i].Name == type) {
|
||||
graph = CreateGraph(graphTypes[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (graph == null) {
|
||||
Debug.LogError("No NavGraph of type '"+type+"' could be found");
|
||||
return null;
|
||||
}
|
||||
|
||||
AddGraph(graph);
|
||||
|
||||
return graph;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a graph of type type to the <see cref="graphs"/> array.
|
||||
/// See: runtime-graphs (view in online documentation for working links)
|
||||
/// </summary>
|
||||
public NavGraph AddGraph (System.Type type) {
|
||||
NavGraph graph = null;
|
||||
|
||||
for (int i = 0; i < graphTypes.Length; i++) {
|
||||
if (System.Type.Equals(graphTypes[i], type)) {
|
||||
graph = CreateGraph(graphTypes[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (graph == null) {
|
||||
Debug.LogError("No NavGraph of type '"+type+"' could be found, "+graphTypes.Length+" graph types are avaliable");
|
||||
return null;
|
||||
}
|
||||
|
||||
AddGraph(graph);
|
||||
|
||||
return graph;
|
||||
}
|
||||
|
||||
/// <summary>Adds the specified graph to the <see cref="graphs"/> array</summary>
|
||||
void AddGraph (NavGraph graph) {
|
||||
// Make sure to not interfere with pathfinding
|
||||
var graphLock = AssertSafe(true);
|
||||
|
||||
// Try to fill in an empty position
|
||||
bool foundEmpty = false;
|
||||
|
||||
for (int i = 0; i < graphs.Length; i++) {
|
||||
if (graphs[i] == null) {
|
||||
graphs[i] = graph;
|
||||
graph.graphIndex = (uint)i;
|
||||
foundEmpty = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundEmpty) {
|
||||
if (graphs != null && graphs.Length >= GraphNode.MaxGraphIndex) {
|
||||
throw new System.Exception("Graph Count Limit Reached. You cannot have more than " + GraphNode.MaxGraphIndex + " graphs.");
|
||||
}
|
||||
|
||||
// Add a new entry to the list
|
||||
var graphList = new List<NavGraph>(graphs ?? new NavGraph[0]);
|
||||
graphList.Add(graph);
|
||||
graphs = graphList.ToArray();
|
||||
graph.graphIndex = (uint)(graphs.Length-1);
|
||||
}
|
||||
|
||||
UpdateShortcuts();
|
||||
graph.active = active;
|
||||
graphLock.Release();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the specified graph from the <see cref="graphs"/> array and Destroys it in a safe manner.
|
||||
/// To avoid changing graph indices for the other graphs, the graph is simply nulled in the array instead
|
||||
/// of actually removing it from the array.
|
||||
/// The empty position will be reused if a new graph is added.
|
||||
///
|
||||
/// Returns: True if the graph was sucessfully removed (i.e it did exist in the <see cref="graphs"/> array). False otherwise.
|
||||
///
|
||||
/// Version: Changed in 3.2.5 to call SafeOnDestroy before removing
|
||||
/// and nulling it in the array instead of removing the element completely in the <see cref="graphs"/> array.
|
||||
/// </summary>
|
||||
public bool RemoveGraph (NavGraph graph) {
|
||||
// Make sure the pathfinding threads are stopped
|
||||
// If we don't wait until pathfinding that is potentially running on
|
||||
// this graph right now we could end up with NullReferenceExceptions
|
||||
var graphLock = AssertSafe();
|
||||
|
||||
((IGraphInternals)graph).OnDestroy();
|
||||
graph.active = null;
|
||||
|
||||
int i = System.Array.IndexOf(graphs, graph);
|
||||
if (i != -1) graphs[i] = null;
|
||||
|
||||
UpdateShortcuts();
|
||||
graphLock.Release();
|
||||
return i != -1;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region GraphUtility
|
||||
|
||||
/// <summary>
|
||||
/// Returns the graph which contains the specified node.
|
||||
/// The graph must be in the <see cref="graphs"/> array.
|
||||
///
|
||||
/// Returns: Returns the graph which contains the node. Null if the graph wasn't found
|
||||
/// </summary>
|
||||
public static NavGraph GetGraph (GraphNode node) {
|
||||
if (node == null) return null;
|
||||
|
||||
AstarPath script = AstarPath.active;
|
||||
if (script == null) return null;
|
||||
|
||||
AstarData data = script.data;
|
||||
if (data == null || data.graphs == null) return null;
|
||||
|
||||
uint graphIndex = node.GraphIndex;
|
||||
|
||||
if (graphIndex >= data.graphs.Length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return data.graphs[(int)graphIndex];
|
||||
}
|
||||
|
||||
/// <summary>Returns the first graph which satisfies the predicate. Returns null if no graph was found.</summary>
|
||||
public NavGraph FindGraph (System.Func<NavGraph, bool> predicate) {
|
||||
if (graphs != null) {
|
||||
for (int i = 0; i < graphs.Length; i++) {
|
||||
if (graphs[i] != null && predicate(graphs[i])) {
|
||||
return graphs[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Returns the first graph of type type found in the <see cref="graphs"/> array. Returns null if no graph was found.</summary>
|
||||
public NavGraph FindGraphOfType (System.Type type) {
|
||||
return FindGraph(graph => System.Type.Equals(graph.GetType(), type));
|
||||
}
|
||||
|
||||
/// <summary>Returns the first graph which inherits from the type type. Returns null if no graph was found.</summary>
|
||||
public NavGraph FindGraphWhichInheritsFrom (System.Type type) {
|
||||
return FindGraph(graph => WindowsStoreCompatibility.GetTypeInfo(type).IsAssignableFrom(WindowsStoreCompatibility.GetTypeInfo(graph.GetType())));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loop through this function to get all graphs of type 'type'
|
||||
/// <code>
|
||||
/// foreach (GridGraph graph in AstarPath.data.FindGraphsOfType (typeof(GridGraph))) {
|
||||
/// //Do something with the graph
|
||||
/// }
|
||||
/// </code>
|
||||
/// See: AstarPath.RegisterSafeNodeUpdate
|
||||
/// </summary>
|
||||
public IEnumerable FindGraphsOfType (System.Type type) {
|
||||
if (graphs == null) yield break;
|
||||
for (int i = 0; i < graphs.Length; i++) {
|
||||
if (graphs[i] != null && System.Type.Equals(graphs[i].GetType(), type)) {
|
||||
yield return graphs[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// All graphs which implements the UpdateableGraph interface
|
||||
/// <code> foreach (IUpdatableGraph graph in AstarPath.data.GetUpdateableGraphs ()) {
|
||||
/// //Do something with the graph
|
||||
/// } </code>
|
||||
/// See: AstarPath.AddWorkItem
|
||||
/// See: Pathfinding.IUpdatableGraph
|
||||
/// </summary>
|
||||
public IEnumerable GetUpdateableGraphs () {
|
||||
if (graphs == null) yield break;
|
||||
for (int i = 0; i < graphs.Length; i++) {
|
||||
if (graphs[i] is IUpdatableGraph) {
|
||||
yield return graphs[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// All graphs which implements the UpdateableGraph interface
|
||||
/// <code> foreach (IRaycastableGraph graph in AstarPath.data.GetRaycastableGraphs ()) {
|
||||
/// //Do something with the graph
|
||||
/// } </code>
|
||||
/// See: Pathfinding.IRaycastableGraph
|
||||
/// Deprecated: Deprecated because it is not used by the package internally and the use cases are few. Iterate through the <see cref="graphs"/> array instead.
|
||||
/// </summary>
|
||||
[System.Obsolete("Obsolete because it is not used by the package internally and the use cases are few. Iterate through the graphs array instead.")]
|
||||
public IEnumerable GetRaycastableGraphs () {
|
||||
if (graphs == null) yield break;
|
||||
for (int i = 0; i < graphs.Length; i++) {
|
||||
if (graphs[i] is IRaycastableGraph) {
|
||||
yield return graphs[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Gets the index of the NavGraph in the <see cref="graphs"/> array</summary>
|
||||
public int GetGraphIndex (NavGraph graph) {
|
||||
if (graph == null) throw new System.ArgumentNullException("graph");
|
||||
|
||||
var index = -1;
|
||||
if (graphs != null) {
|
||||
index = System.Array.IndexOf(graphs, graph);
|
||||
if (index == -1) Debug.LogError("Graph doesn't exist");
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
7
AR/Assets/AstarPathfindingProject/Core/AstarData.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/AstarData.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 38d211caa07cb44ef886481aa1cf755c
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
1530
AR/Assets/AstarPathfindingProject/Core/AstarMath.cs
Normal file
1530
AR/Assets/AstarPathfindingProject/Core/AstarMath.cs
Normal file
File diff suppressed because it is too large
Load Diff
7
AR/Assets/AstarPathfindingProject/Core/AstarMath.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/AstarMath.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 960fd9020b1f74f939fee737c3c0f491
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
2163
AR/Assets/AstarPathfindingProject/Core/AstarPath.cs
Normal file
2163
AR/Assets/AstarPathfindingProject/Core/AstarPath.cs
Normal file
File diff suppressed because it is too large
Load Diff
16
AR/Assets/AstarPathfindingProject/Core/AstarPath.cs.meta
generated
Normal file
16
AR/Assets/AstarPathfindingProject/Core/AstarPath.cs.meta
generated
Normal file
@ -0,0 +1,16 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 78396926cbbfc4ac3b48fc5fc34a87d1
|
||||
labels:
|
||||
- Pathfinder
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences:
|
||||
- gizmoSurfaceMaterial: {fileID: 2100000, guid: 5ce51318bbfb1466188b929a68a6bd3a,
|
||||
type: 2}
|
||||
- gizmoLineMaterial: {fileID: 2100000, guid: 91035448860ba4e708919485c73f7edc, type: 2}
|
||||
executionOrder: -10000
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
398
AR/Assets/AstarPathfindingProject/Core/GraphUpdateScene.cs
Normal file
398
AR/Assets/AstarPathfindingProject/Core/GraphUpdateScene.cs
Normal file
@ -0,0 +1,398 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace Pathfinding {
|
||||
[AddComponentMenu("Pathfinding/GraphUpdateScene")]
|
||||
/// <summary>
|
||||
/// Helper class for easily updating graphs.
|
||||
///
|
||||
/// The GraphUpdateScene component is really easy to use. Create a new empty GameObject and add the component to it, it can be found in Components-->Pathfinding-->GraphUpdateScene.\n
|
||||
/// When you have added the component, you should see something like the image below.
|
||||
/// [Open online documentation to see images]
|
||||
/// The region which the component will affect is defined by creating a polygon in the scene.
|
||||
/// If you make sure you have the Position tool enabled (top-left corner of the Unity window) you can shift+click in the scene view to add more points to the polygon.
|
||||
/// You can remove points using shift+alt+click.
|
||||
/// By clicking on the points you can bring up a positioning tool. You can also open the "points" array in the inspector to set each point's coordinates manually.
|
||||
/// [Open online documentation to see images]
|
||||
/// In the inspector there are a number of variables. The first one is named "Convex", it sets if the convex hull of the points should be calculated or if the polygon should be used as-is.
|
||||
/// Using the convex hull is faster when applying the changes to the graph, but with a non-convex polygon you can specify more complicated areas.\n
|
||||
/// The next two variables, called "Apply On Start" and "Apply On Scan" determine when to apply the changes. If the object is in the scene from the beginning, both can be left on, it doesn't
|
||||
/// matter since the graph is also scanned at start. However if you instantiate it later in the game, you can make it apply it's setting directly, or wait until the next scan (if any).
|
||||
/// If the graph is rescanned, all GraphUpdateScene components which have the Apply On Scan variable toggled will apply their settings again to the graph since rescanning clears all previous changes.\n
|
||||
/// You can also make it apply it's changes using scripting.
|
||||
/// <code> GetComponent<GraphUpdateScene>().Apply (); </code>
|
||||
/// The above code will make it apply its changes to the graph (assuming a GraphUpdateScene component is attached to the same GameObject).
|
||||
///
|
||||
/// Next there is "Modify Walkability" and "Set Walkability" (which appears when "Modify Walkability" is toggled).
|
||||
/// If Modify Walkability is set, then all nodes inside the area will either be set to walkable or unwalkable depending on the value of the "Set Walkability" variable.
|
||||
///
|
||||
/// Penalty can also be applied to the nodes. A higher penalty (aka weight) makes the nodes harder to traverse so it will try to avoid those areas.
|
||||
///
|
||||
/// The tagging variables can be read more about on this page: tags (view in online documentation for working links) "Working with tags".
|
||||
///
|
||||
/// Note: The Y (up) axis of the transform that this component is attached to should be in the same direction as the up direction of the graph.
|
||||
/// So if you for example have a grid in the XY plane then the transform should have the rotation (-90,0,0).
|
||||
/// </summary>
|
||||
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_graph_update_scene.php")]
|
||||
public class GraphUpdateScene : GraphModifier {
|
||||
/// <summary>Points which define the region to update</summary>
|
||||
public Vector3[] points;
|
||||
|
||||
/// <summary>Private cached convex hull of the <see cref="points"/></summary>
|
||||
private Vector3[] convexPoints;
|
||||
|
||||
/// <summary>
|
||||
/// Use the convex hull of the points instead of the original polygon.
|
||||
///
|
||||
/// See: https://en.wikipedia.org/wiki/Convex_hull
|
||||
/// </summary>
|
||||
public bool convex = true;
|
||||
|
||||
/// <summary>
|
||||
/// Minumum height of the bounds of the resulting Graph Update Object.
|
||||
/// Useful when all points are laid out on a plane but you still need a bounds with a height greater than zero since a
|
||||
/// zero height graph update object would usually result in no nodes being updated.
|
||||
/// </summary>
|
||||
public float minBoundsHeight = 1;
|
||||
|
||||
/// <summary>
|
||||
/// Penalty to add to nodes.
|
||||
/// Usually you need quite large values, at least 1000-10000. A higher penalty means that agents will try to avoid those nodes more.
|
||||
///
|
||||
/// Be careful when setting negative values since if a node gets a negative penalty it will underflow and instead get
|
||||
/// really large. In most cases a warning will be logged if that happens.
|
||||
///
|
||||
/// See: tags (view in online documentation for working links) for another way of applying penalties.
|
||||
/// </summary>
|
||||
public int penaltyDelta;
|
||||
|
||||
/// <summary>If true, then all affected nodes will be made walkable or unwalkable according to <see cref="setWalkability"/></summary>
|
||||
public bool modifyWalkability;
|
||||
|
||||
/// <summary>Nodes will be made walkable or unwalkable according to this value if <see cref="modifyWalkability"/> is true</summary>
|
||||
public bool setWalkability;
|
||||
|
||||
/// <summary>Apply this graph update object on start</summary>
|
||||
public bool applyOnStart = true;
|
||||
|
||||
/// <summary>Apply this graph update object whenever a graph is rescanned</summary>
|
||||
public bool applyOnScan = true;
|
||||
|
||||
/// <summary>
|
||||
/// Update node's walkability and connectivity using physics functions.
|
||||
/// For grid graphs, this will update the node's position and walkability exactly like when doing a scan of the graph.
|
||||
/// If enabled for grid graphs, <see cref="modifyWalkability"/> will be ignored.
|
||||
///
|
||||
/// For Point Graphs, this will recalculate all connections which passes through the bounds of the resulting Graph Update Object
|
||||
/// using raycasts (if enabled).
|
||||
/// </summary>
|
||||
public bool updatePhysics;
|
||||
|
||||
/// <summary>\copydoc Pathfinding::GraphUpdateObject::resetPenaltyOnPhysics</summary>
|
||||
public bool resetPenaltyOnPhysics = true;
|
||||
|
||||
/// <summary>\copydoc Pathfinding::GraphUpdateObject::updateErosion</summary>
|
||||
public bool updateErosion = true;
|
||||
|
||||
/// <summary>
|
||||
/// Should the tags of the nodes be modified.
|
||||
/// If enabled, set all nodes' tags to <see cref="setTag"/>
|
||||
/// </summary>
|
||||
public bool modifyTag;
|
||||
|
||||
/// <summary>If <see cref="modifyTag"/> is enabled, set all nodes' tags to this value</summary>
|
||||
public int setTag;
|
||||
|
||||
/// <summary>Emulates behavior from before version 4.0</summary>
|
||||
[HideInInspector]
|
||||
public bool legacyMode = false;
|
||||
|
||||
/// <summary>
|
||||
/// Private cached inversion of <see cref="setTag"/>.
|
||||
/// Used for InvertSettings()
|
||||
/// </summary>
|
||||
private int setTagInvert;
|
||||
|
||||
/// <summary>
|
||||
/// Has apply been called yet.
|
||||
/// Used to prevent applying twice when both applyOnScan and applyOnStart are enabled
|
||||
/// </summary>
|
||||
private bool firstApplied;
|
||||
|
||||
[SerializeField]
|
||||
private int serializedVersion = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Use world space for coordinates.
|
||||
/// If true, the shape will not follow when moving around the transform.
|
||||
///
|
||||
/// See: <see cref="ToggleUseWorldSpace"/>
|
||||
/// </summary>
|
||||
[SerializeField]
|
||||
[UnityEngine.Serialization.FormerlySerializedAs("useWorldSpace")]
|
||||
private bool legacyUseWorldSpace;
|
||||
|
||||
/// <summary>Do some stuff at start</summary>
|
||||
public void Start () {
|
||||
if (!Application.isPlaying) return;
|
||||
|
||||
// If firstApplied is true, that means the graph was scanned during Awake.
|
||||
// So we shouldn't apply it again because then we would end up applying it two times
|
||||
if (!firstApplied && applyOnStart) {
|
||||
Apply();
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnPostScan () {
|
||||
if (applyOnScan) Apply();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inverts all invertable settings for this GUS.
|
||||
/// Namely: penalty delta, walkability, tags.
|
||||
///
|
||||
/// Penalty delta will be changed to negative penalty delta.\n
|
||||
/// <see cref="setWalkability"/> will be inverted.\n
|
||||
/// <see cref="setTag"/> will be stored in a private variable, and the new value will be 0. When calling this function again, the saved
|
||||
/// value will be the new value.
|
||||
///
|
||||
/// Calling this function an even number of times without changing any settings in between will be identical to no change in settings.
|
||||
/// </summary>
|
||||
public virtual void InvertSettings () {
|
||||
setWalkability = !setWalkability;
|
||||
penaltyDelta = -penaltyDelta;
|
||||
if (setTagInvert == 0) {
|
||||
setTagInvert = setTag;
|
||||
setTag = 0;
|
||||
} else {
|
||||
setTag = setTagInvert;
|
||||
setTagInvert = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recalculate convex hull.
|
||||
/// Will not do anything if <see cref="convex"/> is disabled.
|
||||
/// </summary>
|
||||
public void RecalcConvex () {
|
||||
convexPoints = convex ? Polygon.ConvexHullXZ(points) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Switches between using world space and using local space.
|
||||
/// Deprecated: World space can no longer be used as it does not work well with rotated graphs. Use transform.InverseTransformPoint to transform points to local space.
|
||||
/// </summary>
|
||||
[System.ObsoleteAttribute("World space can no longer be used as it does not work well with rotated graphs. Use transform.InverseTransformPoint to transform points to local space.", true)]
|
||||
void ToggleUseWorldSpace () {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lock all points to a specific Y value.
|
||||
/// Deprecated: The Y coordinate is no longer important. Use the position of the object instead.
|
||||
/// </summary>
|
||||
[System.ObsoleteAttribute("The Y coordinate is no longer important. Use the position of the object instead", true)]
|
||||
public void LockToY () {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates the bounds for this component.
|
||||
/// This is a relatively expensive operation, it needs to go through all points and
|
||||
/// run matrix multiplications.
|
||||
/// </summary>
|
||||
public Bounds GetBounds () {
|
||||
if (points == null || points.Length == 0) {
|
||||
Bounds bounds;
|
||||
var coll = GetComponent<Collider>();
|
||||
var coll2D = GetComponent<Collider2D>();
|
||||
var rend = GetComponent<Renderer>();
|
||||
|
||||
if (coll != null) bounds = coll.bounds;
|
||||
else if (coll2D != null) {
|
||||
bounds = coll2D.bounds;
|
||||
bounds.size = new Vector3(bounds.size.x, bounds.size.y, Mathf.Max(bounds.size.z, 1f));
|
||||
} else if (rend != null) {
|
||||
bounds = rend.bounds;
|
||||
} else {
|
||||
return new Bounds(Vector3.zero, Vector3.zero);
|
||||
}
|
||||
|
||||
if (legacyMode && bounds.size.y < minBoundsHeight) bounds.size = new Vector3(bounds.size.x, minBoundsHeight, bounds.size.z);
|
||||
return bounds;
|
||||
} else {
|
||||
return GraphUpdateShape.GetBounds(convex ? convexPoints : points, legacyMode && legacyUseWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix, minBoundsHeight);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates graphs with a created GUO.
|
||||
/// Creates a Pathfinding.GraphUpdateObject with a Pathfinding.GraphUpdateShape
|
||||
/// representing the polygon of this object and update all graphs using AstarPath.UpdateGraphs.
|
||||
/// This will not update graphs immediately. See AstarPath.UpdateGraph for more info.
|
||||
/// </summary>
|
||||
public void Apply () {
|
||||
if (AstarPath.active == null) {
|
||||
Debug.LogError("There is no AstarPath object in the scene", this);
|
||||
return;
|
||||
}
|
||||
|
||||
GraphUpdateObject guo;
|
||||
|
||||
if (points == null || points.Length == 0) {
|
||||
var polygonCollider = GetComponent<PolygonCollider2D>();
|
||||
if (polygonCollider != null) {
|
||||
var points2D = polygonCollider.points;
|
||||
Vector3[] pts = new Vector3[points2D.Length];
|
||||
for (int i = 0; i < pts.Length; i++) {
|
||||
var p = points2D[i] + polygonCollider.offset;
|
||||
pts[i] = new Vector3(p.x, 0, p.y);
|
||||
}
|
||||
|
||||
var mat = transform.localToWorldMatrix * Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(-90, 0, 0), Vector3.one);
|
||||
var shape = new GraphUpdateShape(pts, convex, mat, minBoundsHeight);
|
||||
guo = new GraphUpdateObject(GetBounds());
|
||||
guo.shape = shape;
|
||||
} else {
|
||||
var bounds = GetBounds();
|
||||
if (bounds.center == Vector3.zero && bounds.size == Vector3.zero) {
|
||||
Debug.LogError("Cannot apply GraphUpdateScene, no points defined and no renderer or collider attached", this);
|
||||
return;
|
||||
}
|
||||
|
||||
guo = new GraphUpdateObject(bounds);
|
||||
}
|
||||
} else {
|
||||
GraphUpdateShape shape;
|
||||
if (legacyMode && !legacyUseWorldSpace) {
|
||||
// Used for compatibility with older versions
|
||||
var worldPoints = new Vector3[points.Length];
|
||||
for (int i = 0; i < points.Length; i++) worldPoints[i] = transform.TransformPoint(points[i]);
|
||||
shape = new GraphUpdateShape(worldPoints, convex, Matrix4x4.identity, minBoundsHeight);
|
||||
} else {
|
||||
shape = new GraphUpdateShape(points, convex, legacyMode && legacyUseWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix, minBoundsHeight);
|
||||
}
|
||||
var bounds = shape.GetBounds();
|
||||
guo = new GraphUpdateObject(bounds);
|
||||
guo.shape = shape;
|
||||
}
|
||||
|
||||
firstApplied = true;
|
||||
|
||||
guo.modifyWalkability = modifyWalkability;
|
||||
guo.setWalkability = setWalkability;
|
||||
guo.addPenalty = penaltyDelta;
|
||||
guo.updatePhysics = updatePhysics;
|
||||
guo.updateErosion = updateErosion;
|
||||
guo.resetPenaltyOnPhysics = resetPenaltyOnPhysics;
|
||||
|
||||
guo.modifyTag = modifyTag;
|
||||
guo.setTag = setTag;
|
||||
|
||||
AstarPath.active.UpdateGraphs(guo);
|
||||
}
|
||||
|
||||
/// <summary>Draws some gizmos</summary>
|
||||
void OnDrawGizmos () {
|
||||
OnDrawGizmos(false);
|
||||
}
|
||||
|
||||
/// <summary>Draws some gizmos</summary>
|
||||
void OnDrawGizmosSelected () {
|
||||
OnDrawGizmos(true);
|
||||
}
|
||||
|
||||
/// <summary>Draws some gizmos</summary>
|
||||
void OnDrawGizmos (bool selected) {
|
||||
Color c = selected ? new Color(227/255f, 61/255f, 22/255f, 1.0f) : new Color(227/255f, 61/255f, 22/255f, 0.9f);
|
||||
|
||||
if (selected) {
|
||||
Gizmos.color = Color.Lerp(c, new Color(1, 1, 1, 0.2f), 0.9f);
|
||||
|
||||
Bounds b = GetBounds();
|
||||
Gizmos.DrawCube(b.center, b.size);
|
||||
Gizmos.DrawWireCube(b.center, b.size);
|
||||
}
|
||||
|
||||
if (points == null) return;
|
||||
|
||||
if (convex) c.a *= 0.5f;
|
||||
|
||||
Gizmos.color = c;
|
||||
|
||||
Matrix4x4 matrix = legacyMode && legacyUseWorldSpace ? Matrix4x4.identity : transform.localToWorldMatrix;
|
||||
|
||||
if (convex) {
|
||||
c.r -= 0.1f;
|
||||
c.g -= 0.2f;
|
||||
c.b -= 0.1f;
|
||||
|
||||
Gizmos.color = c;
|
||||
}
|
||||
|
||||
if (selected || !convex) {
|
||||
for (int i = 0; i < points.Length; i++) {
|
||||
Gizmos.DrawLine(matrix.MultiplyPoint3x4(points[i]), matrix.MultiplyPoint3x4(points[(i+1)%points.Length]));
|
||||
}
|
||||
}
|
||||
|
||||
if (convex) {
|
||||
if (convexPoints == null) RecalcConvex();
|
||||
|
||||
Gizmos.color = selected ? new Color(227/255f, 61/255f, 22/255f, 1.0f) : new Color(227/255f, 61/255f, 22/255f, 0.9f);
|
||||
|
||||
for (int i = 0; i < convexPoints.Length; i++) {
|
||||
Gizmos.DrawLine(matrix.MultiplyPoint3x4(convexPoints[i]), matrix.MultiplyPoint3x4(convexPoints[(i+1)%convexPoints.Length]));
|
||||
}
|
||||
}
|
||||
|
||||
// Draw the full 3D shape
|
||||
var pts = convex ? convexPoints : points;
|
||||
if (selected && pts != null && pts.Length > 0) {
|
||||
Gizmos.color = new Color(1, 1, 1, 0.2f);
|
||||
float miny = pts[0].y, maxy = pts[0].y;
|
||||
for (int i = 0; i < pts.Length; i++) {
|
||||
miny = Mathf.Min(miny, pts[i].y);
|
||||
maxy = Mathf.Max(maxy, pts[i].y);
|
||||
}
|
||||
var extraHeight = Mathf.Max(minBoundsHeight - (maxy - miny), 0) * 0.5f;
|
||||
miny -= extraHeight;
|
||||
maxy += extraHeight;
|
||||
|
||||
for (int i = 0; i < pts.Length; i++) {
|
||||
var next = (i+1) % pts.Length;
|
||||
var p1 = matrix.MultiplyPoint3x4(pts[i] + Vector3.up*(miny - pts[i].y));
|
||||
var p2 = matrix.MultiplyPoint3x4(pts[i] + Vector3.up*(maxy - pts[i].y));
|
||||
var p1n = matrix.MultiplyPoint3x4(pts[next] + Vector3.up*(miny - pts[next].y));
|
||||
var p2n = matrix.MultiplyPoint3x4(pts[next] + Vector3.up*(maxy - pts[next].y));
|
||||
Gizmos.DrawLine(p1, p2);
|
||||
Gizmos.DrawLine(p1, p1n);
|
||||
Gizmos.DrawLine(p2, p2n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disables legacy mode if it is enabled.
|
||||
/// Legacy mode is automatically enabled for components when upgrading from an earlier version than 3.8.6.
|
||||
/// </summary>
|
||||
public void DisableLegacyMode () {
|
||||
if (legacyMode) {
|
||||
legacyMode = false;
|
||||
if (legacyUseWorldSpace) {
|
||||
legacyUseWorldSpace = false;
|
||||
for (int i = 0; i < points.Length; i++) {
|
||||
points[i] = transform.InverseTransformPoint(points[i]);
|
||||
}
|
||||
RecalcConvex();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Awake () {
|
||||
if (serializedVersion == 0) {
|
||||
// Use the old behavior if some points are already set
|
||||
if (points != null && points.Length > 0) legacyMode = true;
|
||||
serializedVersion = 1;
|
||||
}
|
||||
base.Awake();
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/GraphUpdateScene.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/GraphUpdateScene.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: efee954c69f0d421086729bb8df1137f
|
||||
timeCreated: 1490044676
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: -221
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
143
AR/Assets/AstarPathfindingProject/Core/GraphUpdateShape.cs
Normal file
143
AR/Assets/AstarPathfindingProject/Core/GraphUpdateShape.cs
Normal file
@ -0,0 +1,143 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace Pathfinding {
|
||||
/// <summary>
|
||||
/// Defines a shape for a Pathfinding.GraphUpdateObject.
|
||||
/// The shape consists of a number of points which it can either calculate the convex hull of or use as a polygon directly.
|
||||
///
|
||||
/// A shape is essentially a 2D shape however it can be rotated arbitrarily.
|
||||
/// When a matrix and a list of points is specified in the constructor the matrix decides what direction
|
||||
/// is the 'up' direction. When checking if a point is contained in the shape, the point will be projected down
|
||||
/// on a plane where the 'up' direction is the normal and then it will check if the shape contains the point.
|
||||
///
|
||||
/// See: Pathfinding.GraphUpdateObject.shape
|
||||
/// </summary>
|
||||
public class GraphUpdateShape {
|
||||
Vector3[] _points;
|
||||
Vector3[] _convexPoints;
|
||||
bool _convex;
|
||||
Vector3 right = Vector3.right;
|
||||
Vector3 forward = Vector3.forward;
|
||||
Vector3 up = Vector3.up;
|
||||
Vector3 origin;
|
||||
public float minimumHeight;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the points of the polygon in the shape.
|
||||
/// These points should be specified in clockwise order.
|
||||
/// Will automatically calculate the convex hull if <see cref="convex"/> is set to true
|
||||
/// </summary>
|
||||
public Vector3[] points {
|
||||
get {
|
||||
return _points;
|
||||
}
|
||||
set {
|
||||
_points = value;
|
||||
if (convex) CalculateConvexHull();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets if the convex hull of the points should be calculated.
|
||||
/// Convex hulls are faster but non-convex hulls can be used to specify more complicated shapes.
|
||||
/// </summary>
|
||||
public bool convex {
|
||||
get {
|
||||
return _convex;
|
||||
}
|
||||
set {
|
||||
if (_convex != value && value) {
|
||||
CalculateConvexHull();
|
||||
}
|
||||
_convex = value;
|
||||
}
|
||||
}
|
||||
|
||||
public GraphUpdateShape () {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Construct a shape.
|
||||
/// See: <see cref="convex"/>
|
||||
/// </summary>
|
||||
/// <param name="points">Contour of the shape in local space with respect to the matrix (i.e the shape should be in the XZ plane, the Y coordinate will only affect the bounds)</param>
|
||||
/// <param name="convex">If true, the convex hull of the points will be calculated.</param>
|
||||
/// <param name="matrix">local to world space matrix for the points. The matrix determines the up direction of the shape.</param>
|
||||
/// <param name="minimumHeight">If the points would be in the XZ plane only, the shape would not have a height and then it might not
|
||||
/// include any points inside it (as testing for inclusion is done in 3D space when updating graphs). This ensures
|
||||
/// that the shape has at least the minimum height (in the up direction that the matrix specifies).</param>
|
||||
public GraphUpdateShape (Vector3[] points, bool convex, Matrix4x4 matrix, float minimumHeight) {
|
||||
this.convex = convex;
|
||||
this.points = points;
|
||||
origin = matrix.MultiplyPoint3x4(Vector3.zero);
|
||||
right = matrix.MultiplyPoint3x4(Vector3.right) - origin;
|
||||
up = matrix.MultiplyPoint3x4(Vector3.up) - origin;
|
||||
forward = matrix.MultiplyPoint3x4(Vector3.forward) - origin;
|
||||
this.minimumHeight = minimumHeight;
|
||||
}
|
||||
|
||||
void CalculateConvexHull () {
|
||||
_convexPoints = points != null? Polygon.ConvexHullXZ(points) : null;
|
||||
}
|
||||
|
||||
/// <summary>World space bounding box of this shape</summary>
|
||||
public Bounds GetBounds () {
|
||||
return GetBounds(convex ? _convexPoints : points, right, up, forward, origin, minimumHeight);
|
||||
}
|
||||
|
||||
public static Bounds GetBounds (Vector3[] points, Matrix4x4 matrix, float minimumHeight) {
|
||||
var origin = matrix.MultiplyPoint3x4(Vector3.zero);
|
||||
var right = matrix.MultiplyPoint3x4(Vector3.right) - origin;
|
||||
var up = matrix.MultiplyPoint3x4(Vector3.up) - origin;
|
||||
var forward = matrix.MultiplyPoint3x4(Vector3.forward) - origin;
|
||||
|
||||
return GetBounds(points, right, up, forward, origin, minimumHeight);
|
||||
}
|
||||
|
||||
static Bounds GetBounds (Vector3[] points, Vector3 right, Vector3 up, Vector3 forward, Vector3 origin, float minimumHeight) {
|
||||
if (points == null || points.Length == 0) return new Bounds();
|
||||
float miny = points[0].y, maxy = points[0].y;
|
||||
for (int i = 0; i < points.Length; i++) {
|
||||
miny = Mathf.Min(miny, points[i].y);
|
||||
maxy = Mathf.Max(maxy, points[i].y);
|
||||
}
|
||||
var extraHeight = Mathf.Max(minimumHeight - (maxy - miny), 0) * 0.5f;
|
||||
miny -= extraHeight;
|
||||
maxy += extraHeight;
|
||||
|
||||
Vector3 min = right * points[0].x + up * points[0].y + forward * points[0].z;
|
||||
Vector3 max = min;
|
||||
for (int i = 0; i < points.Length; i++) {
|
||||
var p = right * points[i].x + forward * points[i].z;
|
||||
var p1 = p + up * miny;
|
||||
var p2 = p + up * maxy;
|
||||
min = Vector3.Min(min, p1);
|
||||
min = Vector3.Min(min, p2);
|
||||
max = Vector3.Max(max, p1);
|
||||
max = Vector3.Max(max, p2);
|
||||
}
|
||||
return new Bounds((min+max)*0.5F + origin, max-min);
|
||||
}
|
||||
|
||||
public bool Contains (GraphNode node) {
|
||||
return Contains((Vector3)node.position);
|
||||
}
|
||||
|
||||
public bool Contains (Vector3 point) {
|
||||
// Transform to local space (shape in the XZ plane)
|
||||
point -= origin;
|
||||
var localSpacePoint = new Vector3(Vector3.Dot(point, right)/right.sqrMagnitude, 0, Vector3.Dot(point, forward)/forward.sqrMagnitude);
|
||||
|
||||
if (convex) {
|
||||
if (_convexPoints == null) return false;
|
||||
|
||||
for (int i = 0, j = _convexPoints.Length-1; i < _convexPoints.Length; j = i, i++) {
|
||||
if (VectorMath.RightOrColinearXZ(_convexPoints[i], _convexPoints[j], localSpacePoint)) return false;
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
return _points != null && Polygon.ContainsPointXZ(_points, localSpacePoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
7
AR/Assets/AstarPathfindingProject/Core/GraphUpdateShape.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/GraphUpdateShape.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1c31d3b0be14344e98aa458dc66c3a94
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
2
AR/Assets/AstarPathfindingProject/Core/Misc.meta
generated
Normal file
2
AR/Assets/AstarPathfindingProject/Core/Misc.meta
generated
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: dfc976d61106d46b6a18ace94ffaea8d
|
122
AR/Assets/AstarPathfindingProject/Core/Misc/AnimationLink.cs
Normal file
122
AR/Assets/AstarPathfindingProject/Core/Misc/AnimationLink.cs
Normal file
@ -0,0 +1,122 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding {
|
||||
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_animation_link.php")]
|
||||
public class AnimationLink : NodeLink2 {
|
||||
public string clip;
|
||||
public float animSpeed = 1;
|
||||
public bool reverseAnim = true;
|
||||
|
||||
public GameObject referenceMesh;
|
||||
public LinkClip[] sequence;
|
||||
public string boneRoot = "bn_COG_Root";
|
||||
|
||||
[System.Serializable]
|
||||
public class LinkClip {
|
||||
public AnimationClip clip;
|
||||
public Vector3 velocity;
|
||||
public int loopCount = 1;
|
||||
|
||||
public string name {
|
||||
get {
|
||||
return clip != null ? clip.name : "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static Transform SearchRec (Transform tr, string name) {
|
||||
int childCount = tr.childCount;
|
||||
|
||||
for (int i = 0; i < childCount; i++) {
|
||||
Transform ch = tr.GetChild(i);
|
||||
if (ch.name == name) return ch;
|
||||
else {
|
||||
Transform rec = SearchRec(ch, name);
|
||||
if (rec != null) return rec;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void CalculateOffsets (List<Vector3> trace, out Vector3 endPosition) {
|
||||
//Vector3 opos = transform.position;
|
||||
endPosition = transform.position;
|
||||
if (referenceMesh == null) return;
|
||||
|
||||
GameObject ob = GameObject.Instantiate(referenceMesh, transform.position, transform.rotation) as GameObject;
|
||||
ob.hideFlags = HideFlags.HideAndDontSave;
|
||||
|
||||
Transform root = SearchRec(ob.transform, boneRoot);
|
||||
if (root == null) throw new System.Exception("Could not find root transform");
|
||||
|
||||
Animation anim = ob.GetComponent<Animation>();
|
||||
if (anim == null) anim = ob.AddComponent<Animation>();
|
||||
|
||||
for (int i = 0; i < sequence.Length; i++) {
|
||||
anim.AddClip(sequence[i].clip, sequence[i].clip.name);
|
||||
}
|
||||
|
||||
Vector3 prevOffset = Vector3.zero;
|
||||
Vector3 position = transform.position;
|
||||
Vector3 firstOffset = Vector3.zero;
|
||||
|
||||
for (int i = 0; i < sequence.Length; i++) {
|
||||
LinkClip c = sequence[i];
|
||||
if (c == null) {
|
||||
endPosition = position;
|
||||
return;
|
||||
}
|
||||
|
||||
anim[c.clip.name].enabled = true;
|
||||
anim[c.clip.name].weight = 1;
|
||||
|
||||
for (int repeat = 0; repeat < c.loopCount; repeat++) {
|
||||
anim[c.clip.name].normalizedTime = 0;
|
||||
anim.Sample();
|
||||
Vector3 soffset = root.position - transform.position;
|
||||
|
||||
if (i > 0) {
|
||||
position += prevOffset - soffset;
|
||||
} else {
|
||||
firstOffset = soffset;
|
||||
}
|
||||
|
||||
for (int t = 0; t <= 20; t++) {
|
||||
float tf = t/20.0f;
|
||||
anim[c.clip.name].normalizedTime = tf;
|
||||
anim.Sample();
|
||||
Vector3 tmp = position + (root.position-transform.position) + c.velocity*tf*c.clip.length;
|
||||
trace.Add(tmp);
|
||||
}
|
||||
position = position + c.velocity*1*c.clip.length;
|
||||
|
||||
anim[c.clip.name].normalizedTime = 1;
|
||||
anim.Sample();
|
||||
Vector3 eoffset = root.position - transform.position;
|
||||
prevOffset = eoffset;
|
||||
}
|
||||
|
||||
anim[c.clip.name].enabled = false;
|
||||
anim[c.clip.name].weight = 0;
|
||||
}
|
||||
|
||||
position += prevOffset - firstOffset;
|
||||
|
||||
GameObject.DestroyImmediate(ob);
|
||||
|
||||
endPosition = position;
|
||||
}
|
||||
|
||||
public override void OnDrawGizmosSelected () {
|
||||
base.OnDrawGizmosSelected();
|
||||
List<Vector3> buffer = Pathfinding.Util.ListPool<Vector3>.Claim();
|
||||
Vector3 endPosition = Vector3.zero;
|
||||
CalculateOffsets(buffer, out endPosition);
|
||||
Gizmos.color = Color.blue;
|
||||
for (int i = 0; i < buffer.Count-1; i++) {
|
||||
Gizmos.DrawLine(buffer[i], buffer[i+1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
8
AR/Assets/AstarPathfindingProject/Core/Misc/AnimationLink.cs.meta
generated
Normal file
8
AR/Assets/AstarPathfindingProject/Core/Misc/AnimationLink.cs.meta
generated
Normal file
@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d2e8b1fd6fa484fc29f8a26fb5e8662b
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
198
AR/Assets/AstarPathfindingProject/Core/Misc/ArrayPool.cs
Normal file
198
AR/Assets/AstarPathfindingProject/Core/Misc/ArrayPool.cs
Normal file
@ -0,0 +1,198 @@
|
||||
#if !UNITY_EDITOR
|
||||
// Extra optimizations when not running in the editor, but less error checking
|
||||
#define ASTAR_OPTIMIZE_POOLING
|
||||
#endif
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding.Util {
|
||||
/// <summary>
|
||||
/// Lightweight Array Pool.
|
||||
/// Handy class for pooling arrays of type T.
|
||||
///
|
||||
/// Usage:
|
||||
/// - Claim a new array using <code> SomeClass[] foo = ArrayPool<SomeClass>.Claim (capacity); </code>
|
||||
/// - Use it and do stuff with it
|
||||
/// - Release it with <code> ArrayPool<SomeClass>.Release (foo); </code>
|
||||
///
|
||||
/// Warning: Arrays returned from the Claim method may contain arbitrary data.
|
||||
/// You cannot rely on it being zeroed out.
|
||||
///
|
||||
/// After you have released a array, you should never use it again, if you do use it
|
||||
/// your code may modify it at the same time as some other code is using it which
|
||||
/// will likely lead to bad results.
|
||||
///
|
||||
/// \since Version 3.8.6
|
||||
/// See: Pathfinding.Util.ListPool
|
||||
/// </summary>
|
||||
public static class ArrayPool<T> {
|
||||
#if !ASTAR_NO_POOLING
|
||||
/// <summary>
|
||||
/// Maximum length of an array pooled using ClaimWithExactLength.
|
||||
/// Arrays with lengths longer than this will silently not be pooled.
|
||||
/// </summary>
|
||||
const int MaximumExactArrayLength = 256;
|
||||
|
||||
/// <summary>
|
||||
/// Internal pool.
|
||||
/// The arrays in each bucket have lengths of 2^i
|
||||
/// </summary>
|
||||
static readonly Stack<T[]>[] pool = new Stack<T[]>[31];
|
||||
static readonly Stack<T[]>[] exactPool = new Stack<T[]>[MaximumExactArrayLength+1];
|
||||
#if !ASTAR_OPTIMIZE_POOLING
|
||||
static readonly HashSet<T[]> inPool = new HashSet<T[]>();
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Returns an array with at least the specified length.
|
||||
/// Warning: Returned arrays may contain arbitrary data.
|
||||
/// You cannot rely on it being zeroed out.
|
||||
/// </summary>
|
||||
public static T[] Claim (int minimumLength) {
|
||||
if (minimumLength <= 0) {
|
||||
return ClaimWithExactLength(0);
|
||||
}
|
||||
|
||||
int bucketIndex = 0;
|
||||
while ((1 << bucketIndex) < minimumLength && bucketIndex < 30) {
|
||||
bucketIndex++;
|
||||
}
|
||||
|
||||
if (bucketIndex == 30)
|
||||
throw new System.ArgumentException("Too high minimum length");
|
||||
|
||||
#if !ASTAR_NO_POOLING
|
||||
lock (pool) {
|
||||
if (pool[bucketIndex] == null) {
|
||||
pool[bucketIndex] = new Stack<T[]>();
|
||||
}
|
||||
|
||||
if (pool[bucketIndex].Count > 0) {
|
||||
var array = pool[bucketIndex].Pop();
|
||||
#if !ASTAR_OPTIMIZE_POOLING
|
||||
inPool.Remove(array);
|
||||
#endif
|
||||
return array;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return new T[1 << bucketIndex];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns an array with the specified length.
|
||||
/// Use with caution as pooling too many arrays with different lengths that
|
||||
/// are rarely being reused will lead to an effective memory leak.
|
||||
///
|
||||
/// Use <see cref="Claim"/> if you just need an array that is at least as large as some value.
|
||||
///
|
||||
/// Warning: Returned arrays may contain arbitrary data.
|
||||
/// You cannot rely on it being zeroed out.
|
||||
/// </summary>
|
||||
public static T[] ClaimWithExactLength (int length) {
|
||||
#if !ASTAR_NO_POOLING
|
||||
bool isPowerOfTwo = length != 0 && (length & (length - 1)) == 0;
|
||||
if (isPowerOfTwo) {
|
||||
// Will return the correct array length
|
||||
return Claim(length);
|
||||
}
|
||||
|
||||
if (length <= MaximumExactArrayLength) {
|
||||
lock (pool) {
|
||||
Stack<T[]> stack = exactPool[length];
|
||||
if (stack != null && stack.Count > 0) {
|
||||
var array = stack.Pop();
|
||||
#if !ASTAR_OPTIMIZE_POOLING
|
||||
inPool.Remove(array);
|
||||
#endif
|
||||
return array;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return new T[length];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pool an array.
|
||||
/// If the array was got using the <see cref="ClaimWithExactLength"/> method then the allowNonPowerOfTwo parameter must be set to true.
|
||||
/// The parameter exists to make sure that non power of two arrays are not pooled unintentionally which could lead to memory leaks.
|
||||
/// </summary>
|
||||
public static void Release (ref T[] array, bool allowNonPowerOfTwo = false) {
|
||||
if (array == null) return;
|
||||
if (array.GetType() != typeof(T[])) {
|
||||
throw new System.ArgumentException("Expected array type " + typeof(T[]).Name + " but found " + array.GetType().Name + "\nAre you using the correct generic class?\n");
|
||||
}
|
||||
|
||||
#if !ASTAR_NO_POOLING
|
||||
bool isPowerOfTwo = array.Length != 0 && (array.Length & (array.Length - 1)) == 0;
|
||||
if (!isPowerOfTwo && !allowNonPowerOfTwo && array.Length != 0) throw new System.ArgumentException("Length is not a power of 2");
|
||||
|
||||
lock (pool) {
|
||||
#if !ASTAR_OPTIMIZE_POOLING
|
||||
if (!inPool.Add(array)) {
|
||||
throw new InvalidOperationException("You are trying to pool an array twice. Please make sure that you only pool it once.");
|
||||
}
|
||||
#endif
|
||||
if (isPowerOfTwo) {
|
||||
int bucketIndex = 0;
|
||||
while ((1 << bucketIndex) < array.Length && bucketIndex < 30) {
|
||||
bucketIndex++;
|
||||
}
|
||||
|
||||
if (pool[bucketIndex] == null) {
|
||||
pool[bucketIndex] = new Stack<T[]>();
|
||||
}
|
||||
|
||||
pool[bucketIndex].Push(array);
|
||||
} else if (array.Length <= MaximumExactArrayLength) {
|
||||
Stack<T[]> stack = exactPool[array.Length];
|
||||
if (stack == null) stack = exactPool[array.Length] = new Stack<T[]>();
|
||||
stack.Push(array);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
array = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Extension methods for List<T></summary>
|
||||
public static class ListExtensions {
|
||||
/// <summary>
|
||||
/// Identical to ToArray but it uses ArrayPool<T> to avoid allocations if possible.
|
||||
///
|
||||
/// Use with caution as pooling too many arrays with different lengths that
|
||||
/// are rarely being reused will lead to an effective memory leak.
|
||||
/// </summary>
|
||||
public static T[] ToArrayFromPool<T>(this List<T> list) {
|
||||
var arr = ArrayPool<T>.ClaimWithExactLength(list.Count);
|
||||
|
||||
for (int i = 0; i < arr.Length; i++) {
|
||||
arr[i] = list[i];
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clear a list faster than List<T>.Clear.
|
||||
/// It turns out that the List<T>.Clear method will clear all elements in the underlaying array
|
||||
/// not just the ones up to Count. If the list only has a few elements, but the capacity
|
||||
/// is huge, this can cause performance problems. Using the RemoveRange method to remove
|
||||
/// all elements in the list does not have this problem, however it is implemented in a
|
||||
/// stupid way, so it will clear the elements twice (completely unnecessarily) so it will
|
||||
/// only be faster than using the Clear method if the number of elements in the list is
|
||||
/// less than half of the capacity of the list.
|
||||
///
|
||||
/// Hopefully this method can be removed when Unity upgrades to a newer version of Mono.
|
||||
/// </summary>
|
||||
public static void ClearFast<T>(this List<T> list) {
|
||||
if (list.Count*2 < list.Capacity) {
|
||||
list.RemoveRange(0, list.Count);
|
||||
} else {
|
||||
list.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/Misc/ArrayPool.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/Misc/ArrayPool.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 787a564bf2d894ee09284b775074864c
|
||||
timeCreated: 1470483941
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
337
AR/Assets/AstarPathfindingProject/Core/Misc/AstarDebugger.cs
Normal file
337
AR/Assets/AstarPathfindingProject/Core/Misc/AstarDebugger.cs
Normal file
@ -0,0 +1,337 @@
|
||||
//#define ProfileAstar
|
||||
|
||||
using UnityEngine;
|
||||
using System.Text;
|
||||
|
||||
namespace Pathfinding {
|
||||
[AddComponentMenu("Pathfinding/Pathfinding Debugger")]
|
||||
[ExecuteInEditMode]
|
||||
/// <summary>
|
||||
/// Debugger for the A* Pathfinding Project.
|
||||
/// This class can be used to profile different parts of the pathfinding system
|
||||
/// and the whole game as well to some extent.
|
||||
///
|
||||
/// Clarification of the labels shown when enabled.
|
||||
/// All memory related things profiles <b>the whole game</b> not just the A* Pathfinding System.\n
|
||||
/// - Currently allocated: memory the GC (garbage collector) says the application has allocated right now.
|
||||
/// - Peak allocated: maximum measured value of the above.
|
||||
/// - Last collect peak: the last peak of 'currently allocated'.
|
||||
/// - Allocation rate: how much the 'currently allocated' value increases per second. This value is not as reliable as you can think
|
||||
/// it is often very random probably depending on how the GC thinks this application is using memory.
|
||||
/// - Collection frequency: how often the GC is called. Again, the GC might decide it is better with many small collections
|
||||
/// or with a few large collections. So you cannot really trust this variable much.
|
||||
/// - Last collect fps: FPS during the last garbage collection, the GC will lower the fps a lot.
|
||||
///
|
||||
/// - FPS: current FPS (not updated every frame for readability)
|
||||
/// - Lowest FPS (last x): As the label says, the lowest fps of the last x frames.
|
||||
///
|
||||
/// - Size: Size of the path pool.
|
||||
/// - Total created: Number of paths of that type which has been created. Pooled paths are not counted twice.
|
||||
/// If this value just keeps on growing and growing without an apparent stop, you are are either not pooling any paths
|
||||
/// or you have missed to pool some path somewhere in your code.
|
||||
///
|
||||
/// See: pooling
|
||||
///
|
||||
/// TODO: Add field showing how many graph updates are being done right now
|
||||
/// </summary>
|
||||
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_astar_debugger.php")]
|
||||
public class AstarDebugger : VersionedMonoBehaviour {
|
||||
public int yOffset = 5;
|
||||
|
||||
public bool show = true;
|
||||
public bool showInEditor = false;
|
||||
|
||||
public bool showFPS = false;
|
||||
public bool showPathProfile = false;
|
||||
public bool showMemProfile = false;
|
||||
public bool showGraph = false;
|
||||
|
||||
public int graphBufferSize = 200;
|
||||
|
||||
/// <summary>
|
||||
/// Font to use.
|
||||
/// A monospaced font is the best
|
||||
/// </summary>
|
||||
public Font font = null;
|
||||
public int fontSize = 12;
|
||||
|
||||
StringBuilder text = new StringBuilder();
|
||||
string cachedText;
|
||||
float lastUpdate = -999;
|
||||
|
||||
private GraphPoint[] graph;
|
||||
|
||||
struct GraphPoint {
|
||||
public float fps, memory;
|
||||
public bool collectEvent;
|
||||
}
|
||||
|
||||
private float delayedDeltaTime = 1;
|
||||
private float lastCollect = 0;
|
||||
private float lastCollectNum = 0;
|
||||
private float delta = 0;
|
||||
private float lastDeltaTime = 0;
|
||||
private int allocRate = 0;
|
||||
private int lastAllocMemory = 0;
|
||||
private float lastAllocSet = -9999;
|
||||
private int allocMem = 0;
|
||||
private int collectAlloc = 0;
|
||||
private int peakAlloc = 0;
|
||||
|
||||
private int fpsDropCounterSize = 200;
|
||||
private float[] fpsDrops;
|
||||
|
||||
private Rect boxRect;
|
||||
|
||||
private GUIStyle style;
|
||||
|
||||
private Camera cam;
|
||||
|
||||
float graphWidth = 100;
|
||||
float graphHeight = 100;
|
||||
float graphOffset = 50;
|
||||
|
||||
public void Start () {
|
||||
useGUILayout = false;
|
||||
|
||||
fpsDrops = new float[fpsDropCounterSize];
|
||||
|
||||
cam = GetComponent<Camera>();
|
||||
if (cam == null) {
|
||||
cam = Camera.main;
|
||||
}
|
||||
|
||||
graph = new GraphPoint[graphBufferSize];
|
||||
|
||||
if (Time.unscaledDeltaTime > 0) {
|
||||
for (int i = 0; i < fpsDrops.Length; i++) {
|
||||
fpsDrops[i] = 1F / Time.unscaledDeltaTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int maxVecPool = 0;
|
||||
int maxNodePool = 0;
|
||||
|
||||
PathTypeDebug[] debugTypes = new PathTypeDebug[] {
|
||||
new PathTypeDebug("ABPath", () => PathPool.GetSize(typeof(ABPath)), () => PathPool.GetTotalCreated(typeof(ABPath)))
|
||||
};
|
||||
|
||||
struct PathTypeDebug {
|
||||
string name;
|
||||
System.Func<int> getSize;
|
||||
System.Func<int> getTotalCreated;
|
||||
public PathTypeDebug (string name, System.Func<int> getSize, System.Func<int> getTotalCreated) {
|
||||
this.name = name;
|
||||
this.getSize = getSize;
|
||||
this.getTotalCreated = getTotalCreated;
|
||||
}
|
||||
|
||||
public void Print (StringBuilder text) {
|
||||
int totCreated = getTotalCreated();
|
||||
|
||||
if (totCreated > 0) {
|
||||
text.Append("\n").Append((" " + name).PadRight(25)).Append(getSize()).Append("/").Append(totCreated);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void LateUpdate () {
|
||||
if (!show || (!Application.isPlaying && !showInEditor)) return;
|
||||
|
||||
if (Time.unscaledDeltaTime <= 0.0001f)
|
||||
return;
|
||||
|
||||
int collCount = System.GC.CollectionCount(0);
|
||||
|
||||
if (lastCollectNum != collCount) {
|
||||
lastCollectNum = collCount;
|
||||
delta = Time.realtimeSinceStartup-lastCollect;
|
||||
lastCollect = Time.realtimeSinceStartup;
|
||||
lastDeltaTime = Time.unscaledDeltaTime;
|
||||
collectAlloc = allocMem;
|
||||
}
|
||||
|
||||
allocMem = (int)System.GC.GetTotalMemory(false);
|
||||
|
||||
bool collectEvent = allocMem < peakAlloc;
|
||||
peakAlloc = !collectEvent ? allocMem : peakAlloc;
|
||||
|
||||
if (Time.realtimeSinceStartup - lastAllocSet > 0.3F || !Application.isPlaying) {
|
||||
int diff = allocMem - lastAllocMemory;
|
||||
lastAllocMemory = allocMem;
|
||||
lastAllocSet = Time.realtimeSinceStartup;
|
||||
delayedDeltaTime = Time.unscaledDeltaTime;
|
||||
|
||||
if (diff >= 0) {
|
||||
allocRate = diff;
|
||||
}
|
||||
}
|
||||
|
||||
if (Application.isPlaying) {
|
||||
fpsDrops[Time.frameCount % fpsDrops.Length] = Time.unscaledDeltaTime > 0.00001f ? 1F / Time.unscaledDeltaTime : 0;
|
||||
int graphIndex = Time.frameCount % graph.Length;
|
||||
graph[graphIndex].fps = Time.unscaledDeltaTime < 0.00001f ? 1F / Time.unscaledDeltaTime : 0;
|
||||
graph[graphIndex].collectEvent = collectEvent;
|
||||
graph[graphIndex].memory = allocMem;
|
||||
}
|
||||
|
||||
if (Application.isPlaying && cam != null && showGraph) {
|
||||
graphWidth = cam.pixelWidth*0.8f;
|
||||
|
||||
|
||||
float minMem = float.PositiveInfinity, maxMem = 0, minFPS = float.PositiveInfinity, maxFPS = 0;
|
||||
for (int i = 0; i < graph.Length; i++) {
|
||||
minMem = Mathf.Min(graph[i].memory, minMem);
|
||||
maxMem = Mathf.Max(graph[i].memory, maxMem);
|
||||
minFPS = Mathf.Min(graph[i].fps, minFPS);
|
||||
maxFPS = Mathf.Max(graph[i].fps, maxFPS);
|
||||
}
|
||||
|
||||
int currentGraphIndex = Time.frameCount % graph.Length;
|
||||
|
||||
Matrix4x4 m = Matrix4x4.TRS(new Vector3((cam.pixelWidth - graphWidth)/2f, graphOffset, 1), Quaternion.identity, new Vector3(graphWidth, graphHeight, 1));
|
||||
|
||||
for (int i = 0; i < graph.Length-1; i++) {
|
||||
if (i == currentGraphIndex) continue;
|
||||
|
||||
DrawGraphLine(i, m, i/(float)graph.Length, (i+1)/(float)graph.Length, Mathf.InverseLerp(minMem, maxMem, graph[i].memory), Mathf.InverseLerp(minMem, maxMem, graph[i+1].memory), Color.blue);
|
||||
DrawGraphLine(i, m, i/(float)graph.Length, (i+1)/(float)graph.Length, Mathf.InverseLerp(minFPS, maxFPS, graph[i].fps), Mathf.InverseLerp(minFPS, maxFPS, graph[i+1].fps), Color.green);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void DrawGraphLine (int index, Matrix4x4 m, float x1, float x2, float y1, float y2, Color color) {
|
||||
Debug.DrawLine(cam.ScreenToWorldPoint(m.MultiplyPoint3x4(new Vector3(x1, y1))), cam.ScreenToWorldPoint(m.MultiplyPoint3x4(new Vector3(x2, y2))), color);
|
||||
}
|
||||
|
||||
public void OnGUI () {
|
||||
if (!show || (!Application.isPlaying && !showInEditor)) return;
|
||||
|
||||
if (style == null) {
|
||||
style = new GUIStyle();
|
||||
style.normal.textColor = Color.white;
|
||||
style.padding = new RectOffset(5, 5, 5, 5);
|
||||
}
|
||||
|
||||
if (Time.realtimeSinceStartup - lastUpdate > 0.5f || cachedText == null || !Application.isPlaying) {
|
||||
lastUpdate = Time.realtimeSinceStartup;
|
||||
|
||||
boxRect = new Rect(5, yOffset, 310, 40);
|
||||
|
||||
text.Length = 0;
|
||||
text.AppendLine("A* Pathfinding Project Debugger");
|
||||
text.Append("A* Version: ").Append(AstarPath.Version.ToString());
|
||||
|
||||
if (showMemProfile) {
|
||||
boxRect.height += 200;
|
||||
|
||||
text.AppendLine();
|
||||
text.AppendLine();
|
||||
text.Append("Currently allocated".PadRight(25));
|
||||
text.Append((allocMem/1000000F).ToString("0.0 MB"));
|
||||
text.AppendLine();
|
||||
|
||||
text.Append("Peak allocated".PadRight(25));
|
||||
text.Append((peakAlloc/1000000F).ToString("0.0 MB")).AppendLine();
|
||||
|
||||
text.Append("Last collect peak".PadRight(25));
|
||||
text.Append((collectAlloc/1000000F).ToString("0.0 MB")).AppendLine();
|
||||
|
||||
|
||||
text.Append("Allocation rate".PadRight(25));
|
||||
text.Append((allocRate/1000000F).ToString("0.0 MB")).AppendLine();
|
||||
|
||||
text.Append("Collection frequency".PadRight(25));
|
||||
text.Append(delta.ToString("0.00"));
|
||||
text.Append("s\n");
|
||||
|
||||
text.Append("Last collect fps".PadRight(25));
|
||||
text.Append((1F/lastDeltaTime).ToString("0.0 fps"));
|
||||
text.Append(" (");
|
||||
text.Append(lastDeltaTime.ToString("0.000 s"));
|
||||
text.Append(")");
|
||||
}
|
||||
|
||||
if (showFPS) {
|
||||
text.AppendLine();
|
||||
text.AppendLine();
|
||||
var delayedFPS = delayedDeltaTime > 0.00001f ? 1F/delayedDeltaTime : 0;
|
||||
text.Append("FPS".PadRight(25)).Append(delayedFPS.ToString("0.0 fps"));
|
||||
|
||||
|
||||
float minFps = Mathf.Infinity;
|
||||
|
||||
for (int i = 0; i < fpsDrops.Length; i++) if (fpsDrops[i] < minFps) minFps = fpsDrops[i];
|
||||
|
||||
text.AppendLine();
|
||||
text.Append(("Lowest fps (last " + fpsDrops.Length + ")").PadRight(25)).Append(minFps.ToString("0.0"));
|
||||
}
|
||||
|
||||
if (showPathProfile) {
|
||||
AstarPath astar = AstarPath.active;
|
||||
|
||||
text.AppendLine();
|
||||
|
||||
if (astar == null) {
|
||||
text.Append("\nNo AstarPath Object In The Scene");
|
||||
} else {
|
||||
#if ProfileAstar
|
||||
double searchSpeed = (double)AstarPath.TotalSearchedNodes*10000 / (double)AstarPath.TotalSearchTime;
|
||||
text.Append("\nSearch Speed (nodes/ms) ").Append(searchSpeed.ToString("0")).Append(" ("+AstarPath.TotalSearchedNodes+" / ").Append(((double)AstarPath.TotalSearchTime/10000F).ToString("0")+")");
|
||||
#endif
|
||||
|
||||
if (Pathfinding.Util.ListPool<Vector3>.GetSize() > maxVecPool) maxVecPool = Pathfinding.Util.ListPool<Vector3>.GetSize();
|
||||
if (Pathfinding.Util.ListPool<Pathfinding.GraphNode>.GetSize() > maxNodePool) maxNodePool = Pathfinding.Util.ListPool<Pathfinding.GraphNode>.GetSize();
|
||||
|
||||
text.Append("\nPool Sizes (size/total created)");
|
||||
|
||||
for (int i = 0; i < debugTypes.Length; i++) {
|
||||
debugTypes[i].Print(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cachedText = text.ToString();
|
||||
}
|
||||
|
||||
|
||||
if (font != null) {
|
||||
style.font = font;
|
||||
style.fontSize = fontSize;
|
||||
}
|
||||
|
||||
boxRect.height = style.CalcHeight(new GUIContent(cachedText), boxRect.width);
|
||||
|
||||
GUI.Box(boxRect, "");
|
||||
GUI.Label(boxRect, cachedText, style);
|
||||
|
||||
if (showGraph) {
|
||||
float minMem = float.PositiveInfinity, maxMem = 0, minFPS = float.PositiveInfinity, maxFPS = 0;
|
||||
for (int i = 0; i < graph.Length; i++) {
|
||||
minMem = Mathf.Min(graph[i].memory, minMem);
|
||||
maxMem = Mathf.Max(graph[i].memory, maxMem);
|
||||
minFPS = Mathf.Min(graph[i].fps, minFPS);
|
||||
maxFPS = Mathf.Max(graph[i].fps, maxFPS);
|
||||
}
|
||||
|
||||
float line;
|
||||
GUI.color = Color.blue;
|
||||
// Round to nearest x.x MB
|
||||
line = Mathf.RoundToInt(maxMem/(100.0f*1000));
|
||||
GUI.Label(new Rect(5, Screen.height - AstarMath.MapTo(minMem, maxMem, 0 + graphOffset, graphHeight + graphOffset, line*1000*100) - 10, 100, 20), (line/10.0f).ToString("0.0 MB"));
|
||||
|
||||
line = Mathf.Round(minMem/(100.0f*1000));
|
||||
GUI.Label(new Rect(5, Screen.height - AstarMath.MapTo(minMem, maxMem, 0 + graphOffset, graphHeight + graphOffset, line*1000*100) - 10, 100, 20), (line/10.0f).ToString("0.0 MB"));
|
||||
|
||||
GUI.color = Color.green;
|
||||
// Round to nearest x.x MB
|
||||
line = Mathf.Round(maxFPS);
|
||||
GUI.Label(new Rect(55, Screen.height - AstarMath.MapTo(minFPS, maxFPS, 0 + graphOffset, graphHeight + graphOffset, line) - 10, 100, 20), line.ToString("0 FPS"));
|
||||
|
||||
line = Mathf.Round(minFPS);
|
||||
GUI.Label(new Rect(55, Screen.height - AstarMath.MapTo(minFPS, maxFPS, 0 + graphOffset, graphHeight + graphOffset, line) - 10, 100, 20), line.ToString("0 FPS"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
7
AR/Assets/AstarPathfindingProject/Core/Misc/AstarDebugger.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/Misc/AstarDebugger.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5103795af2d504ea693528e938005441
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
100
AR/Assets/AstarPathfindingProject/Core/Misc/AutoRepathPolicy.cs
Normal file
100
AR/Assets/AstarPathfindingProject/Core/Misc/AutoRepathPolicy.cs
Normal file
@ -0,0 +1,100 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace Pathfinding {
|
||||
using Pathfinding.Util;
|
||||
|
||||
/// <summary>
|
||||
/// Policy for how often to recalculate an agent's path.
|
||||
///
|
||||
/// See: \reflink{AIBase.autoRepath}
|
||||
/// See: \reflink{AILerp.autoRepath}
|
||||
/// </summary>
|
||||
[System.Serializable]
|
||||
public class AutoRepathPolicy {
|
||||
/// <summary>Policy mode for how often to recalculate an agent's path.</summary>
|
||||
public enum Mode {
|
||||
/// <summary>
|
||||
/// Never automatically recalculate the path.
|
||||
/// Paths can be recalculated manually by for example calling \reflink{IAstarAI.SearchPath} or \reflink{IAstarAI.SetPath}.
|
||||
/// This mode is useful if you want full control of when the agent calculates its path.
|
||||
/// </summary>
|
||||
Never,
|
||||
/// <summary>Recalculate the path every \reflink{interval} seconds</summary>
|
||||
EveryNSeconds,
|
||||
/// <summary>
|
||||
/// Recalculate the path at least every \reflink{maximumInterval} seconds but more often if the destination moves a lot.
|
||||
/// This mode is recommended since it allows the agent to quickly respond to new destinations without using up a lot of CPU power to calculate paths
|
||||
/// when it doesn't have to.
|
||||
///
|
||||
/// More precisely:\n
|
||||
/// Let C be a circle centered at the destination for the last calculated path with a radius equal to the distance to that point divided by \reflink{sensitivity}.\n
|
||||
/// If the new destination is outside that circle the path will be immediately recalculated.\n
|
||||
/// Otherwise let F be the 1 - (distance from the circle's center to the new destination divided by the circle's radius).\n
|
||||
/// So F will be 1 if the new destination is the same as the old one and 0 if it is at the circle's edge.\n
|
||||
/// Recalculate the path if the time since the last path recalculation is greater than \reflink{maximumInterval} multiplied by F.\n
|
||||
///
|
||||
/// Thus if the destination doesn't change the path will be recalculated every \reflink{maximumInterval} seconds.
|
||||
/// </summary>
|
||||
Dynamic,
|
||||
}
|
||||
|
||||
/// <summary>Policy to use when recalculating paths</summary>
|
||||
public Mode mode = Mode.Dynamic;
|
||||
|
||||
/// <summary>Number of seconds between each automatic path recalculation for Mode.EveryNSeconds</summary>
|
||||
public float interval = 0.5f;
|
||||
|
||||
/// <summary>
|
||||
/// How sensitive the agent should be to changes in its destination for Mode.Dynamic.
|
||||
/// A higher value means the destination has to move less for the path to be recalculated.
|
||||
///
|
||||
/// See: \reflink{Mode}
|
||||
/// </summary>
|
||||
public float sensitivity = 10.0f;
|
||||
|
||||
/// <summary>Maximum number of seconds between each automatic path recalculation for Mode.Dynamic</summary>
|
||||
public float maximumInterval = 2.0f;
|
||||
|
||||
/// <summary>If true the sensitivity will be visualized as a circle in the scene view when the game is playing</summary>
|
||||
public bool visualizeSensitivity = false;
|
||||
|
||||
Vector3 lastDestination = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
|
||||
float lastRepathTime = float.NegativeInfinity;
|
||||
|
||||
/// <summary>True if the path should be recalculated according to the policy</summary>
|
||||
public virtual bool ShouldRecalculatePath (IAstarAI ai) {
|
||||
if (mode == Mode.Never || float.IsPositiveInfinity(ai.destination.x)) return false;
|
||||
|
||||
float timeSinceLast = Time.time - lastRepathTime;
|
||||
if (mode == Mode.EveryNSeconds) {
|
||||
return timeSinceLast >= interval;
|
||||
} else {
|
||||
// cost = change in destination / max(distance to destination, radius)
|
||||
float squaredCost = (ai.destination - lastDestination).sqrMagnitude / Mathf.Max((ai.position - lastDestination).sqrMagnitude, ai.radius*ai.radius);
|
||||
float fraction = squaredCost * (sensitivity*sensitivity);
|
||||
if (fraction > 1.0f || float.IsNaN(fraction)) return true;
|
||||
|
||||
if (timeSinceLast >= maximumInterval*(1 - Mathf.Sqrt(fraction))) return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reset the runtime variables so that the policy behaves as if the game just started</summary>
|
||||
public virtual void Reset () {
|
||||
lastRepathTime = float.NegativeInfinity;
|
||||
}
|
||||
|
||||
/// <summary>Must be called when a path request has been scheduled</summary>
|
||||
public virtual void DidRecalculatePath (Vector3 destination) {
|
||||
lastRepathTime = Time.time;
|
||||
lastDestination = destination;
|
||||
}
|
||||
|
||||
public void DrawGizmos (IAstarAI ai) {
|
||||
if (visualizeSensitivity && !float.IsPositiveInfinity(lastDestination.x)) {
|
||||
float r = Mathf.Sqrt(Mathf.Max((ai.position - lastDestination).sqrMagnitude, ai.radius*ai.radius)/(sensitivity*sensitivity));
|
||||
Draw.Gizmos.CircleXZ(lastDestination, r, Color.magenta);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
11
AR/Assets/AstarPathfindingProject/Core/Misc/AutoRepathPolicy.cs.meta
generated
Normal file
11
AR/Assets/AstarPathfindingProject/Core/Misc/AutoRepathPolicy.cs.meta
generated
Normal file
@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2664ef60fd2811ba280670298a6d312b
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
324
AR/Assets/AstarPathfindingProject/Core/Misc/BinaryHeap.cs
Normal file
324
AR/Assets/AstarPathfindingProject/Core/Misc/BinaryHeap.cs
Normal file
@ -0,0 +1,324 @@
|
||||
#pragma warning disable 162
|
||||
#pragma warning disable 429
|
||||
#define DECREASE_KEY
|
||||
|
||||
namespace Pathfinding {
|
||||
/// <summary>
|
||||
/// Binary heap implementation.
|
||||
/// Binary heaps are really fast for ordering nodes in a way that
|
||||
/// makes it possible to get the node with the lowest F score.
|
||||
/// Also known as a priority queue.
|
||||
///
|
||||
/// This has actually been rewritten as a 4-ary heap
|
||||
/// for performance, but it's the same principle.
|
||||
///
|
||||
/// See: http://en.wikipedia.org/wiki/Binary_heap
|
||||
/// See: https://en.wikipedia.org/wiki/D-ary_heap
|
||||
/// </summary>
|
||||
public class BinaryHeap {
|
||||
/// <summary>Number of items in the tree</summary>
|
||||
public int numberOfItems;
|
||||
|
||||
/// <summary>The tree will grow by at least this factor every time it is expanded</summary>
|
||||
public float growthFactor = 2;
|
||||
|
||||
/// <summary>
|
||||
/// Number of children of each node in the tree.
|
||||
/// Different values have been tested and 4 has been empirically found to perform the best.
|
||||
/// See: https://en.wikipedia.org/wiki/D-ary_heap
|
||||
/// </summary>
|
||||
const int D = 4;
|
||||
|
||||
/// <summary>
|
||||
/// Sort nodes by G score if there is a tie when comparing the F score.
|
||||
/// Disabling this will improve pathfinding performance with around 2.5%
|
||||
/// but may break ties between paths that have the same length in a less
|
||||
/// desirable manner (only relevant for grid graphs).
|
||||
/// </summary>
|
||||
const bool SortGScores = true;
|
||||
|
||||
public const ushort NotInHeap = 0xFFFF;
|
||||
|
||||
/// <summary>Internal backing array for the heap</summary>
|
||||
private Tuple[] heap;
|
||||
|
||||
/// <summary>True if the heap does not contain any elements</summary>
|
||||
public bool isEmpty {
|
||||
get {
|
||||
return numberOfItems <= 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Item in the heap</summary>
|
||||
private struct Tuple {
|
||||
public PathNode node;
|
||||
public uint F;
|
||||
|
||||
public Tuple (uint f, PathNode node) {
|
||||
this.F = f;
|
||||
this.node = node;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rounds up v so that it has remainder 1 when divided by D.
|
||||
/// I.e it is of the form n*D + 1 where n is any non-negative integer.
|
||||
/// </summary>
|
||||
static int RoundUpToNextMultipleMod1 (int v) {
|
||||
// I have a feeling there is a nicer way to do this
|
||||
return v + (4 - ((v-1) % D)) % D;
|
||||
}
|
||||
|
||||
/// <summary>Create a new heap with the specified initial capacity</summary>
|
||||
public BinaryHeap (int capacity) {
|
||||
// Make sure the size has remainder 1 when divided by D
|
||||
// This allows us to always guarantee that indices used in the Remove method
|
||||
// will never throw out of bounds exceptions
|
||||
capacity = RoundUpToNextMultipleMod1(capacity);
|
||||
|
||||
heap = new Tuple[capacity];
|
||||
numberOfItems = 0;
|
||||
}
|
||||
|
||||
/// <summary>Removes all elements from the heap</summary>
|
||||
public void Clear () {
|
||||
#if DECREASE_KEY
|
||||
// Clear all heap indices
|
||||
// This is important to avoid bugs
|
||||
for (int i = 0; i < numberOfItems; i++) {
|
||||
heap[i].node.heapIndex = NotInHeap;
|
||||
}
|
||||
#endif
|
||||
|
||||
numberOfItems = 0;
|
||||
}
|
||||
|
||||
internal PathNode GetNode (int i) {
|
||||
return heap[i].node;
|
||||
}
|
||||
|
||||
internal void SetF (int i, uint f) {
|
||||
heap[i].F = f;
|
||||
}
|
||||
|
||||
/// <summary>Expands to a larger backing array when the current one is too small</summary>
|
||||
void Expand () {
|
||||
// 65533 == 1 mod 4 and slightly smaller than 1<<16 = 65536
|
||||
int newSize = System.Math.Max(heap.Length+4, System.Math.Min(65533, (int)System.Math.Round(heap.Length*growthFactor)));
|
||||
|
||||
// Make sure the size has remainder 1 when divided by D
|
||||
// This allows us to always guarantee that indices used in the Remove method
|
||||
// will never throw out of bounds exceptions
|
||||
newSize = RoundUpToNextMultipleMod1(newSize);
|
||||
|
||||
// Check if the heap is really large
|
||||
// Also note that heaps larger than this are not supported
|
||||
// since PathNode.heapIndex is a ushort and can only store
|
||||
// values up to 65535 (NotInHeap = 65535 is reserved however)
|
||||
if (newSize > (1<<16) - 2) {
|
||||
throw new System.Exception("Binary Heap Size really large (>65534). A heap size this large is probably the cause of pathfinding running in an infinite loop. ");
|
||||
}
|
||||
|
||||
var newHeap = new Tuple[newSize];
|
||||
heap.CopyTo(newHeap, 0);
|
||||
#if ASTARDEBUG
|
||||
UnityEngine.Debug.Log("Resizing binary heap to "+newSize);
|
||||
#endif
|
||||
heap = newHeap;
|
||||
}
|
||||
|
||||
/// <summary>Adds a node to the heap</summary>
|
||||
public void Add (PathNode node) {
|
||||
if (node == null) throw new System.ArgumentNullException("node");
|
||||
|
||||
#if DECREASE_KEY
|
||||
// Check if node is already in the heap
|
||||
if (node.heapIndex != NotInHeap) {
|
||||
DecreaseKey(heap[node.heapIndex], node.heapIndex);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (numberOfItems == heap.Length) {
|
||||
Expand();
|
||||
}
|
||||
|
||||
DecreaseKey(new Tuple(0, node), (ushort)numberOfItems);
|
||||
numberOfItems++;
|
||||
}
|
||||
|
||||
void DecreaseKey (Tuple node, ushort index) {
|
||||
// This is where 'obj' is in the binary heap logically speaking
|
||||
// (for performance reasons we don't actually store it there until
|
||||
// we know the final index, that's just a waste of CPU cycles)
|
||||
int bubbleIndex = index;
|
||||
// Update F value, it might have changed since the node was originally added to the heap
|
||||
uint nodeF = node.F = node.node.F;
|
||||
uint nodeG = node.node.G;
|
||||
|
||||
while (bubbleIndex != 0) {
|
||||
// Parent node of the bubble node
|
||||
int parentIndex = (bubbleIndex-1) / D;
|
||||
|
||||
if (nodeF < heap[parentIndex].F || (SortGScores && nodeF == heap[parentIndex].F && nodeG > heap[parentIndex].node.G)) {
|
||||
// Swap the bubble node and parent node
|
||||
// (we don't really need to store the bubble node until we know the final index though
|
||||
// so we do that after the loop instead)
|
||||
heap[bubbleIndex] = heap[parentIndex];
|
||||
#if DECREASE_KEY
|
||||
heap[bubbleIndex].node.heapIndex = (ushort)bubbleIndex;
|
||||
#endif
|
||||
bubbleIndex = parentIndex;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
heap[bubbleIndex] = node;
|
||||
#if DECREASE_KEY
|
||||
node.node.heapIndex = (ushort)bubbleIndex;
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>Returns the node with the lowest F score from the heap</summary>
|
||||
public PathNode Remove () {
|
||||
PathNode returnItem = heap[0].node;
|
||||
|
||||
#if DECREASE_KEY
|
||||
returnItem.heapIndex = NotInHeap;
|
||||
#endif
|
||||
|
||||
numberOfItems--;
|
||||
if (numberOfItems == 0) return returnItem;
|
||||
|
||||
// Last item in the heap array
|
||||
var swapItem = heap[numberOfItems];
|
||||
var swapItemG = swapItem.node.G;
|
||||
|
||||
int swapIndex = 0, parent;
|
||||
|
||||
// Trickle upwards
|
||||
while (true) {
|
||||
parent = swapIndex;
|
||||
uint swapF = swapItem.F;
|
||||
int pd = parent * D + 1;
|
||||
|
||||
// If this holds, then the indices used
|
||||
// below are guaranteed to not throw an index out of bounds
|
||||
// exception since we choose the size of the array in that way
|
||||
if (pd <= numberOfItems) {
|
||||
// Loading all F scores here instead of inside the if statements
|
||||
// reduces data dependencies and improves performance
|
||||
uint f0 = heap[pd+0].F;
|
||||
uint f1 = heap[pd+1].F;
|
||||
uint f2 = heap[pd+2].F;
|
||||
uint f3 = heap[pd+3].F;
|
||||
|
||||
// The common case is that all children of a node are present
|
||||
// so the first comparison in each if statement below
|
||||
// will be extremely well predicted so it is essentially free
|
||||
// (I tried optimizing for the common case, but it didn't affect performance at all
|
||||
// at the expense of longer code, the CPU branch predictor is really good)
|
||||
|
||||
if (pd+0 < numberOfItems && (f0 < swapF || (SortGScores && f0 == swapF && heap[pd+0].node.G < swapItemG))) {
|
||||
swapF = f0;
|
||||
swapIndex = pd+0;
|
||||
}
|
||||
|
||||
if (pd+1 < numberOfItems && (f1 < swapF || (SortGScores && f1 == swapF && heap[pd+1].node.G < (swapIndex == parent ? swapItemG : heap[swapIndex].node.G)))) {
|
||||
swapF = f1;
|
||||
swapIndex = pd+1;
|
||||
}
|
||||
|
||||
if (pd+2 < numberOfItems && (f2 < swapF || (SortGScores && f2 == swapF && heap[pd+2].node.G < (swapIndex == parent ? swapItemG : heap[swapIndex].node.G)))) {
|
||||
swapF = f2;
|
||||
swapIndex = pd+2;
|
||||
}
|
||||
|
||||
if (pd+3 < numberOfItems && (f3 < swapF || (SortGScores && f3 == swapF && heap[pd+3].node.G < (swapIndex == parent ? swapItemG : heap[swapIndex].node.G)))) {
|
||||
swapIndex = pd+3;
|
||||
}
|
||||
}
|
||||
|
||||
// One if the parent's children are smaller or equal, swap them
|
||||
// (actually we are just pretenting we swapped them, we hold the swapData
|
||||
// in local variable and only assign it once we know the final index)
|
||||
if (parent != swapIndex) {
|
||||
heap[parent] = heap[swapIndex];
|
||||
#if DECREASE_KEY
|
||||
heap[parent].node.heapIndex = (ushort)parent;
|
||||
#endif
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Assign element to the final position
|
||||
heap[swapIndex] = swapItem;
|
||||
#if DECREASE_KEY
|
||||
swapItem.node.heapIndex = (ushort)swapIndex;
|
||||
#endif
|
||||
|
||||
// For debugging
|
||||
// Validate ();
|
||||
|
||||
return returnItem;
|
||||
}
|
||||
|
||||
void Validate () {
|
||||
for (int i = 1; i < numberOfItems; i++) {
|
||||
int parentIndex = (i-1)/D;
|
||||
if (heap[parentIndex].F > heap[i].F) {
|
||||
throw new System.Exception("Invalid state at " + i + ":" + parentIndex + " ( " + heap[parentIndex].F + " > " + heap[i].F + " ) ");
|
||||
}
|
||||
#if DECREASE_KEY
|
||||
if (heap[i].node.heapIndex != i) {
|
||||
throw new System.Exception("Invalid heap index");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rebuilds the heap by trickeling down all items.
|
||||
/// Usually called after the hTarget on a path has been changed
|
||||
/// </summary>
|
||||
public void Rebuild () {
|
||||
#if ASTARDEBUG
|
||||
int changes = 0;
|
||||
#endif
|
||||
|
||||
for (int i = 2; i < numberOfItems; i++) {
|
||||
int bubbleIndex = i;
|
||||
var node = heap[i];
|
||||
uint nodeF = node.F;
|
||||
while (bubbleIndex != 1) {
|
||||
int parentIndex = bubbleIndex / D;
|
||||
|
||||
if (nodeF < heap[parentIndex].F) {
|
||||
heap[bubbleIndex] = heap[parentIndex];
|
||||
#if DECREASE_KEY
|
||||
heap[bubbleIndex].node.heapIndex = (ushort)bubbleIndex;
|
||||
#endif
|
||||
|
||||
heap[parentIndex] = node;
|
||||
#if DECREASE_KEY
|
||||
heap[parentIndex].node.heapIndex = (ushort)parentIndex;
|
||||
#endif
|
||||
|
||||
bubbleIndex = parentIndex;
|
||||
#if ASTARDEBUG
|
||||
changes++;
|
||||
#endif
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if ASTARDEBUG
|
||||
UnityEngine.Debug.Log("+++ Rebuilt Heap - "+changes+" changes +++");
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
7
AR/Assets/AstarPathfindingProject/Core/Misc/BinaryHeap.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/Misc/BinaryHeap.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: eb4299e8747f44ad2b4e086752108ea3
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
91
AR/Assets/AstarPathfindingProject/Core/Misc/Draw.cs
Normal file
91
AR/Assets/AstarPathfindingProject/Core/Misc/Draw.cs
Normal file
@ -0,0 +1,91 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace Pathfinding.Util {
|
||||
/// <summary>Helper methods for drawing gizmos and debug lines</summary>
|
||||
public class Draw {
|
||||
public static readonly Draw Debug = new Draw { gizmos = false };
|
||||
public static readonly Draw Gizmos = new Draw { gizmos = true };
|
||||
|
||||
bool gizmos;
|
||||
Matrix4x4 matrix = Matrix4x4.identity;
|
||||
|
||||
void SetColor (Color color) {
|
||||
if (gizmos && UnityEngine.Gizmos.color != color) UnityEngine.Gizmos.color = color;
|
||||
}
|
||||
|
||||
public void Polyline (System.Collections.Generic.List<Vector3> points, Color color, bool cycle = false) {
|
||||
for (int i = 0; i < points.Count - 1; i++) {
|
||||
Line(points[i], points[i+1], color);
|
||||
}
|
||||
if (cycle && points.Count > 1) Line(points[points.Count - 1], points[0], color);
|
||||
}
|
||||
|
||||
public void Line (Vector3 a, Vector3 b, Color color) {
|
||||
SetColor(color);
|
||||
if (gizmos) UnityEngine.Gizmos.DrawLine(matrix.MultiplyPoint3x4(a), matrix.MultiplyPoint3x4(b));
|
||||
else UnityEngine.Debug.DrawLine(matrix.MultiplyPoint3x4(a), matrix.MultiplyPoint3x4(b), color);
|
||||
}
|
||||
|
||||
public void CircleXZ (Vector3 center, float radius, Color color, float startAngle = 0f, float endAngle = 2*Mathf.PI) {
|
||||
int steps = 40;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
if (gizmos) steps = (int)Mathf.Clamp(Mathf.Sqrt(radius / UnityEditor.HandleUtility.GetHandleSize((UnityEngine.Gizmos.matrix * matrix).MultiplyPoint3x4(center))) * 25, 4, 40);
|
||||
#endif
|
||||
while (startAngle > endAngle) startAngle -= 2*Mathf.PI;
|
||||
|
||||
Vector3 prev = new Vector3(Mathf.Cos(startAngle)*radius, 0, Mathf.Sin(startAngle)*radius);
|
||||
for (int i = 0; i <= steps; i++) {
|
||||
Vector3 c = new Vector3(Mathf.Cos(Mathf.Lerp(startAngle, endAngle, i/(float)steps))*radius, 0, Mathf.Sin(Mathf.Lerp(startAngle, endAngle, i/(float)steps))*radius);
|
||||
Line(center + prev, center + c, color);
|
||||
prev = c;
|
||||
}
|
||||
}
|
||||
|
||||
public void Cylinder (Vector3 position, Vector3 up, float height, float radius, Color color) {
|
||||
var tangent = Vector3.Cross(up, Vector3.one).normalized;
|
||||
|
||||
matrix = Matrix4x4.TRS(position, Quaternion.LookRotation(tangent, up), new Vector3(radius, height, radius));
|
||||
CircleXZ(Vector3.zero, 1, color);
|
||||
|
||||
if (height > 0) {
|
||||
CircleXZ(Vector3.up, 1, color);
|
||||
Line(new Vector3(1, 0, 0), new Vector3(1, 1, 0), color);
|
||||
Line(new Vector3(-1, 0, 0), new Vector3(-1, 1, 0), color);
|
||||
Line(new Vector3(0, 0, 1), new Vector3(0, 1, 1), color);
|
||||
Line(new Vector3(0, 0, -1), new Vector3(0, 1, -1), color);
|
||||
}
|
||||
|
||||
matrix = Matrix4x4.identity;
|
||||
}
|
||||
|
||||
public void CrossXZ (Vector3 position, Color color, float size = 1) {
|
||||
size *= 0.5f;
|
||||
Line(position - Vector3.right*size, position + Vector3.right*size, color);
|
||||
Line(position - Vector3.forward*size, position + Vector3.forward*size, color);
|
||||
}
|
||||
|
||||
public void Bezier (Vector3 a, Vector3 b, Color color) {
|
||||
Vector3 dir = b - a;
|
||||
|
||||
if (dir == Vector3.zero) return;
|
||||
|
||||
Vector3 normal = Vector3.Cross(Vector3.up, dir);
|
||||
Vector3 normalUp = Vector3.Cross(dir, normal);
|
||||
|
||||
normalUp = normalUp.normalized;
|
||||
normalUp *= dir.magnitude*0.1f;
|
||||
|
||||
Vector3 p1c = a + normalUp;
|
||||
Vector3 p2c = b + normalUp;
|
||||
|
||||
Vector3 prev = a;
|
||||
for (int i = 1; i <= 20; i++) {
|
||||
float t = i/20.0f;
|
||||
Vector3 p = AstarSplines.CubicBezier(a, p1c, p2c, b, t);
|
||||
Line(prev, p, color);
|
||||
prev = p;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/Misc/Draw.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/Misc/Draw.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 506739df886ce4ebb9b14b16d86b5e13
|
||||
timeCreated: 1492346087
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@ -0,0 +1,105 @@
|
||||
namespace Pathfinding {
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
|
||||
/// <summary>Internal utility class for looking up editor resources</summary>
|
||||
public static class EditorResourceHelper {
|
||||
/// <summary>
|
||||
/// Path to the editor assets folder for the A* Pathfinding Project. If this path turns out to be incorrect, the script will try to find the correct path
|
||||
/// See: LoadStyles
|
||||
/// </summary>
|
||||
public static string editorAssets;
|
||||
|
||||
static EditorResourceHelper () {
|
||||
// Look up editor assets directory when first accessed
|
||||
LocateEditorAssets();
|
||||
}
|
||||
|
||||
static Material surfaceMat, lineMat;
|
||||
static Texture2D handlesAALineTex;
|
||||
public static Material GizmoSurfaceMaterial {
|
||||
get {
|
||||
if (!surfaceMat) surfaceMat = UnityEditor.AssetDatabase.LoadAssetAtPath(EditorResourceHelper.editorAssets + "/Materials/Navmesh.mat", typeof(Material)) as Material;
|
||||
return surfaceMat;
|
||||
}
|
||||
}
|
||||
|
||||
public static Material GizmoLineMaterial {
|
||||
get {
|
||||
if (!lineMat) lineMat = UnityEditor.AssetDatabase.LoadAssetAtPath(EditorResourceHelper.editorAssets + "/Materials/NavmeshOutline.mat", typeof(Material)) as Material;
|
||||
return lineMat;
|
||||
}
|
||||
}
|
||||
|
||||
public static Texture2D HandlesAALineTexture {
|
||||
get {
|
||||
if (!handlesAALineTex) handlesAALineTex = Resources.Load<Texture2D>("handles_aaline");
|
||||
return handlesAALineTex;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Locates the editor assets folder in case the user has moved it</summary>
|
||||
public static bool LocateEditorAssets () {
|
||||
#if UNITY_2019_3_OR_NEWER
|
||||
var package = UnityEditor.PackageManager.PackageInfo.FindForAssembly(typeof(EditorResourceHelper).Assembly);
|
||||
if (package != null) {
|
||||
editorAssets = package.assetPath + "/Editor/EditorAssets";
|
||||
if (System.IO.File.Exists(package.resolvedPath + "/Editor/EditorAssets/AstarEditorSkinLight.guiskin")) {
|
||||
return true;
|
||||
} else {
|
||||
Debug.LogError("Could not find editor assets folder in package at " + editorAssets + ". Is the package corrupt?");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
string projectPath = Application.dataPath;
|
||||
|
||||
if (projectPath.EndsWith("/Assets")) {
|
||||
projectPath = projectPath.Remove(projectPath.Length-("Assets".Length));
|
||||
}
|
||||
|
||||
editorAssets = "Assets/AstarPathfindingProject/Editor/EditorAssets";
|
||||
if (!System.IO.File.Exists(projectPath + editorAssets + "/AstarEditorSkinLight.guiskin") && !System.IO.File.Exists(projectPath + editorAssets + "/AstarEditorSkin.guiskin")) {
|
||||
//Initiate search
|
||||
|
||||
var sdir = new System.IO.DirectoryInfo(Application.dataPath);
|
||||
|
||||
var dirQueue = new Queue<System.IO.DirectoryInfo>();
|
||||
dirQueue.Enqueue(sdir);
|
||||
|
||||
bool found = false;
|
||||
while (dirQueue.Count > 0) {
|
||||
System.IO.DirectoryInfo dir = dirQueue.Dequeue();
|
||||
if (System.IO.File.Exists(dir.FullName + "/AstarEditorSkinLight.guiskin") || System.IO.File.Exists(dir.FullName + "/AstarEditorSkin.guiskin")) {
|
||||
// Handle windows file paths
|
||||
string path = dir.FullName.Replace('\\', '/');
|
||||
found = true;
|
||||
// Remove data path from string to make it relative
|
||||
path = path.Replace(projectPath, "");
|
||||
|
||||
if (path.StartsWith("/")) {
|
||||
path = path.Remove(0, 1);
|
||||
}
|
||||
|
||||
editorAssets = path;
|
||||
return true;
|
||||
}
|
||||
var dirs = dir.GetDirectories();
|
||||
for (int i = 0; i < dirs.Length; i++) {
|
||||
dirQueue.Enqueue(dirs[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
Debug.LogWarning("Could not locate editor assets folder. Make sure you have imported the package correctly.\nA* Pathfinding Project");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/Misc/EditorResourceHelper.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/Misc/EditorResourceHelper.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8127bc49e9e2d42dfa7a4e057842f165
|
||||
timeCreated: 1480419306
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@ -0,0 +1,10 @@
|
||||
using Pathfinding.Serialization;
|
||||
|
||||
namespace Pathfinding {
|
||||
[JsonOptIn]
|
||||
/// <summary>Defined here only so non-editor classes can use the <see cref="target"/> field</summary>
|
||||
public class GraphEditorBase {
|
||||
/// <summary>NavGraph this editor is exposing</summary>
|
||||
public NavGraph target;
|
||||
}
|
||||
}
|
7
AR/Assets/AstarPathfindingProject/Core/Misc/GraphEditorBase.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/Misc/GraphEditorBase.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 704136724bc95455ebe477f42f5c5a84
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
204
AR/Assets/AstarPathfindingProject/Core/Misc/GraphModifier.cs
Normal file
204
AR/Assets/AstarPathfindingProject/Core/Misc/GraphModifier.cs
Normal file
@ -0,0 +1,204 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding {
|
||||
/// <summary>
|
||||
/// GraphModifier is used for modifying graphs or processing graph data based on events.
|
||||
/// This class is a simple container for a number of events.
|
||||
///
|
||||
/// Warning: Some events will be called both in play mode <b>and in editor mode</b> (at least the scan events).
|
||||
/// So make sure your code handles both cases well. You may choose to ignore editor events.
|
||||
/// See: Application.IsPlaying
|
||||
/// </summary>
|
||||
[ExecuteInEditMode]
|
||||
public abstract class GraphModifier : VersionedMonoBehaviour {
|
||||
/// <summary>All active graph modifiers</summary>
|
||||
private static GraphModifier root;
|
||||
|
||||
private GraphModifier prev;
|
||||
private GraphModifier next;
|
||||
|
||||
/// <summary>Unique persistent ID for this component, used for serialization</summary>
|
||||
[SerializeField]
|
||||
[HideInInspector]
|
||||
protected ulong uniqueID;
|
||||
|
||||
/// <summary>Maps persistent IDs to the component that uses it</summary>
|
||||
protected static Dictionary<ulong, GraphModifier> usedIDs = new Dictionary<ulong, GraphModifier>();
|
||||
|
||||
protected static List<T> GetModifiersOfType<T>() where T : GraphModifier {
|
||||
var current = root;
|
||||
var result = new List<T>();
|
||||
|
||||
while (current != null) {
|
||||
var cast = current as T;
|
||||
if (cast != null) result.Add(cast);
|
||||
current = current.next;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void FindAllModifiers () {
|
||||
var allModifiers = FindObjectsOfType(typeof(GraphModifier)) as GraphModifier[];
|
||||
|
||||
for (int i = 0; i < allModifiers.Length; i++) {
|
||||
if (allModifiers[i].enabled) allModifiers[i].OnEnable();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>GraphModifier event type</summary>
|
||||
public enum EventType {
|
||||
PostScan = 1 << 0,
|
||||
PreScan = 1 << 1,
|
||||
LatePostScan = 1 << 2,
|
||||
PreUpdate = 1 << 3,
|
||||
PostUpdate = 1 << 4,
|
||||
PostCacheLoad = 1 << 5
|
||||
}
|
||||
|
||||
/// <summary>Triggers an event for all active graph modifiers</summary>
|
||||
public static void TriggerEvent (GraphModifier.EventType type) {
|
||||
if (!Application.isPlaying) {
|
||||
FindAllModifiers();
|
||||
}
|
||||
|
||||
GraphModifier c = root;
|
||||
switch (type) {
|
||||
case EventType.PreScan:
|
||||
while (c != null) { c.OnPreScan(); c = c.next; }
|
||||
break;
|
||||
case EventType.PostScan:
|
||||
while (c != null) { c.OnPostScan(); c = c.next; }
|
||||
break;
|
||||
case EventType.LatePostScan:
|
||||
while (c != null) { c.OnLatePostScan(); c = c.next; }
|
||||
break;
|
||||
case EventType.PreUpdate:
|
||||
while (c != null) { c.OnGraphsPreUpdate(); c = c.next; }
|
||||
break;
|
||||
case EventType.PostUpdate:
|
||||
while (c != null) { c.OnGraphsPostUpdate(); c = c.next; }
|
||||
break;
|
||||
case EventType.PostCacheLoad:
|
||||
while (c != null) { c.OnPostCacheLoad(); c = c.next; }
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Adds this modifier to list of active modifiers</summary>
|
||||
protected virtual void OnEnable () {
|
||||
RemoveFromLinkedList();
|
||||
AddToLinkedList();
|
||||
ConfigureUniqueID();
|
||||
}
|
||||
|
||||
/// <summary>Removes this modifier from list of active modifiers</summary>
|
||||
protected virtual void OnDisable () {
|
||||
RemoveFromLinkedList();
|
||||
}
|
||||
|
||||
protected override void Awake () {
|
||||
base.Awake();
|
||||
ConfigureUniqueID();
|
||||
}
|
||||
|
||||
void ConfigureUniqueID () {
|
||||
// Check if any other object is using the same uniqueID
|
||||
// In that case this object may have been duplicated
|
||||
GraphModifier usedBy;
|
||||
|
||||
if (usedIDs.TryGetValue(uniqueID, out usedBy) && usedBy != this) {
|
||||
Reset();
|
||||
}
|
||||
|
||||
usedIDs[uniqueID] = this;
|
||||
}
|
||||
|
||||
void AddToLinkedList () {
|
||||
if (root == null) {
|
||||
root = this;
|
||||
} else {
|
||||
next = root;
|
||||
root.prev = this;
|
||||
root = this;
|
||||
}
|
||||
}
|
||||
|
||||
void RemoveFromLinkedList () {
|
||||
if (root == this) {
|
||||
root = next;
|
||||
if (root != null) root.prev = null;
|
||||
} else {
|
||||
if (prev != null) prev.next = next;
|
||||
if (next != null) next.prev = prev;
|
||||
}
|
||||
prev = null;
|
||||
next = null;
|
||||
}
|
||||
|
||||
protected virtual void OnDestroy () {
|
||||
usedIDs.Remove(uniqueID);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called right after all graphs have been scanned.
|
||||
/// FloodFill and other post processing has not been done.
|
||||
///
|
||||
/// Warning: Since OnEnable and Awake are called roughly in the same time, the only way
|
||||
/// to ensure that these scripts get this call when scanning in Awake is to
|
||||
/// set the Script Execution Order for AstarPath to some time later than default time
|
||||
/// (see Edit -> Project Settings -> Script Execution Order).
|
||||
/// TODO: Is this still relevant? A call to FindAllModifiers should have before this method is called
|
||||
/// so the above warning is probably not relevant anymore.
|
||||
///
|
||||
/// See: OnLatePostScan
|
||||
/// </summary>
|
||||
public virtual void OnPostScan () {}
|
||||
|
||||
/// <summary>
|
||||
/// Called right before graphs are going to be scanned.
|
||||
///
|
||||
/// Warning: Since OnEnable and Awake are called roughly in the same time, the only way
|
||||
/// to ensure that these scripts get this call when scanning in Awake is to
|
||||
/// set the Script Execution Order for AstarPath to some time later than default time
|
||||
/// (see Edit -> Project Settings -> Script Execution Order).
|
||||
/// TODO: Is this still relevant? A call to FindAllModifiers should have before this method is called
|
||||
/// so the above warning is probably not relevant anymore.
|
||||
///
|
||||
/// See: OnLatePostScan
|
||||
/// </summary>
|
||||
public virtual void OnPreScan () {}
|
||||
|
||||
/// <summary>
|
||||
/// Called at the end of the scanning procedure.
|
||||
/// This is the absolute last thing done by Scan.
|
||||
/// </summary>
|
||||
public virtual void OnLatePostScan () {}
|
||||
|
||||
/// <summary>
|
||||
/// Called after cached graphs have been loaded.
|
||||
/// When using cached startup, this event is analogous to OnLatePostScan and implementing scripts
|
||||
/// should do roughly the same thing for both events.
|
||||
/// </summary>
|
||||
public virtual void OnPostCacheLoad () {}
|
||||
|
||||
/// <summary>Called before graphs are updated using GraphUpdateObjects</summary>
|
||||
public virtual void OnGraphsPreUpdate () {}
|
||||
|
||||
/// <summary>
|
||||
/// Called after graphs have been updated using GraphUpdateObjects.
|
||||
/// Eventual flood filling has been done
|
||||
/// </summary>
|
||||
public virtual void OnGraphsPostUpdate () {}
|
||||
|
||||
protected override void Reset () {
|
||||
base.Reset();
|
||||
// Create a new random 64 bit value (62 bit actually because we skip negative numbers, but that's still enough by a huge margin)
|
||||
var rnd1 = (ulong)Random.Range(0, int.MaxValue);
|
||||
var rnd2 = ((ulong)Random.Range(0, int.MaxValue) << 32);
|
||||
|
||||
uniqueID = rnd1 | rnd2;
|
||||
usedIDs[uniqueID] = this;
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/Misc/GraphModifier.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/Misc/GraphModifier.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 39897fb482672480a817862c3909a4aa
|
||||
timeCreated: 1490044676
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: -222
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@ -0,0 +1,369 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using UnityEngine;
|
||||
#if UNITY_5_5_OR_NEWER
|
||||
using UnityEngine.Profiling;
|
||||
#endif
|
||||
|
||||
namespace Pathfinding {
|
||||
using UnityEngine.Assertions;
|
||||
|
||||
#if NETFX_CORE
|
||||
using Thread = Pathfinding.WindowsStore.Thread;
|
||||
#else
|
||||
using Thread = System.Threading.Thread;
|
||||
#endif
|
||||
|
||||
class GraphUpdateProcessor {
|
||||
public event System.Action OnGraphsUpdated;
|
||||
|
||||
/// <summary>Holds graphs that can be updated</summary>
|
||||
readonly AstarPath astar;
|
||||
|
||||
#if !UNITY_WEBGL
|
||||
/// <summary>
|
||||
/// Reference to the thread which handles async graph updates.
|
||||
/// See: ProcessGraphUpdatesAsync
|
||||
/// </summary>
|
||||
Thread graphUpdateThread;
|
||||
#endif
|
||||
|
||||
/// <summary>Used for IsAnyGraphUpdateInProgress</summary>
|
||||
bool anyGraphUpdateInProgress;
|
||||
|
||||
#if UNITY_2017_3_OR_NEWER && !UNITY_WEBGL
|
||||
CustomSampler asyncUpdateProfilingSampler;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Queue containing all waiting graph update queries. Add to this queue by using \link AddToQueue \endlink.
|
||||
/// See: AddToQueue
|
||||
/// </summary>
|
||||
readonly Queue<GraphUpdateObject> graphUpdateQueue = new Queue<GraphUpdateObject>();
|
||||
|
||||
/// <summary>Queue of all async graph updates waiting to be executed</summary>
|
||||
readonly Queue<GUOSingle> graphUpdateQueueAsync = new Queue<GUOSingle>();
|
||||
|
||||
/// <summary>Queue of all non-async graph update post events waiting to be executed</summary>
|
||||
readonly Queue<GUOSingle> graphUpdateQueuePost = new Queue<GUOSingle>();
|
||||
|
||||
/// <summary>Queue of all non-async graph updates waiting to be executed</summary>
|
||||
readonly Queue<GUOSingle> graphUpdateQueueRegular = new Queue<GUOSingle>();
|
||||
|
||||
readonly System.Threading.ManualResetEvent asyncGraphUpdatesComplete = new System.Threading.ManualResetEvent(true);
|
||||
|
||||
#if !UNITY_WEBGL
|
||||
readonly System.Threading.AutoResetEvent graphUpdateAsyncEvent = new System.Threading.AutoResetEvent(false);
|
||||
readonly System.Threading.AutoResetEvent exitAsyncThread = new System.Threading.AutoResetEvent(false);
|
||||
#endif
|
||||
|
||||
/// <summary>Returns if any graph updates are waiting to be applied</summary>
|
||||
public bool IsAnyGraphUpdateQueued { get { return graphUpdateQueue.Count > 0; } }
|
||||
|
||||
/// <summary>Returns if any graph updates are in progress</summary>
|
||||
public bool IsAnyGraphUpdateInProgress { get { return anyGraphUpdateInProgress; } }
|
||||
|
||||
/// <summary>Order type for updating graphs</summary>
|
||||
enum GraphUpdateOrder {
|
||||
GraphUpdate,
|
||||
// FloodFill
|
||||
}
|
||||
|
||||
/// <summary>Holds a single update that needs to be performed on a graph</summary>
|
||||
struct GUOSingle {
|
||||
public GraphUpdateOrder order;
|
||||
public IUpdatableGraph graph;
|
||||
public GraphUpdateObject obj;
|
||||
}
|
||||
|
||||
public GraphUpdateProcessor (AstarPath astar) {
|
||||
this.astar = astar;
|
||||
}
|
||||
|
||||
/// <summary>Work item which can be used to apply all queued updates</summary>
|
||||
public AstarWorkItem GetWorkItem () {
|
||||
return new AstarWorkItem(QueueGraphUpdatesInternal, ProcessGraphUpdates);
|
||||
}
|
||||
|
||||
public void EnableMultithreading () {
|
||||
#if !UNITY_WEBGL
|
||||
if (graphUpdateThread == null || !graphUpdateThread.IsAlive) {
|
||||
#if UNITY_2017_3_OR_NEWER && !UNITY_WEBGL
|
||||
asyncUpdateProfilingSampler = CustomSampler.Create("Graph Update");
|
||||
#endif
|
||||
|
||||
graphUpdateThread = new Thread(ProcessGraphUpdatesAsync);
|
||||
graphUpdateThread.IsBackground = true;
|
||||
|
||||
// Set the thread priority for graph updates
|
||||
// Unless compiling for windows store or windows phone which does not support it
|
||||
#if !UNITY_WINRT
|
||||
graphUpdateThread.Priority = System.Threading.ThreadPriority.Lowest;
|
||||
#endif
|
||||
graphUpdateThread.Start();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
public void DisableMultithreading () {
|
||||
#if !UNITY_WEBGL
|
||||
if (graphUpdateThread != null && graphUpdateThread.IsAlive) {
|
||||
// Resume graph update thread, will cause it to terminate
|
||||
exitAsyncThread.Set();
|
||||
|
||||
if (!graphUpdateThread.Join(5*1000)) {
|
||||
Debug.LogError("Graph update thread did not exit in 5 seconds");
|
||||
}
|
||||
|
||||
graphUpdateThread = null;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Update all graphs using the GraphUpdateObject.
|
||||
/// This can be used to, e.g make all nodes in an area unwalkable, or set them to a higher penalty.
|
||||
/// The graphs will be updated as soon as possible (with respect to AstarPath.batchGraphUpdates)
|
||||
///
|
||||
/// See: FlushGraphUpdates
|
||||
/// </summary>
|
||||
public void AddToQueue (GraphUpdateObject ob) {
|
||||
// Put the GUO in the queue
|
||||
graphUpdateQueue.Enqueue(ob);
|
||||
}
|
||||
|
||||
/// <summary>Schedules graph updates internally</summary>
|
||||
void QueueGraphUpdatesInternal () {
|
||||
while (graphUpdateQueue.Count > 0) {
|
||||
GraphUpdateObject ob = graphUpdateQueue.Dequeue();
|
||||
if (ob.internalStage != GraphUpdateObject.STAGE_PENDING) {
|
||||
Debug.LogError("Expected remaining graph updates to be pending");
|
||||
continue;
|
||||
}
|
||||
ob.internalStage = 0;
|
||||
|
||||
foreach (IUpdatableGraph g in astar.data.GetUpdateableGraphs()) {
|
||||
NavGraph gr = g as NavGraph;
|
||||
if (ob.nnConstraint == null || ob.nnConstraint.SuitableGraph(astar.data.GetGraphIndex(gr), gr)) {
|
||||
var guo = new GUOSingle();
|
||||
guo.order = GraphUpdateOrder.GraphUpdate;
|
||||
guo.obj = ob;
|
||||
guo.graph = g;
|
||||
ob.internalStage += 1;
|
||||
graphUpdateQueueRegular.Enqueue(guo);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
GraphModifier.TriggerEvent(GraphModifier.EventType.PreUpdate);
|
||||
anyGraphUpdateInProgress = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates graphs.
|
||||
/// Will do some graph updates, possibly signal another thread to do them.
|
||||
/// Will only process graph updates added by QueueGraphUpdatesInternal
|
||||
///
|
||||
/// Returns: True if all graph updates have been done and pathfinding (or other tasks) may resume.
|
||||
/// False if there are still graph updates being processed or waiting in the queue.
|
||||
/// </summary>
|
||||
/// <param name="force">If true, all graph updates will be processed before this function returns. The return value
|
||||
/// will be True.</param>
|
||||
bool ProcessGraphUpdates (bool force) {
|
||||
Assert.IsTrue(anyGraphUpdateInProgress);
|
||||
|
||||
if (force) {
|
||||
asyncGraphUpdatesComplete.WaitOne();
|
||||
} else {
|
||||
#if !UNITY_WEBGL
|
||||
if (!asyncGraphUpdatesComplete.WaitOne(0)) {
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
Assert.AreEqual(graphUpdateQueueAsync.Count, 0, "Queue should be empty at this stage");
|
||||
|
||||
ProcessPostUpdates();
|
||||
if (!ProcessRegularUpdates(force)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GraphModifier.TriggerEvent(GraphModifier.EventType.PostUpdate);
|
||||
if (OnGraphsUpdated != null) OnGraphsUpdated();
|
||||
|
||||
Assert.AreEqual(graphUpdateQueueRegular.Count, 0, "QueueRegular should be empty at this stage");
|
||||
Assert.AreEqual(graphUpdateQueueAsync.Count, 0, "QueueAsync should be empty at this stage");
|
||||
Assert.AreEqual(graphUpdateQueuePost.Count, 0, "QueuePost should be empty at this stage");
|
||||
|
||||
anyGraphUpdateInProgress = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ProcessRegularUpdates (bool force) {
|
||||
while (graphUpdateQueueRegular.Count > 0) {
|
||||
GUOSingle s = graphUpdateQueueRegular.Peek();
|
||||
|
||||
GraphUpdateThreading threading = s.graph.CanUpdateAsync(s.obj);
|
||||
|
||||
#if UNITY_WEBGL
|
||||
// Never use multithreading in WebGL
|
||||
threading &= ~GraphUpdateThreading.SeparateThread;
|
||||
#else
|
||||
// When not playing or when not using a graph update thread (or if it has crashed), everything runs in the Unity thread
|
||||
if (force || !Application.isPlaying || graphUpdateThread == null || !graphUpdateThread.IsAlive) {
|
||||
// Remove the SeparateThread flag
|
||||
threading &= ~GraphUpdateThreading.SeparateThread;
|
||||
}
|
||||
#endif
|
||||
|
||||
if ((threading & GraphUpdateThreading.UnityInit) != 0) {
|
||||
// Process async graph updates first.
|
||||
// Next call to this function will process this object so it is not dequeued now
|
||||
if (StartAsyncUpdatesIfQueued()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
s.graph.UpdateAreaInit(s.obj);
|
||||
}
|
||||
|
||||
if ((threading & GraphUpdateThreading.SeparateThread) != 0) {
|
||||
// Move GUO to async queue to be updated by another thread
|
||||
graphUpdateQueueRegular.Dequeue();
|
||||
graphUpdateQueueAsync.Enqueue(s);
|
||||
|
||||
// Don't start any more async graph updates because this update
|
||||
// requires a Unity thread function to run after it has been completed
|
||||
// but before the next update is started
|
||||
if ((threading & GraphUpdateThreading.UnityPost) != 0) {
|
||||
if (StartAsyncUpdatesIfQueued()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Unity Thread
|
||||
|
||||
if (StartAsyncUpdatesIfQueued()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
graphUpdateQueueRegular.Dequeue();
|
||||
|
||||
try {
|
||||
s.graph.UpdateArea(s.obj);
|
||||
} catch (System.Exception e) {
|
||||
Debug.LogError("Error while updating graphs\n"+e);
|
||||
}
|
||||
|
||||
if ((threading & GraphUpdateThreading.UnityPost) != 0) {
|
||||
s.graph.UpdateAreaPost(s.obj);
|
||||
}
|
||||
|
||||
s.obj.internalStage -= 1;
|
||||
UnityEngine.Assertions.Assert.IsTrue(s.obj.internalStage >= 0);
|
||||
}
|
||||
}
|
||||
|
||||
if (StartAsyncUpdatesIfQueued()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Signal the graph update thread to start processing graph updates if there are any in the <see cref="graphUpdateQueueAsync"/> queue.
|
||||
/// Returns: True if the other thread was signaled.
|
||||
/// </summary>
|
||||
bool StartAsyncUpdatesIfQueued () {
|
||||
if (graphUpdateQueueAsync.Count > 0) {
|
||||
#if UNITY_WEBGL
|
||||
throw new System.Exception("This should not happen in WebGL");
|
||||
#else
|
||||
asyncGraphUpdatesComplete.Reset();
|
||||
graphUpdateAsyncEvent.Set();
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void ProcessPostUpdates () {
|
||||
while (graphUpdateQueuePost.Count > 0) {
|
||||
GUOSingle s = graphUpdateQueuePost.Dequeue();
|
||||
|
||||
GraphUpdateThreading threading = s.graph.CanUpdateAsync(s.obj);
|
||||
|
||||
if ((threading & GraphUpdateThreading.UnityPost) != 0) {
|
||||
try {
|
||||
s.graph.UpdateAreaPost(s.obj);
|
||||
} catch (System.Exception e) {
|
||||
Debug.LogError("Error while updating graphs (post step)\n"+e);
|
||||
}
|
||||
}
|
||||
|
||||
s.obj.internalStage -= 1;
|
||||
UnityEngine.Assertions.Assert.IsTrue(s.obj.internalStage >= 0);
|
||||
}
|
||||
}
|
||||
|
||||
#if !UNITY_WEBGL
|
||||
/// <summary>
|
||||
/// Graph update thread.
|
||||
/// Async graph updates will be executed by this method in another thread.
|
||||
/// </summary>
|
||||
void ProcessGraphUpdatesAsync () {
|
||||
#if UNITY_2017_3_OR_NEWER
|
||||
Profiler.BeginThreadProfiling("Pathfinding", "Threaded Graph Updates");
|
||||
#endif
|
||||
|
||||
var handles = new [] { graphUpdateAsyncEvent, exitAsyncThread };
|
||||
|
||||
while (true) {
|
||||
// Wait for the next batch or exit event
|
||||
var handleIndex = WaitHandle.WaitAny(handles);
|
||||
|
||||
if (handleIndex == 1) {
|
||||
// Exit even was fired
|
||||
// Abort thread and clear queue
|
||||
while (graphUpdateQueueAsync.Count > 0) {
|
||||
var s = graphUpdateQueueAsync.Dequeue();
|
||||
s.obj.internalStage = GraphUpdateObject.STAGE_ABORTED;
|
||||
}
|
||||
asyncGraphUpdatesComplete.Set();
|
||||
#if UNITY_2017_3_OR_NEWER
|
||||
Profiler.EndThreadProfiling();
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
|
||||
while (graphUpdateQueueAsync.Count > 0) {
|
||||
#if UNITY_2017_3_OR_NEWER
|
||||
asyncUpdateProfilingSampler.Begin();
|
||||
#endif
|
||||
// Note that no locking is required here because the main thread
|
||||
// cannot access it until asyncGraphUpdatesComplete is signaled
|
||||
GUOSingle aguo = graphUpdateQueueAsync.Dequeue();
|
||||
|
||||
try {
|
||||
if (aguo.order == GraphUpdateOrder.GraphUpdate) {
|
||||
aguo.graph.UpdateArea(aguo.obj);
|
||||
graphUpdateQueuePost.Enqueue(aguo);
|
||||
} else {
|
||||
throw new System.NotSupportedException("" + aguo.order);
|
||||
}
|
||||
} catch (System.Exception e) {
|
||||
Debug.LogError("Exception while updating graphs:\n"+e);
|
||||
}
|
||||
#if UNITY_2017_3_OR_NEWER
|
||||
asyncUpdateProfilingSampler.End();
|
||||
#endif
|
||||
}
|
||||
|
||||
// Done
|
||||
asyncGraphUpdatesComplete.Set();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/Misc/GraphUpdateProcessor.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/Misc/GraphUpdateProcessor.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b1798d8e7c7d54972ae8522558cbd27c
|
||||
timeCreated: 1443114816
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
270
AR/Assets/AstarPathfindingProject/Core/Misc/GraphUtilities.cs
Normal file
270
AR/Assets/AstarPathfindingProject/Core/Misc/GraphUtilities.cs
Normal file
@ -0,0 +1,270 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding {
|
||||
using Pathfinding.Util;
|
||||
|
||||
/// <summary>
|
||||
/// Contains utility methods for getting useful information out of graph.
|
||||
/// This class works a lot with the <see cref="Pathfinding.GraphNode"/> class, a useful function to get nodes is <see cref="AstarPath.GetNearest"/>.
|
||||
///
|
||||
/// See: <see cref="AstarPath.GetNearest"/>
|
||||
/// See: <see cref="Pathfinding.GraphUpdateUtilities"/>
|
||||
/// See: <see cref="Pathfinding.PathUtilities"/>
|
||||
///
|
||||
/// \ingroup utils
|
||||
/// </summary>
|
||||
public static class GraphUtilities {
|
||||
/// <summary>
|
||||
/// Convenience method to get a list of all segments of the contours of a graph.
|
||||
/// Returns: A list of segments. Every 2 elements form a line segment. The first segment is (result[0], result[1]), the second one is (result[2], result[3]) etc.
|
||||
/// The line segments are oriented so that the navmesh is on the right side of the segments when seen from above.
|
||||
///
|
||||
/// This method works for navmesh, recast, grid graphs and layered grid graphs. For other graph types it will return an empty list.
|
||||
///
|
||||
/// If you need more information about how the contours are connected you can take a look at the other variants of this method.
|
||||
///
|
||||
/// <code>
|
||||
/// // Get the first graph
|
||||
/// var navmesh = AstarPath.active.graphs[0];
|
||||
///
|
||||
/// // Get all contours of the graph (works for grid, navmesh and recast graphs)
|
||||
/// var segments = GraphUtilities.GetContours(navmesh);
|
||||
///
|
||||
/// // Every 2 elements form a line segment. The first segment is (segments[0], segments[1]), the second one is (segments[2], segments[3]) etc.
|
||||
/// // The line segments are oriented so that the navmesh is on the right side of the segments when seen from above.
|
||||
/// for (int i = 0; i < segments.Count; i += 2) {
|
||||
/// var start = segments[i];
|
||||
/// var end = segments[i+1];
|
||||
/// Debug.DrawLine(start, end, Color.red, 3);
|
||||
/// }
|
||||
/// </code>
|
||||
///
|
||||
/// [Open online documentation to see images]
|
||||
/// [Open online documentation to see images]
|
||||
/// </summary>
|
||||
public static List<Vector3> GetContours (NavGraph graph) {
|
||||
List<Vector3> result = ListPool<Vector3>.Claim();
|
||||
|
||||
if (graph is INavmesh) {
|
||||
GetContours(graph as INavmesh, (vertices, cycle) => {
|
||||
for (int j = cycle ? vertices.Count - 1 : 0, i = 0; i < vertices.Count; j = i, i++) {
|
||||
result.Add((Vector3)vertices[j]);
|
||||
result.Add((Vector3)vertices[i]);
|
||||
}
|
||||
});
|
||||
#if !ASTAR_NO_GRID_GRAPH
|
||||
} else if (graph is GridGraph) {
|
||||
GetContours(graph as GridGraph, vertices => {
|
||||
for (int j = vertices.Length - 1, i = 0; i < vertices.Length; j = i, i++) {
|
||||
result.Add((Vector3)vertices[j]);
|
||||
result.Add((Vector3)vertices[i]);
|
||||
}
|
||||
}, 0);
|
||||
#endif
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Traces the contour of a navmesh.
|
||||
///
|
||||
/// [Open online documentation to see images]
|
||||
///
|
||||
/// This image is just used to illustrate the difference between chains and cycles. That it shows a grid graph is not relevant.
|
||||
/// [Open online documentation to see images]
|
||||
///
|
||||
/// See: <see cref="GetContours(NavGraph)"/>
|
||||
/// </summary>
|
||||
/// <param name="navmesh">The navmesh-like object to trace. This can be a recast or navmesh graph or it could be a single tile in one such graph.</param>
|
||||
/// <param name="results">Will be called once for each contour with the contour as a parameter as well as a boolean indicating if the contour is a cycle or a chain (see second image).</param>
|
||||
public static void GetContours (INavmesh navmesh, System.Action<List<Int3>, bool> results) {
|
||||
// Assume 3 vertices per node
|
||||
var uses = new bool[3];
|
||||
|
||||
var outline = new Dictionary<int, int>();
|
||||
var vertexPositions = new Dictionary<int, Int3>();
|
||||
var hasInEdge = new HashSet<int>();
|
||||
|
||||
navmesh.GetNodes(_node => {
|
||||
var node = _node as TriangleMeshNode;
|
||||
|
||||
uses[0] = uses[1] = uses[2] = false;
|
||||
|
||||
if (node != null) {
|
||||
// Find out which edges are shared with other nodes
|
||||
for (int j = 0; j < node.connections.Length; j++) {
|
||||
var other = node.connections[j].node as TriangleMeshNode;
|
||||
|
||||
// Not necessarily a TriangleMeshNode
|
||||
if (other != null) {
|
||||
int a = node.SharedEdge(other);
|
||||
if (a != -1) uses[a] = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Loop through all edges on the node
|
||||
for (int j = 0; j < 3; j++) {
|
||||
// The edge is not shared with any other node
|
||||
// I.e it is an exterior edge on the mesh
|
||||
if (!uses[j]) {
|
||||
var i1 = j;
|
||||
var i2 = (j+1) % node.GetVertexCount();
|
||||
|
||||
outline[node.GetVertexIndex(i1)] = node.GetVertexIndex(i2);
|
||||
hasInEdge.Add(node.GetVertexIndex(i2));
|
||||
vertexPositions[node.GetVertexIndex(i1)] = node.GetVertex(i1);
|
||||
vertexPositions[node.GetVertexIndex(i2)] = node.GetVertex(i2);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Polygon.TraceContours(outline, hasInEdge, (chain, cycle) => {
|
||||
List<Int3> vertices = ListPool<Int3>.Claim();
|
||||
for (int i = 0; i < chain.Count; i++) vertices.Add(vertexPositions[chain[i]]);
|
||||
results(vertices, cycle);
|
||||
});
|
||||
}
|
||||
|
||||
#if !ASTAR_NO_GRID_GRAPH
|
||||
/// <summary>
|
||||
/// Finds all contours of a collection of nodes in a grid graph.
|
||||
///
|
||||
/// <code>
|
||||
/// var grid = AstarPath.active.data.gridGraph;
|
||||
///
|
||||
/// // Find all contours in the graph and draw them using debug lines
|
||||
/// GraphUtilities.GetContours(grid, vertices => {
|
||||
/// for (int i = 0; i < vertices.Length; i++) {
|
||||
/// Debug.DrawLine(vertices[i], vertices[(i+1)%vertices.Length], Color.red, 4);
|
||||
/// }
|
||||
/// }, 0);
|
||||
/// </code>
|
||||
///
|
||||
/// In the image below you can see the contour of a graph.
|
||||
/// [Open online documentation to see images]
|
||||
///
|
||||
/// In the image below you can see the contour of just a part of a grid graph (when the nodes parameter is supplied)
|
||||
/// [Open online documentation to see images]
|
||||
///
|
||||
/// Contour of a hexagon graph
|
||||
/// [Open online documentation to see images]
|
||||
///
|
||||
/// See: <see cref="GetContours(NavGraph)"/>
|
||||
/// </summary>
|
||||
/// <param name="grid">The grid to find the contours of</param>
|
||||
/// <param name="callback">The callback will be called once for every contour that is found with the vertices of the contour. The contour always forms a cycle.</param>
|
||||
/// <param name="yMergeThreshold">Contours will be simplified if the y coordinates for adjacent vertices differ by no more than this value.</param>
|
||||
/// <param name="nodes">Only these nodes will be searched. If this parameter is null then all nodes in the grid graph will be searched.</param>
|
||||
public static void GetContours (GridGraph grid, System.Action<Vector3[]> callback, float yMergeThreshold, GridNodeBase[] nodes = null) {
|
||||
// Set of all allowed nodes or null if all nodes are allowed
|
||||
HashSet<GridNodeBase> nodeSet = nodes != null ? new HashSet<GridNodeBase>(nodes) : null;
|
||||
|
||||
// Use all nodes if the nodes parameter is null
|
||||
nodes = nodes ?? grid.nodes;
|
||||
int[] neighbourXOffsets = grid.neighbourXOffsets;
|
||||
int[] neighbourZOffsets = grid.neighbourZOffsets;
|
||||
var neighbourIndices = grid.neighbours == NumNeighbours.Six ? GridGraph.hexagonNeighbourIndices : new [] { 0, 1, 2, 3 };
|
||||
var offsetMultiplier = grid.neighbours == NumNeighbours.Six ? 1/3f : 0.5f;
|
||||
|
||||
if (nodes != null) {
|
||||
var trace = ListPool<Vector3>.Claim();
|
||||
var seenStates = new HashSet<int>();
|
||||
|
||||
for (int i = 0; i < nodes.Length; i++) {
|
||||
var startNode = nodes[i];
|
||||
// The third check is a fast check for if the node has connections in all grid directions, if it has then we can skip processing it (unless the nodes parameter was used in which case we have to handle the edge cases)
|
||||
if (startNode != null && startNode.Walkable && (!startNode.HasConnectionsToAllEightNeighbours || nodeSet != null)) {
|
||||
for (int startDir = 0; startDir < neighbourIndices.Length; startDir++) {
|
||||
int startState = (startNode.NodeIndex << 4) | startDir;
|
||||
|
||||
// Check if there is an obstacle in that direction
|
||||
var startNeighbour = startNode.GetNeighbourAlongDirection(neighbourIndices[startDir]);
|
||||
if ((startNeighbour == null || (nodeSet != null && !nodeSet.Contains(startNeighbour))) && !seenStates.Contains(startState)) {
|
||||
// Start tracing a contour here
|
||||
trace.ClearFast();
|
||||
int dir = startDir;
|
||||
GridNodeBase node = startNode;
|
||||
|
||||
while (true) {
|
||||
int state = (node.NodeIndex << 4) | dir;
|
||||
if (state == startState && trace.Count > 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
seenStates.Add(state);
|
||||
|
||||
var neighbour = node.GetNeighbourAlongDirection(neighbourIndices[dir]);
|
||||
if (neighbour == null || (nodeSet != null && !nodeSet.Contains(neighbour))) {
|
||||
// Draw edge
|
||||
var d0 = neighbourIndices[dir];
|
||||
dir = (dir + 1) % neighbourIndices.Length;
|
||||
var d1 = neighbourIndices[dir];
|
||||
|
||||
// Position in graph space of the vertex
|
||||
Vector3 graphSpacePos = new Vector3(node.XCoordinateInGrid + 0.5f, 0, node.ZCoordinateInGrid + 0.5f);
|
||||
// Offset along diagonal to get the correct XZ coordinates
|
||||
graphSpacePos.x += (neighbourXOffsets[d0] + neighbourXOffsets[d1]) * offsetMultiplier;
|
||||
graphSpacePos.z += (neighbourZOffsets[d0] + neighbourZOffsets[d1]) * offsetMultiplier;
|
||||
graphSpacePos.y = grid.transform.InverseTransform((Vector3)node.position).y;
|
||||
|
||||
if (trace.Count >= 2) {
|
||||
var v0 = trace[trace.Count-2];
|
||||
var v1 = trace[trace.Count-1];
|
||||
var v1d = v1 - v0;
|
||||
var v2d = graphSpacePos - v0;
|
||||
// Replace the previous point if it is colinear with the point just before it and just after it (the current point), because that point wouldn't add much information, but it would add CPU overhead
|
||||
if (((Mathf.Abs(v1d.x) > 0.01f || Mathf.Abs(v2d.x) > 0.01f) && (Mathf.Abs(v1d.z) > 0.01f || Mathf.Abs(v2d.z) > 0.01f)) || (Mathf.Abs(v1d.y) > yMergeThreshold || Mathf.Abs(v2d.y) > yMergeThreshold)) {
|
||||
trace.Add(graphSpacePos);
|
||||
} else {
|
||||
trace[trace.Count-1] = graphSpacePos;
|
||||
}
|
||||
} else {
|
||||
trace.Add(graphSpacePos);
|
||||
}
|
||||
} else {
|
||||
// Move
|
||||
node = neighbour;
|
||||
dir = (dir + neighbourIndices.Length/2 + 1) % neighbourIndices.Length;
|
||||
}
|
||||
}
|
||||
|
||||
// Simplify the contour a bit around the start point.
|
||||
// Otherwise we might return a cycle which was not as simplified as possible and the number of vertices
|
||||
// would depend on where in the cycle the algorithm started to traverse the contour.
|
||||
if (trace.Count >= 3) {
|
||||
var v0 = trace[trace.Count-2];
|
||||
var v1 = trace[trace.Count-1];
|
||||
var v1d = v1 - v0;
|
||||
var v2d = trace[0] - v0;
|
||||
// Replace the previous point if it is colinear with the point just before it and just after it (the current point), because that point wouldn't add much information, but it would add CPU overhead
|
||||
if (!(((Mathf.Abs(v1d.x) > 0.01f || Mathf.Abs(v2d.x) > 0.01f) && (Mathf.Abs(v1d.z) > 0.01f || Mathf.Abs(v2d.z) > 0.01f)) || (Mathf.Abs(v1d.y) > yMergeThreshold || Mathf.Abs(v2d.y) > yMergeThreshold))) {
|
||||
trace.RemoveAt(trace.Count - 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (trace.Count >= 3) {
|
||||
var v0 = trace[trace.Count-1];
|
||||
var v1 = trace[0];
|
||||
var v1d = v1 - v0;
|
||||
var v2d = trace[1] - v0;
|
||||
// Replace the previous point if it is colinear with the point just before it and just after it (the current point), because that point wouldn't add much information, but it would add CPU overhead
|
||||
if (!(((Mathf.Abs(v1d.x) > 0.01f || Mathf.Abs(v2d.x) > 0.01f) && (Mathf.Abs(v1d.z) > 0.01f || Mathf.Abs(v2d.z) > 0.01f)) || (Mathf.Abs(v1d.y) > yMergeThreshold || Mathf.Abs(v2d.y) > yMergeThreshold))) {
|
||||
trace.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
var result = trace.ToArray();
|
||||
grid.transform.Transform(result);
|
||||
callback(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ListPool<Vector3>.Release(ref trace);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/Misc/GraphUtilities.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/Misc/GraphUtilities.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fd178834bf6c54cdb8fc5f76a039a91c
|
||||
timeCreated: 1502889881
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
346
AR/Assets/AstarPathfindingProject/Core/Misc/HierarchicalGraph.cs
Normal file
346
AR/Assets/AstarPathfindingProject/Core/Misc/HierarchicalGraph.cs
Normal file
@ -0,0 +1,346 @@
|
||||
using System.Collections.Generic;
|
||||
using Pathfinding.Util;
|
||||
using Pathfinding.Serialization;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
#if UNITY_5_5_OR_NEWER
|
||||
using UnityEngine.Profiling;
|
||||
#endif
|
||||
|
||||
namespace Pathfinding {
|
||||
/// <summary>
|
||||
/// Holds a hierarchical graph to speed up certain pathfinding queries.
|
||||
///
|
||||
/// A common type of query that needs to be very fast is on the form 'is this node reachable from this other node'.
|
||||
/// This is for example used when picking the end node of a path. The end node is determined as the closest node to the end point
|
||||
/// that can be reached from the start node.
|
||||
///
|
||||
/// This data structure's primary purpose is to keep track of which connected component each node is contained in, in order to make such queries fast.
|
||||
///
|
||||
/// See: https://en.wikipedia.org/wiki/Connected_component_(graph_theory)
|
||||
///
|
||||
/// A connected component is a set of nodes such that there is a valid path between every pair of nodes in that set.
|
||||
/// Thus the query above can simply be answered by checking if they are in the same connected component.
|
||||
/// The connected component is exposed on nodes as the <see cref="Pathfinding.GraphNode.Area"/> property and on this class using the <see cref="GetArea"/> method.
|
||||
///
|
||||
/// In the image below (showing a 200x200 grid graph) each connected component is colored using a separate color.
|
||||
/// The actual color doesn't signify anything in particular however, only that they are different.
|
||||
/// [Open online documentation to see images]
|
||||
///
|
||||
/// Prior to version 4.2 the connected components were just a number stored on each node, and when a graph was updated
|
||||
/// the connected components were completely recalculated. This can be done relatively efficiently using a flood filling
|
||||
/// algorithm (see https://en.wikipedia.org/wiki/Flood_fill) however it still requires a pass through every single node
|
||||
/// which can be quite costly on larger graphs.
|
||||
///
|
||||
/// This class instead builds a much smaller graph that still respects the same connectivity as the original graph.
|
||||
/// Each node in this hierarchical graph represents a larger number of real nodes that are one single connected component.
|
||||
/// Take a look at the image below for an example. In the image each color is a separate hierarchical node, and the black connections go between the center of each hierarchical node.
|
||||
///
|
||||
/// [Open online documentation to see images]
|
||||
///
|
||||
/// With the hierarchical graph, the connected components can be calculated by flood filling the hierarchical graph instead of the real graph.
|
||||
/// Then when we need to know which connected component a node belongs to, we look up the connected component of the hierarchical node the node belongs to.
|
||||
///
|
||||
/// The benefit is not immediately obvious. The above is just a bit more complicated way to accomplish the same thing. However the real benefit comes when updating the graph.
|
||||
/// When the graph is updated, all hierarchical nodes which contain any node that was affected by the update is removed completely and then once all have been removed new hierarchical nodes are recalculated in their place.
|
||||
/// Once this is done the connected components of the whole graph can be updated by flood filling only the hierarchical graph. Since the hierarchical graph is vastly smaller than the real graph, this is significantly faster.
|
||||
///
|
||||
/// [Open online documentation to see videos]
|
||||
///
|
||||
/// So finally using all of this, the connected components of the graph can be recalculated very quickly as the graph is updated.
|
||||
/// The effect of this grows larger the larger the graph is, and the smaller the graph update is. Making a small update to a 1000x1000 grid graph is on the order of 40 times faster with these optimizations.
|
||||
/// When scanning a graph or making updates to the whole graph at the same time there is however no speed boost. In fact due to the extra complexity it is a bit slower, however after profiling the extra time seems to be mostly insignificant compared to the rest of the cost of scanning the graph.
|
||||
///
|
||||
/// [Open online documentation to see videos]
|
||||
///
|
||||
/// See: <see cref="Pathfinding.PathUtilities.IsPathPossible"/>
|
||||
/// See: <see cref="Pathfinding.NNConstraint"/>
|
||||
/// See: <see cref="Pathfinding.GraphNode.Area"/>
|
||||
/// </summary>
|
||||
public class HierarchicalGraph {
|
||||
const int Tiling = 16;
|
||||
const int MaxChildrenPerNode = Tiling * Tiling;
|
||||
const int MinChildrenPerNode = MaxChildrenPerNode/2;
|
||||
|
||||
List<GraphNode>[] children = new List<GraphNode>[0];
|
||||
List<int>[] connections = new List<int>[0];
|
||||
int[] areas = new int[0];
|
||||
byte[] dirty = new byte[0];
|
||||
|
||||
public int version { get; private set; }
|
||||
public System.Action onConnectedComponentsChanged;
|
||||
|
||||
System.Action<GraphNode> connectionCallback;
|
||||
|
||||
Queue<GraphNode> temporaryQueue = new Queue<GraphNode>();
|
||||
List<GraphNode> currentChildren = null;
|
||||
List<int> currentConnections = null;
|
||||
int currentHierarchicalNodeIndex;
|
||||
Stack<int> temporaryStack = new Stack<int>();
|
||||
|
||||
int numDirtyNodes = 0;
|
||||
GraphNode[] dirtyNodes = new GraphNode[128];
|
||||
|
||||
Stack<int> freeNodeIndices = new Stack<int>();
|
||||
|
||||
int gizmoVersion = 0;
|
||||
|
||||
public HierarchicalGraph () {
|
||||
// Cache this callback to avoid allocating a new one every time the FindHierarchicalNodeChildren method is called.
|
||||
// It is a big ugly to have to use member variables for the state information in that method, but I see no better way.
|
||||
connectionCallback = (GraphNode neighbour) => {
|
||||
var hIndex = neighbour.HierarchicalNodeIndex;
|
||||
if (hIndex == 0) {
|
||||
if (currentChildren.Count < MaxChildrenPerNode && neighbour.Walkable /* && (((GridNode)currentChildren[0]).XCoordinateInGrid/Tiling == ((GridNode)neighbour).XCoordinateInGrid/Tiling) && (((GridNode)currentChildren[0]).ZCoordinateInGrid/Tiling == ((GridNode)neighbour).ZCoordinateInGrid/Tiling)*/) {
|
||||
neighbour.HierarchicalNodeIndex = currentHierarchicalNodeIndex;
|
||||
temporaryQueue.Enqueue(neighbour);
|
||||
currentChildren.Add(neighbour);
|
||||
}
|
||||
} else if (hIndex != currentHierarchicalNodeIndex && !currentConnections.Contains(hIndex)) {
|
||||
// The Contains call can in theory be very slow as an hierarchical node may be adjacent to an arbitrary number of nodes.
|
||||
// However in practice due to how the nodes are constructed they will only be adjacent to a smallish (≈4-6) number of other nodes.
|
||||
// So a Contains call will be much faster than say a Set lookup.
|
||||
currentConnections.Add(hIndex);
|
||||
}
|
||||
};
|
||||
|
||||
Grow();
|
||||
}
|
||||
|
||||
void Grow () {
|
||||
var newChildren = new List<GraphNode>[System.Math.Max(64, children.Length*2)];
|
||||
var newConnections = new List<int>[newChildren.Length];
|
||||
var newAreas = new int[newChildren.Length];
|
||||
var newDirty = new byte[newChildren.Length];
|
||||
|
||||
children.CopyTo(newChildren, 0);
|
||||
connections.CopyTo(newConnections, 0);
|
||||
areas.CopyTo(newAreas, 0);
|
||||
dirty.CopyTo(newDirty, 0);
|
||||
|
||||
for (int i = children.Length; i < newChildren.Length; i++) {
|
||||
newChildren[i] = ListPool<GraphNode>.Claim(MaxChildrenPerNode);
|
||||
newConnections[i] = new List<int>();
|
||||
if (i > 0) freeNodeIndices.Push(i);
|
||||
}
|
||||
|
||||
children = newChildren;
|
||||
connections = newConnections;
|
||||
areas = newAreas;
|
||||
dirty = newDirty;
|
||||
}
|
||||
|
||||
int GetHierarchicalNodeIndex () {
|
||||
if (freeNodeIndices.Count == 0) Grow();
|
||||
return freeNodeIndices.Pop();
|
||||
}
|
||||
|
||||
internal void OnCreatedNode (GraphNode node) {
|
||||
if (node.NodeIndex >= dirtyNodes.Length) {
|
||||
var newDirty = new GraphNode[System.Math.Max(node.NodeIndex + 1, dirtyNodes.Length*2)];
|
||||
dirtyNodes.CopyTo(newDirty, 0);
|
||||
dirtyNodes = newDirty;
|
||||
}
|
||||
AddDirtyNode(node);
|
||||
}
|
||||
|
||||
internal void AddDirtyNode (GraphNode node) {
|
||||
if (!node.IsHierarchicalNodeDirty) {
|
||||
node.IsHierarchicalNodeDirty = true;
|
||||
// While the dirtyNodes array is guaranteed to be large enough to hold all nodes in the graphs
|
||||
// the array may also end up containing many destroyed nodes. This can in rare cases cause it to go out of bounds.
|
||||
// In that case we need to go through the array and filter out any destroyed nodes while making sure to mark their
|
||||
// corresponding hierarchical nodes as being dirty.
|
||||
if (numDirtyNodes < dirtyNodes.Length) {
|
||||
dirtyNodes[numDirtyNodes] = node;
|
||||
numDirtyNodes++;
|
||||
} else {
|
||||
int maxIndex = 0;
|
||||
for (int i = numDirtyNodes - 1; i >= 0; i--) {
|
||||
if (dirtyNodes[i].Destroyed) {
|
||||
numDirtyNodes--;
|
||||
dirty[dirtyNodes[i].HierarchicalNodeIndex] = 1;
|
||||
dirtyNodes[i] = dirtyNodes[numDirtyNodes];
|
||||
dirtyNodes[numDirtyNodes] = null;
|
||||
} else {
|
||||
maxIndex = System.Math.Max(maxIndex, dirtyNodes[i].NodeIndex);
|
||||
}
|
||||
}
|
||||
if (numDirtyNodes >= dirtyNodes.Length) throw new System.Exception("Failed to compactify dirty nodes array. This should not happen. " + maxIndex + " " + numDirtyNodes + " " + dirtyNodes.Length);
|
||||
AddDirtyNode(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int NumConnectedComponents { get; private set; }
|
||||
|
||||
/// <summary>Get the connected component index of a hierarchical node</summary>
|
||||
public uint GetConnectedComponent (int hierarchicalNodeIndex) {
|
||||
return (uint)areas[hierarchicalNodeIndex];
|
||||
}
|
||||
|
||||
void RemoveHierarchicalNode (int hierarchicalNode, bool removeAdjacentSmallNodes) {
|
||||
freeNodeIndices.Push(hierarchicalNode);
|
||||
var conns = connections[hierarchicalNode];
|
||||
|
||||
for (int i = 0; i < conns.Count; i++) {
|
||||
var adjacentHierarchicalNode = conns[i];
|
||||
// If dirty, this node will be removed later anyway, so don't bother doing anything with it.
|
||||
if (dirty[adjacentHierarchicalNode] != 0) continue;
|
||||
|
||||
if (removeAdjacentSmallNodes && children[adjacentHierarchicalNode].Count < MinChildrenPerNode) {
|
||||
dirty[adjacentHierarchicalNode] = 2;
|
||||
RemoveHierarchicalNode(adjacentHierarchicalNode, false);
|
||||
} else {
|
||||
// Remove the connection from the other node to this node as we are removing this node.
|
||||
connections[adjacentHierarchicalNode].Remove(hierarchicalNode);
|
||||
}
|
||||
}
|
||||
conns.Clear();
|
||||
|
||||
var nodeChildren = children[hierarchicalNode];
|
||||
|
||||
for (int i = 0; i < nodeChildren.Count; i++) {
|
||||
AddDirtyNode(nodeChildren[i]);
|
||||
}
|
||||
|
||||
nodeChildren.ClearFast();
|
||||
}
|
||||
|
||||
/// <summary>Recalculate the hierarchical graph and the connected components if any nodes have been marked as dirty</summary>
|
||||
public void RecalculateIfNecessary () {
|
||||
if (numDirtyNodes > 0) {
|
||||
Profiler.BeginSample("Recalculate Connected Components");
|
||||
for (int i = 0; i < numDirtyNodes; i++) {
|
||||
dirty[dirtyNodes[i].HierarchicalNodeIndex] = 1;
|
||||
}
|
||||
|
||||
// Remove all hierarchical nodes and then build new hierarchical nodes in their place
|
||||
// which take into account the new graph data.
|
||||
for (int i = 1; i < dirty.Length; i++) {
|
||||
if (dirty[i] == 1) RemoveHierarchicalNode(i, true);
|
||||
}
|
||||
for (int i = 1; i < dirty.Length; i++) dirty[i] = 0;
|
||||
|
||||
for (int i = 0; i < numDirtyNodes; i++) {
|
||||
dirtyNodes[i].HierarchicalNodeIndex = 0;
|
||||
}
|
||||
|
||||
for (int i = 0; i < numDirtyNodes; i++) {
|
||||
var node = dirtyNodes[i];
|
||||
// Be nice to the GC
|
||||
dirtyNodes[i] = null;
|
||||
node.IsHierarchicalNodeDirty = false;
|
||||
|
||||
if (node.HierarchicalNodeIndex == 0 && node.Walkable && !node.Destroyed) {
|
||||
FindHierarchicalNodeChildren(GetHierarchicalNodeIndex(), node);
|
||||
}
|
||||
}
|
||||
|
||||
numDirtyNodes = 0;
|
||||
// Recalculate the connected components of the hierarchical nodes
|
||||
FloodFill();
|
||||
Profiler.EndSample();
|
||||
gizmoVersion++;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recalculate everything from scratch.
|
||||
/// This is primarily to be used for legacy code for compatibility reasons, not for any new code.
|
||||
///
|
||||
/// See: <see cref="RecalculateIfNecessary"/>
|
||||
/// </summary>
|
||||
public void RecalculateAll () {
|
||||
AstarPath.active.data.GetNodes(node => AddDirtyNode(node));
|
||||
RecalculateIfNecessary();
|
||||
}
|
||||
|
||||
/// <summary>Flood fills the graph of hierarchical nodes and assigns the same area ID to all hierarchical nodes that are in the same connected component</summary>
|
||||
void FloodFill () {
|
||||
for (int i = 0; i < areas.Length; i++) areas[i] = 0;
|
||||
|
||||
Stack<int> stack = temporaryStack;
|
||||
int currentArea = 0;
|
||||
for (int i = 1; i < areas.Length; i++) {
|
||||
// Already taken care of
|
||||
if (areas[i] != 0) continue;
|
||||
|
||||
currentArea++;
|
||||
areas[i] = currentArea;
|
||||
stack.Push(i);
|
||||
while (stack.Count > 0) {
|
||||
int node = stack.Pop();
|
||||
var conns = connections[node];
|
||||
for (int j = conns.Count - 1; j >= 0; j--) {
|
||||
var otherNode = conns[j];
|
||||
// Note: slightly important that this is != currentArea and not != 0 in case there are some connected, but not stongly connected components in the graph (this will happen in only veeery few types of games)
|
||||
if (areas[otherNode] != currentArea) {
|
||||
areas[otherNode] = currentArea;
|
||||
stack.Push(otherNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
NumConnectedComponents = System.Math.Max(1, currentArea + 1);
|
||||
version++;
|
||||
}
|
||||
|
||||
/// <summary>Run a BFS out from a start node and assign up to MaxChildrenPerNode nodes to the specified hierarchical node which are not already assigned to another hierarchical node</summary>
|
||||
void FindHierarchicalNodeChildren (int hierarchicalNode, GraphNode startNode) {
|
||||
// Set some state for the connectionCallback delegate to use
|
||||
currentChildren = children[hierarchicalNode];
|
||||
currentConnections = connections[hierarchicalNode];
|
||||
currentHierarchicalNodeIndex = hierarchicalNode;
|
||||
|
||||
var que = temporaryQueue;
|
||||
que.Enqueue(startNode);
|
||||
|
||||
startNode.HierarchicalNodeIndex = hierarchicalNode;
|
||||
currentChildren.Add(startNode);
|
||||
|
||||
while (que.Count > 0) {
|
||||
que.Dequeue().GetConnections(connectionCallback);
|
||||
}
|
||||
|
||||
for (int i = 0; i < currentConnections.Count; i++) {
|
||||
connections[currentConnections[i]].Add(hierarchicalNode);
|
||||
}
|
||||
|
||||
que.Clear();
|
||||
}
|
||||
|
||||
public void OnDrawGizmos (Pathfinding.Util.RetainedGizmos gizmos) {
|
||||
var hasher = new Pathfinding.Util.RetainedGizmos.Hasher(AstarPath.active);
|
||||
|
||||
hasher.AddHash(gizmoVersion);
|
||||
|
||||
if (!gizmos.Draw(hasher)) {
|
||||
var builder = ObjectPool<RetainedGizmos.Builder>.Claim();
|
||||
var centers = ArrayPool<UnityEngine.Vector3>.Claim(areas.Length);
|
||||
for (int i = 0; i < areas.Length; i++) {
|
||||
Int3 center = Int3.zero;
|
||||
var childs = children[i];
|
||||
if (childs.Count > 0) {
|
||||
for (int j = 0; j < childs.Count; j++) center += childs[j].position;
|
||||
center /= childs.Count;
|
||||
centers[i] = (UnityEngine.Vector3)center;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < areas.Length; i++) {
|
||||
if (children[i].Count > 0) {
|
||||
for (int j = 0; j < connections[i].Count; j++) {
|
||||
if (connections[i][j] > i) {
|
||||
builder.DrawLine(centers[i], centers[connections[i][j]], UnityEngine.Color.black);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
builder.Submit(gizmos, hasher);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/Misc/HierarchicalGraph.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/Misc/HierarchicalGraph.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: aa5d6e4a6adb04d4ca9b7e735addcbd5
|
||||
timeCreated: 1535050640
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
314
AR/Assets/AstarPathfindingProject/Core/Misc/Int3.cs
Normal file
314
AR/Assets/AstarPathfindingProject/Core/Misc/Int3.cs
Normal file
@ -0,0 +1,314 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace Pathfinding {
|
||||
/// <summary>Holds a coordinate in integers</summary>
|
||||
public struct Int3 : System.IEquatable<Int3> {
|
||||
public int x;
|
||||
public int y;
|
||||
public int z;
|
||||
|
||||
//These should be set to the same value (only PrecisionFactor should be 1 divided by Precision)
|
||||
|
||||
/// <summary>
|
||||
/// Precision for the integer coordinates.
|
||||
/// One world unit is divided into [value] pieces. A value of 1000 would mean millimeter precision, a value of 1 would mean meter precision (assuming 1 world unit = 1 meter).
|
||||
/// This value affects the maximum coordinates for nodes as well as how large the cost values are for moving between two nodes.
|
||||
/// A higher value means that you also have to set all penalty values to a higher value to compensate since the normal cost of moving will be higher.
|
||||
/// </summary>
|
||||
public const int Precision = 1000;
|
||||
|
||||
/// <summary><see cref="Precision"/> as a float</summary>
|
||||
public const float FloatPrecision = 1000F;
|
||||
|
||||
/// <summary>1 divided by <see cref="Precision"/></summary>
|
||||
public const float PrecisionFactor = 0.001F;
|
||||
|
||||
public static Int3 zero { get { return new Int3(); } }
|
||||
|
||||
public Int3 (Vector3 position) {
|
||||
x = (int)System.Math.Round(position.x*FloatPrecision);
|
||||
y = (int)System.Math.Round(position.y*FloatPrecision);
|
||||
z = (int)System.Math.Round(position.z*FloatPrecision);
|
||||
}
|
||||
|
||||
public Int3 (int _x, int _y, int _z) {
|
||||
x = _x;
|
||||
y = _y;
|
||||
z = _z;
|
||||
}
|
||||
|
||||
public static bool operator == (Int3 lhs, Int3 rhs) {
|
||||
return lhs.x == rhs.x &&
|
||||
lhs.y == rhs.y &&
|
||||
lhs.z == rhs.z;
|
||||
}
|
||||
|
||||
public static bool operator != (Int3 lhs, Int3 rhs) {
|
||||
return lhs.x != rhs.x ||
|
||||
lhs.y != rhs.y ||
|
||||
lhs.z != rhs.z;
|
||||
}
|
||||
|
||||
public static explicit operator Int3 (Vector3 ob) {
|
||||
return new Int3(
|
||||
(int)System.Math.Round(ob.x*FloatPrecision),
|
||||
(int)System.Math.Round(ob.y*FloatPrecision),
|
||||
(int)System.Math.Round(ob.z*FloatPrecision)
|
||||
);
|
||||
}
|
||||
|
||||
public static explicit operator Vector3 (Int3 ob) {
|
||||
return new Vector3(ob.x*PrecisionFactor, ob.y*PrecisionFactor, ob.z*PrecisionFactor);
|
||||
}
|
||||
|
||||
public static Int3 operator - (Int3 lhs, Int3 rhs) {
|
||||
lhs.x -= rhs.x;
|
||||
lhs.y -= rhs.y;
|
||||
lhs.z -= rhs.z;
|
||||
return lhs;
|
||||
}
|
||||
|
||||
public static Int3 operator - (Int3 lhs) {
|
||||
lhs.x = -lhs.x;
|
||||
lhs.y = -lhs.y;
|
||||
lhs.z = -lhs.z;
|
||||
return lhs;
|
||||
}
|
||||
|
||||
public static Int3 operator + (Int3 lhs, Int3 rhs) {
|
||||
lhs.x += rhs.x;
|
||||
lhs.y += rhs.y;
|
||||
lhs.z += rhs.z;
|
||||
return lhs;
|
||||
}
|
||||
|
||||
public static Int3 operator * (Int3 lhs, int rhs) {
|
||||
lhs.x *= rhs;
|
||||
lhs.y *= rhs;
|
||||
lhs.z *= rhs;
|
||||
|
||||
return lhs;
|
||||
}
|
||||
|
||||
public static Int3 operator * (Int3 lhs, float rhs) {
|
||||
lhs.x = (int)System.Math.Round(lhs.x * rhs);
|
||||
lhs.y = (int)System.Math.Round(lhs.y * rhs);
|
||||
lhs.z = (int)System.Math.Round(lhs.z * rhs);
|
||||
|
||||
return lhs;
|
||||
}
|
||||
|
||||
public static Int3 operator * (Int3 lhs, double rhs) {
|
||||
lhs.x = (int)System.Math.Round(lhs.x * rhs);
|
||||
lhs.y = (int)System.Math.Round(lhs.y * rhs);
|
||||
lhs.z = (int)System.Math.Round(lhs.z * rhs);
|
||||
|
||||
return lhs;
|
||||
}
|
||||
|
||||
public static Int3 operator / (Int3 lhs, float rhs) {
|
||||
lhs.x = (int)System.Math.Round(lhs.x / rhs);
|
||||
lhs.y = (int)System.Math.Round(lhs.y / rhs);
|
||||
lhs.z = (int)System.Math.Round(lhs.z / rhs);
|
||||
return lhs;
|
||||
}
|
||||
|
||||
public int this[int i] {
|
||||
get {
|
||||
return i == 0 ? x : (i == 1 ? y : z);
|
||||
}
|
||||
set {
|
||||
if (i == 0) x = value;
|
||||
else if (i == 1) y = value;
|
||||
else z = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Angle between the vectors in radians</summary>
|
||||
public static float Angle (Int3 lhs, Int3 rhs) {
|
||||
double cos = Dot(lhs, rhs)/ ((double)lhs.magnitude*(double)rhs.magnitude);
|
||||
|
||||
cos = cos < -1 ? -1 : (cos > 1 ? 1 : cos);
|
||||
return (float)System.Math.Acos(cos);
|
||||
}
|
||||
|
||||
public static int Dot (Int3 lhs, Int3 rhs) {
|
||||
return
|
||||
lhs.x * rhs.x +
|
||||
lhs.y * rhs.y +
|
||||
lhs.z * rhs.z;
|
||||
}
|
||||
|
||||
public static long DotLong (Int3 lhs, Int3 rhs) {
|
||||
return
|
||||
(long)lhs.x * (long)rhs.x +
|
||||
(long)lhs.y * (long)rhs.y +
|
||||
(long)lhs.z * (long)rhs.z;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normal in 2D space (XZ).
|
||||
/// Equivalent to Cross(this, Int3(0,1,0) )
|
||||
/// except that the Y coordinate is left unchanged with this operation.
|
||||
/// </summary>
|
||||
public Int3 Normal2D () {
|
||||
return new Int3(z, y, -x);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the magnitude of the vector. The magnitude is the 'length' of the vector from 0,0,0 to this point. Can be used for distance calculations:
|
||||
/// <code> Debug.Log ("Distance between 3,4,5 and 6,7,8 is: "+(new Int3(3,4,5) - new Int3(6,7,8)).magnitude); </code>
|
||||
/// </summary>
|
||||
public float magnitude {
|
||||
get {
|
||||
//It turns out that using doubles is just as fast as using ints with Mathf.Sqrt. And this can also handle larger numbers (possibly with small errors when using huge numbers)!
|
||||
|
||||
double _x = x;
|
||||
double _y = y;
|
||||
double _z = z;
|
||||
|
||||
return (float)System.Math.Sqrt(_x*_x+_y*_y+_z*_z);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Magnitude used for the cost between two nodes. The default cost between two nodes can be calculated like this:
|
||||
/// <code> int cost = (node1.position-node2.position).costMagnitude; </code>
|
||||
///
|
||||
/// This is simply the magnitude, rounded to the nearest integer
|
||||
/// </summary>
|
||||
public int costMagnitude {
|
||||
get {
|
||||
return (int)System.Math.Round(magnitude);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The squared magnitude of the vector</summary>
|
||||
public float sqrMagnitude {
|
||||
get {
|
||||
double _x = x;
|
||||
double _y = y;
|
||||
double _z = z;
|
||||
return (float)(_x*_x+_y*_y+_z*_z);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The squared magnitude of the vector</summary>
|
||||
public long sqrMagnitudeLong {
|
||||
get {
|
||||
long _x = x;
|
||||
long _y = y;
|
||||
long _z = z;
|
||||
return (_x*_x+_y*_y+_z*_z);
|
||||
}
|
||||
}
|
||||
|
||||
public static implicit operator string (Int3 obj) {
|
||||
return obj.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Returns a nicely formatted string representing the vector</summary>
|
||||
public override string ToString () {
|
||||
return "( "+x+", "+y+", "+z+")";
|
||||
}
|
||||
|
||||
public override bool Equals (System.Object obj) {
|
||||
if (obj == null) return false;
|
||||
|
||||
var rhs = (Int3)obj;
|
||||
|
||||
return x == rhs.x &&
|
||||
y == rhs.y &&
|
||||
z == rhs.z;
|
||||
}
|
||||
|
||||
#region IEquatable implementation
|
||||
|
||||
public bool Equals (Int3 other) {
|
||||
return x == other.x && y == other.y && z == other.z;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public override int GetHashCode () {
|
||||
return x*73856093 ^ y*19349663 ^ z*83492791;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Two Dimensional Integer Coordinate Pair</summary>
|
||||
public struct Int2 : System.IEquatable<Int2> {
|
||||
public int x;
|
||||
public int y;
|
||||
|
||||
public Int2 (int x, int y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
public long sqrMagnitudeLong {
|
||||
get {
|
||||
return (long)x*(long)x+(long)y*(long)y;
|
||||
}
|
||||
}
|
||||
|
||||
public static Int2 operator + (Int2 a, Int2 b) {
|
||||
return new Int2(a.x+b.x, a.y+b.y);
|
||||
}
|
||||
|
||||
public static Int2 operator - (Int2 a, Int2 b) {
|
||||
return new Int2(a.x-b.x, a.y-b.y);
|
||||
}
|
||||
|
||||
public static bool operator == (Int2 a, Int2 b) {
|
||||
return a.x == b.x && a.y == b.y;
|
||||
}
|
||||
|
||||
public static bool operator != (Int2 a, Int2 b) {
|
||||
return a.x != b.x || a.y != b.y;
|
||||
}
|
||||
|
||||
/// <summary>Dot product of the two coordinates</summary>
|
||||
public static long DotLong (Int2 a, Int2 b) {
|
||||
return (long)a.x*(long)b.x + (long)a.y*(long)b.y;
|
||||
}
|
||||
|
||||
public override bool Equals (System.Object o) {
|
||||
if (o == null) return false;
|
||||
var rhs = (Int2)o;
|
||||
|
||||
return x == rhs.x && y == rhs.y;
|
||||
}
|
||||
|
||||
#region IEquatable implementation
|
||||
|
||||
public bool Equals (Int2 other) {
|
||||
return x == other.x && y == other.y;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public override int GetHashCode () {
|
||||
return x*49157+y*98317;
|
||||
}
|
||||
|
||||
public static Int2 Min (Int2 a, Int2 b) {
|
||||
return new Int2(System.Math.Min(a.x, b.x), System.Math.Min(a.y, b.y));
|
||||
}
|
||||
|
||||
public static Int2 Max (Int2 a, Int2 b) {
|
||||
return new Int2(System.Math.Max(a.x, b.x), System.Math.Max(a.y, b.y));
|
||||
}
|
||||
|
||||
public static Int2 FromInt3XZ (Int3 o) {
|
||||
return new Int2(o.x, o.z);
|
||||
}
|
||||
|
||||
public static Int3 ToInt3XZ (Int2 o) {
|
||||
return new Int3(o.x, 0, o.y);
|
||||
}
|
||||
|
||||
public override string ToString () {
|
||||
return "("+x+", " +y+")";
|
||||
}
|
||||
}
|
||||
}
|
7
AR/Assets/AstarPathfindingProject/Core/Misc/Int3.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/Misc/Int3.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5826dd4a1809b448291582cd06deadc1
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
211
AR/Assets/AstarPathfindingProject/Core/Misc/ListPool.cs
Normal file
211
AR/Assets/AstarPathfindingProject/Core/Misc/ListPool.cs
Normal file
@ -0,0 +1,211 @@
|
||||
#if !UNITY_EDITOR
|
||||
// Extra optimizations when not running in the editor, but less error checking
|
||||
#define ASTAR_OPTIMIZE_POOLING
|
||||
#endif
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding.Util {
|
||||
/// <summary>
|
||||
/// Lightweight List Pool.
|
||||
/// Handy class for pooling lists of type T.
|
||||
///
|
||||
/// Usage:
|
||||
/// - Claim a new list using <code> List<SomeClass> foo = ListPool<SomeClass>.Claim (); </code>
|
||||
/// - Use it and do stuff with it
|
||||
/// - Release it with <code> ListPool<SomeClass>.Release (foo); </code>
|
||||
///
|
||||
/// You do not need to clear the list before releasing it.
|
||||
/// After you have released a list, you should never use it again, if you do use it, you will
|
||||
/// mess things up quite badly in the worst case.
|
||||
///
|
||||
/// \since Version 3.2
|
||||
/// See: Pathfinding.Util.StackPool
|
||||
/// </summary>
|
||||
public static class ListPool<T> {
|
||||
/// <summary>Internal pool</summary>
|
||||
static readonly List<List<T> > pool = new List<List<T> >();
|
||||
|
||||
#if !ASTAR_NO_POOLING
|
||||
static readonly List<List<T> > largePool = new List<List<T> >();
|
||||
static readonly HashSet<List<T> > inPool = new HashSet<List<T> >();
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// When requesting a list with a specified capacity, search max this many lists in the pool before giving up.
|
||||
/// Must be greater or equal to one.
|
||||
/// </summary>
|
||||
const int MaxCapacitySearchLength = 8;
|
||||
const int LargeThreshold = 5000;
|
||||
const int MaxLargePoolSize = 8;
|
||||
|
||||
/// <summary>
|
||||
/// Claim a list.
|
||||
/// Returns a pooled list if any are in the pool.
|
||||
/// Otherwise it creates a new one.
|
||||
/// After usage, this list should be released using the Release function (though not strictly necessary).
|
||||
/// </summary>
|
||||
public static List<T> Claim () {
|
||||
#if ASTAR_NO_POOLING
|
||||
return new List<T>();
|
||||
#else
|
||||
lock (pool) {
|
||||
if (pool.Count > 0) {
|
||||
List<T> ls = pool[pool.Count-1];
|
||||
pool.RemoveAt(pool.Count-1);
|
||||
inPool.Remove(ls);
|
||||
return ls;
|
||||
}
|
||||
|
||||
return new List<T>();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
static int FindCandidate (List<List<T> > pool, int capacity) {
|
||||
// Loop through the last MaxCapacitySearchLength items
|
||||
// and check if any item has a capacity greater or equal to the one that
|
||||
// is desired. If so return it.
|
||||
// Otherwise take the largest one or if there are no lists in the pool
|
||||
// then allocate a new one with the desired capacity
|
||||
List<T> list = null;
|
||||
int listIndex = -1;
|
||||
|
||||
for (int i = 0; i < pool.Count && i < MaxCapacitySearchLength; i++) {
|
||||
// ith last item
|
||||
var candidate = pool[pool.Count-1-i];
|
||||
|
||||
// Find the largest list that is not too large (arbitrary decision to try to prevent some memory bloat if the list was not just a temporary list).
|
||||
if ((list == null || candidate.Capacity > list.Capacity) && candidate.Capacity < capacity*16) {
|
||||
list = candidate;
|
||||
listIndex = pool.Count-1-i;
|
||||
|
||||
if (list.Capacity >= capacity) {
|
||||
return listIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return listIndex;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Claim a list with minimum capacity
|
||||
/// Returns a pooled list if any are in the pool.
|
||||
/// Otherwise it creates a new one.
|
||||
/// After usage, this list should be released using the Release function (though not strictly necessary).
|
||||
/// A subset of the pool will be searched for a list with a high enough capacity and one will be returned
|
||||
/// if possible, otherwise the list with the largest capacity found will be returned.
|
||||
/// </summary>
|
||||
public static List<T> Claim (int capacity) {
|
||||
#if ASTAR_NO_POOLING
|
||||
return new List<T>(capacity);
|
||||
#else
|
||||
lock (pool) {
|
||||
var currentPool = pool;
|
||||
var listIndex = FindCandidate(pool, capacity);
|
||||
|
||||
if (capacity > LargeThreshold) {
|
||||
var largeListIndex = FindCandidate(largePool, capacity);
|
||||
if (largeListIndex != -1) {
|
||||
currentPool = largePool;
|
||||
listIndex = largeListIndex;
|
||||
}
|
||||
}
|
||||
|
||||
if (listIndex == -1) {
|
||||
return new List<T>(capacity);
|
||||
} else {
|
||||
var list = currentPool[listIndex];
|
||||
// Swap current item and last item to enable a more efficient removal
|
||||
inPool.Remove(list);
|
||||
currentPool[listIndex] = currentPool[currentPool.Count-1];
|
||||
currentPool.RemoveAt(currentPool.Count-1);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes sure the pool contains at least count pooled items with capacity size.
|
||||
/// This is good if you want to do all allocations at start.
|
||||
/// </summary>
|
||||
public static void Warmup (int count, int size) {
|
||||
lock (pool) {
|
||||
var tmp = new List<T>[count];
|
||||
for (int i = 0; i < count; i++) tmp[i] = Claim(size);
|
||||
for (int i = 0; i < count; i++) Release(tmp[i]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Releases a list and sets the variable to null.
|
||||
/// After the list has been released it should not be used anymore.
|
||||
///
|
||||
/// \throws System.InvalidOperationException
|
||||
/// Releasing a list when it has already been released will cause an exception to be thrown.
|
||||
///
|
||||
/// See: <see cref="Claim"/>
|
||||
/// </summary>
|
||||
public static void Release (ref List<T> list) {
|
||||
Release(list);
|
||||
list = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases a list.
|
||||
/// After the list has been released it should not be used anymore.
|
||||
///
|
||||
/// \throws System.InvalidOperationException
|
||||
/// Releasing a list when it has already been released will cause an exception to be thrown.
|
||||
///
|
||||
/// See: <see cref="Claim"/>
|
||||
/// </summary>
|
||||
public static void Release (List<T> list) {
|
||||
#if !ASTAR_NO_POOLING
|
||||
list.ClearFast();
|
||||
|
||||
lock (pool) {
|
||||
#if !ASTAR_OPTIMIZE_POOLING
|
||||
if (!inPool.Add(list)) {
|
||||
throw new InvalidOperationException("You are trying to pool a list twice. Please make sure that you only pool it once.");
|
||||
}
|
||||
#endif
|
||||
if (list.Capacity > LargeThreshold) {
|
||||
largePool.Add(list);
|
||||
|
||||
// Remove the list which was used the longest time ago from the pool if it
|
||||
// exceeds the maximum size as it probably just contributes to memory bloat
|
||||
if (largePool.Count > MaxLargePoolSize) {
|
||||
largePool.RemoveAt(0);
|
||||
}
|
||||
} else {
|
||||
pool.Add(list);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the pool for lists of this type.
|
||||
/// This is an O(n) operation, where n is the number of pooled lists.
|
||||
/// </summary>
|
||||
public static void Clear () {
|
||||
lock (pool) {
|
||||
#if !ASTAR_OPTIMIZE_POOLING && !ASTAR_NO_POOLING
|
||||
inPool.Clear();
|
||||
#endif
|
||||
pool.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Number of lists of this type in the pool</summary>
|
||||
public static int GetSize () {
|
||||
// No lock required since int writes are atomic
|
||||
return pool.Count;
|
||||
}
|
||||
}
|
||||
}
|
7
AR/Assets/AstarPathfindingProject/Core/Misc/ListPool.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/Misc/ListPool.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2b76b7593907b44d9a6ef1b186fee0a7
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
174
AR/Assets/AstarPathfindingProject/Core/Misc/MovementUtilities.cs
Normal file
174
AR/Assets/AstarPathfindingProject/Core/Misc/MovementUtilities.cs
Normal file
@ -0,0 +1,174 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
|
||||
namespace Pathfinding.Util {
|
||||
public static class MovementUtilities {
|
||||
/// <summary>
|
||||
/// Clamps the velocity to the max speed and optionally the forwards direction.
|
||||
///
|
||||
/// Note that all vectors are 2D vectors, not 3D vectors.
|
||||
///
|
||||
/// Returns: The clamped velocity in world units per second.
|
||||
/// </summary>
|
||||
/// <param name="velocity">Desired velocity of the character. In world units per second.</param>
|
||||
/// <param name="maxSpeed">Max speed of the character. In world units per second.</param>
|
||||
/// <param name="slowdownFactor">Value between 0 and 1 which determines how much slower the character should move than normal.
|
||||
/// Normally 1 but should go to 0 when the character approaches the end of the path.</param>
|
||||
/// <param name="slowWhenNotFacingTarget">Prevent the velocity from being too far away from the forward direction of the character
|
||||
/// and slow the character down if the desired velocity is not in the same direction as the forward vector.</param>
|
||||
/// <param name="forward">Forward direction of the character. Used together with the slowWhenNotFacingTarget parameter.</param>
|
||||
public static Vector2 ClampVelocity (Vector2 velocity, float maxSpeed, float slowdownFactor, bool slowWhenNotFacingTarget, Vector2 forward) {
|
||||
// Max speed to use for this frame
|
||||
var currentMaxSpeed = maxSpeed * slowdownFactor;
|
||||
|
||||
// Check if the agent should slow down in case it is not facing the direction it wants to move in
|
||||
if (slowWhenNotFacingTarget && (forward.x != 0 || forward.y != 0)) {
|
||||
float currentSpeed;
|
||||
var normalizedVelocity = VectorMath.Normalize(velocity, out currentSpeed);
|
||||
float dot = Vector2.Dot(normalizedVelocity, forward);
|
||||
|
||||
// Lower the speed when the character's forward direction is not pointing towards the desired velocity
|
||||
// 1 when velocity is in the same direction as forward
|
||||
// 0.2 when they point in the opposite directions
|
||||
float directionSpeedFactor = Mathf.Clamp(dot+0.707f, 0.2f, 1.0f);
|
||||
currentMaxSpeed *= directionSpeedFactor;
|
||||
currentSpeed = Mathf.Min(currentSpeed, currentMaxSpeed);
|
||||
|
||||
// Angle between the forwards direction of the character and our desired velocity
|
||||
float angle = Mathf.Acos(Mathf.Clamp(dot, -1, 1));
|
||||
|
||||
// Clamp the angle to 20 degrees
|
||||
// We cannot keep the velocity exactly in the forwards direction of the character
|
||||
// because we use the rotation to determine in which direction to rotate and if
|
||||
// the velocity would always be in the forwards direction of the character then
|
||||
// the character would never rotate.
|
||||
// Allow larger angles when near the end of the path to prevent oscillations.
|
||||
angle = Mathf.Min(angle, (20f + 180f*(1 - slowdownFactor*slowdownFactor))*Mathf.Deg2Rad);
|
||||
|
||||
float sin = Mathf.Sin(angle);
|
||||
float cos = Mathf.Cos(angle);
|
||||
|
||||
// Determine if we should rotate clockwise or counter-clockwise to move towards the current velocity
|
||||
sin *= Mathf.Sign(normalizedVelocity.x*forward.y - normalizedVelocity.y*forward.x);
|
||||
// Rotate the #forward vector by #angle radians
|
||||
// The rotation is done using an inlined rotation matrix.
|
||||
// See https://en.wikipedia.org/wiki/Rotation_matrix
|
||||
return new Vector2(forward.x*cos + forward.y*sin, forward.y*cos - forward.x*sin) * currentSpeed;
|
||||
} else {
|
||||
return Vector2.ClampMagnitude(velocity, currentMaxSpeed);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Calculate an acceleration to move deltaPosition units and get there with approximately a velocity of targetVelocity</summary>
|
||||
public static Vector2 CalculateAccelerationToReachPoint (Vector2 deltaPosition, Vector2 targetVelocity, Vector2 currentVelocity, float forwardsAcceleration, float rotationSpeed, float maxSpeed, Vector2 forwardsVector) {
|
||||
// Guard against div by zero
|
||||
if (forwardsAcceleration <= 0) return Vector2.zero;
|
||||
|
||||
float currentSpeed = currentVelocity.magnitude;
|
||||
|
||||
// Convert rotation speed to an acceleration
|
||||
// See https://en.wikipedia.org/wiki/Centripetal_force
|
||||
var sidewaysAcceleration = currentSpeed * rotationSpeed * Mathf.Deg2Rad;
|
||||
|
||||
// To avoid weird behaviour when the rotation speed is very low we allow the agent to accelerate sideways without rotating much
|
||||
// if the rotation speed is very small. Also guards against division by zero.
|
||||
sidewaysAcceleration = Mathf.Max(sidewaysAcceleration, forwardsAcceleration);
|
||||
|
||||
// Transform coordinates to local space where +X is the forwards direction
|
||||
// This is essentially equivalent to Transform.InverseTransformDirection.
|
||||
deltaPosition = VectorMath.ComplexMultiplyConjugate(deltaPosition, forwardsVector);
|
||||
targetVelocity = VectorMath.ComplexMultiplyConjugate(targetVelocity, forwardsVector);
|
||||
currentVelocity = VectorMath.ComplexMultiplyConjugate(currentVelocity, forwardsVector);
|
||||
float ellipseSqrFactorX = 1 / (forwardsAcceleration*forwardsAcceleration);
|
||||
float ellipseSqrFactorY = 1 / (sidewaysAcceleration*sidewaysAcceleration);
|
||||
|
||||
// If the target velocity is zero we can use a more fancy approach
|
||||
// and calculate a nicer path.
|
||||
// In particular, this is the case at the end of the path.
|
||||
if (targetVelocity == Vector2.zero) {
|
||||
// Run a binary search over the time to get to the target point.
|
||||
float mn = 0.01f;
|
||||
float mx = 10;
|
||||
while (mx - mn > 0.01f) {
|
||||
var time = (mx + mn) * 0.5f;
|
||||
|
||||
// Given that we want to move deltaPosition units from out current position, that our current velocity is given
|
||||
// and that when we reach the target we want our velocity to be zero. Also assume that our acceleration will
|
||||
// vary linearly during the slowdown. Then we can calculate what our acceleration should be during this frame.
|
||||
|
||||
//{ t = time
|
||||
//{ deltaPosition = vt + at^2/2 + qt^3/6
|
||||
//{ 0 = v + at + qt^2/2
|
||||
//{ solve for a
|
||||
// a = acceleration vector
|
||||
// q = derivative of the acceleration vector
|
||||
var a = (6*deltaPosition - 4*time*currentVelocity)/(time*time);
|
||||
var q = 6*(time*currentVelocity - 2*deltaPosition)/(time*time*time);
|
||||
|
||||
// Make sure the acceleration is not greater than our maximum allowed acceleration.
|
||||
// If it is we increase the time we want to use to get to the target
|
||||
// and if it is not, we decrease the time to get there faster.
|
||||
// Since the acceleration is described by acceleration = a + q*t
|
||||
// we only need to check at t=0 and t=time.
|
||||
// Note that the acceleration limit is described by an ellipse, not a circle.
|
||||
var nextA = a + q*time;
|
||||
if (a.x*a.x*ellipseSqrFactorX + a.y*a.y*ellipseSqrFactorY > 1.0f || nextA.x*nextA.x*ellipseSqrFactorX + nextA.y*nextA.y*ellipseSqrFactorY > 1.0f) {
|
||||
mn = time;
|
||||
} else {
|
||||
mx = time;
|
||||
}
|
||||
}
|
||||
|
||||
var finalAcceleration = (6*deltaPosition - 4*mx*currentVelocity)/(mx*mx);
|
||||
|
||||
// Boosting
|
||||
{
|
||||
// The trajectory calculated above has a tendency to use very wide arcs
|
||||
// and that does unfortunately not look particularly good in some cases.
|
||||
// Here we amplify the component of the acceleration that is perpendicular
|
||||
// to our current velocity. This will make the agent turn towards the
|
||||
// target quicker.
|
||||
// How much amplification to use. Value is unitless.
|
||||
const float Boost = 1;
|
||||
finalAcceleration.y *= 1 + Boost;
|
||||
|
||||
// Clamp the velocity to the maximum acceleration.
|
||||
// Note that the maximum acceleration constraint is shaped like an ellipse, not like a circle.
|
||||
float ellipseMagnitude = finalAcceleration.x*finalAcceleration.x*ellipseSqrFactorX + finalAcceleration.y*finalAcceleration.y*ellipseSqrFactorY;
|
||||
if (ellipseMagnitude > 1.0f) finalAcceleration /= Mathf.Sqrt(ellipseMagnitude);
|
||||
}
|
||||
|
||||
return VectorMath.ComplexMultiply(finalAcceleration, forwardsVector);
|
||||
} else {
|
||||
// Here we try to move towards the next waypoint which has been modified slightly using our
|
||||
// desired velocity at that point so that the agent will more smoothly round the corner.
|
||||
|
||||
// How much to strive for making sure we reach the target point with the target velocity. Unitless.
|
||||
const float TargetVelocityWeight = 0.5f;
|
||||
|
||||
// Limit to how much to care about the target velocity. Value is in seconds.
|
||||
// This prevents the character from moving away from the path too much when the target point is far away
|
||||
const float TargetVelocityWeightLimit = 1.5f;
|
||||
float targetSpeed;
|
||||
var normalizedTargetVelocity = VectorMath.Normalize(targetVelocity, out targetSpeed);
|
||||
|
||||
var distance = deltaPosition.magnitude;
|
||||
var targetPoint = deltaPosition - normalizedTargetVelocity * System.Math.Min(TargetVelocityWeight * distance * targetSpeed / (currentSpeed + targetSpeed), maxSpeed*TargetVelocityWeightLimit);
|
||||
|
||||
// How quickly the agent will try to reach the velocity that we want it to have.
|
||||
// We need this to prevent oscillations and jitter which is what happens if
|
||||
// we let the constant go towards zero. Value is in seconds.
|
||||
const float TimeToReachDesiredVelocity = 0.1f;
|
||||
// TODO: Clamp to ellipse using more accurate acceleration (use rotation speed as well)
|
||||
var finalAcceleration = (targetPoint.normalized*maxSpeed - currentVelocity) * (1f/TimeToReachDesiredVelocity);
|
||||
|
||||
// Clamp the velocity to the maximum acceleration.
|
||||
// Note that the maximum acceleration constraint is shaped like an ellipse, not like a circle.
|
||||
float ellipseMagnitude = finalAcceleration.x*finalAcceleration.x*ellipseSqrFactorX + finalAcceleration.y*finalAcceleration.y*ellipseSqrFactorY;
|
||||
if (ellipseMagnitude > 1.0f) finalAcceleration /= Mathf.Sqrt(ellipseMagnitude);
|
||||
|
||||
return VectorMath.ComplexMultiply(finalAcceleration, forwardsVector);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/Misc/MovementUtilities.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/Misc/MovementUtilities.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0a6cffd9895f94907aa43f18b0904587
|
||||
timeCreated: 1490097740
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
157
AR/Assets/AstarPathfindingProject/Core/Misc/NodeLink.cs
Normal file
157
AR/Assets/AstarPathfindingProject/Core/Misc/NodeLink.cs
Normal file
@ -0,0 +1,157 @@
|
||||
using UnityEngine;
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
#endif
|
||||
|
||||
namespace Pathfinding {
|
||||
using Pathfinding.Util;
|
||||
|
||||
/// <summary>
|
||||
/// Connects two nodes with a direct connection.
|
||||
/// It is not possible to detect this link when following a path (which may be good or bad), for that you can use NodeLink2.
|
||||
///
|
||||
/// [Open online documentation to see images]
|
||||
///
|
||||
/// See: editing-graphs (view in online documentation for working links)
|
||||
/// </summary>
|
||||
[AddComponentMenu("Pathfinding/Link")]
|
||||
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_node_link.php")]
|
||||
public class NodeLink : GraphModifier {
|
||||
/// <summary>End position of the link</summary>
|
||||
public Transform end;
|
||||
|
||||
/// <summary>
|
||||
/// The connection will be this times harder/slower to traverse.
|
||||
/// Note that values lower than one will not always make the pathfinder choose this path instead of another path even though this one should
|
||||
/// lead to a lower total cost unless you also adjust the Heuristic Scale in A* Inspector -> Settings -> Pathfinding or disable the heuristic altogether.
|
||||
/// </summary>
|
||||
public float costFactor = 1.0f;
|
||||
|
||||
/// <summary>Make a one-way connection</summary>
|
||||
public bool oneWay = false;
|
||||
|
||||
/// <summary>Delete existing connection instead of adding one</summary>
|
||||
public bool deleteConnection = false;
|
||||
|
||||
public Transform Start {
|
||||
get { return transform; }
|
||||
}
|
||||
|
||||
public Transform End {
|
||||
get { return end; }
|
||||
}
|
||||
|
||||
public override void OnPostScan () {
|
||||
if (AstarPath.active.isScanning) {
|
||||
InternalOnPostScan();
|
||||
} else {
|
||||
AstarPath.active.AddWorkItem(new AstarWorkItem(force => {
|
||||
InternalOnPostScan();
|
||||
return true;
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
public void InternalOnPostScan () {
|
||||
Apply();
|
||||
}
|
||||
|
||||
public override void OnGraphsPostUpdate () {
|
||||
if (!AstarPath.active.isScanning) {
|
||||
AstarPath.active.AddWorkItem(new AstarWorkItem(force => {
|
||||
InternalOnPostScan();
|
||||
return true;
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void Apply () {
|
||||
if (Start == null || End == null || AstarPath.active == null) return;
|
||||
|
||||
GraphNode startNode = AstarPath.active.GetNearest(Start.position).node;
|
||||
GraphNode endNode = AstarPath.active.GetNearest(End.position).node;
|
||||
|
||||
if (startNode == null || endNode == null) return;
|
||||
|
||||
|
||||
if (deleteConnection) {
|
||||
startNode.RemoveConnection(endNode);
|
||||
if (!oneWay)
|
||||
endNode.RemoveConnection(startNode);
|
||||
} else {
|
||||
uint cost = (uint)System.Math.Round((startNode.position-endNode.position).costMagnitude*costFactor);
|
||||
|
||||
startNode.AddConnection(endNode, cost);
|
||||
if (!oneWay)
|
||||
endNode.AddConnection(startNode, cost);
|
||||
}
|
||||
}
|
||||
|
||||
public void OnDrawGizmos () {
|
||||
if (Start == null || End == null) return;
|
||||
|
||||
Draw.Gizmos.Bezier(Start.position, End.position, deleteConnection ? Color.red : Color.green);
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
[UnityEditor.MenuItem("Edit/Pathfinding/Link Pair %&l")]
|
||||
public static void LinkObjects () {
|
||||
Transform[] tfs = Selection.transforms;
|
||||
if (tfs.Length == 2) {
|
||||
LinkObjects(tfs[0], tfs[1], false);
|
||||
}
|
||||
SceneView.RepaintAll();
|
||||
}
|
||||
|
||||
[UnityEditor.MenuItem("Edit/Pathfinding/Unlink Pair %&u")]
|
||||
public static void UnlinkObjects () {
|
||||
Transform[] tfs = Selection.transforms;
|
||||
if (tfs.Length == 2) {
|
||||
LinkObjects(tfs[0], tfs[1], true);
|
||||
}
|
||||
SceneView.RepaintAll();
|
||||
}
|
||||
|
||||
[UnityEditor.MenuItem("Edit/Pathfinding/Delete Links on Selected %&b")]
|
||||
public static void DeleteLinks () {
|
||||
Transform[] tfs = Selection.transforms;
|
||||
for (int i = 0; i < tfs.Length; i++) {
|
||||
NodeLink[] conns = tfs[i].GetComponents<NodeLink>();
|
||||
for (int j = 0; j < conns.Length; j++) DestroyImmediate(conns[j]);
|
||||
}
|
||||
SceneView.RepaintAll();
|
||||
}
|
||||
|
||||
public static void LinkObjects (Transform a, Transform b, bool removeConnection) {
|
||||
NodeLink connecting = null;
|
||||
|
||||
NodeLink[] conns = a.GetComponents<NodeLink>();
|
||||
for (int i = 0; i < conns.Length; i++) {
|
||||
if (conns[i].end == b) {
|
||||
connecting = conns[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
conns = b.GetComponents<NodeLink>();
|
||||
for (int i = 0; i < conns.Length; i++) {
|
||||
if (conns[i].end == a) {
|
||||
connecting = conns[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (removeConnection) {
|
||||
if (connecting != null) DestroyImmediate(connecting);
|
||||
} else {
|
||||
if (connecting == null) {
|
||||
connecting = a.gameObject.AddComponent<NodeLink>();
|
||||
connecting.end = b;
|
||||
} else {
|
||||
connecting.deleteConnection = !connecting.deleteConnection;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
7
AR/Assets/AstarPathfindingProject/Core/Misc/NodeLink.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/Misc/NodeLink.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ca327ce4e754a4597a70fb963758f8bd
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
308
AR/Assets/AstarPathfindingProject/Core/Misc/NodeLink2.cs
Normal file
308
AR/Assets/AstarPathfindingProject/Core/Misc/NodeLink2.cs
Normal file
@ -0,0 +1,308 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding {
|
||||
using Pathfinding.Util;
|
||||
|
||||
/// <summary>
|
||||
/// Connects two nodes via two intermediate point nodes.
|
||||
/// In contrast to the NodeLink component, this link type will not connect the nodes directly
|
||||
/// instead it will create two point nodes at the start and end position of this link and connect
|
||||
/// through those nodes.
|
||||
///
|
||||
/// If the closest node to this object is called A and the closest node to the end transform is called
|
||||
/// D, then it will create one point node at this object's position (call it B) and one point node at
|
||||
/// the position of the end transform (call it C), it will then connect A to B, B to C and C to D.
|
||||
///
|
||||
/// This link type is possible to detect while following since it has these special point nodes in the middle.
|
||||
/// The link corresponding to one of those intermediate nodes can be retrieved using the <see cref="GetNodeLink"/> method
|
||||
/// which can be of great use if you want to, for example, play a link specific animation when reaching the link.
|
||||
///
|
||||
/// See: The example scene RecastExample2 contains a few links which you can take a look at to see how they are used.
|
||||
/// </summary>
|
||||
[AddComponentMenu("Pathfinding/Link2")]
|
||||
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_node_link2.php")]
|
||||
public class NodeLink2 : GraphModifier {
|
||||
protected static Dictionary<GraphNode, NodeLink2> reference = new Dictionary<GraphNode, NodeLink2>();
|
||||
public static NodeLink2 GetNodeLink (GraphNode node) {
|
||||
NodeLink2 v;
|
||||
|
||||
reference.TryGetValue(node, out v);
|
||||
return v;
|
||||
}
|
||||
|
||||
/// <summary>End position of the link</summary>
|
||||
public Transform end;
|
||||
|
||||
/// <summary>
|
||||
/// The connection will be this times harder/slower to traverse.
|
||||
/// Note that values lower than 1 will not always make the pathfinder choose this path instead of another path even though this one should
|
||||
/// lead to a lower total cost unless you also adjust the Heuristic Scale in A* Inspector -> Settings -> Pathfinding or disable the heuristic altogether.
|
||||
/// </summary>
|
||||
public float costFactor = 1.0f;
|
||||
|
||||
/// <summary>Make a one-way connection</summary>
|
||||
public bool oneWay = false;
|
||||
|
||||
public Transform StartTransform {
|
||||
get { return transform; }
|
||||
}
|
||||
|
||||
public Transform EndTransform {
|
||||
get { return end; }
|
||||
}
|
||||
|
||||
public PointNode startNode { get; private set; }
|
||||
public PointNode endNode { get; private set; }
|
||||
GraphNode connectedNode1, connectedNode2;
|
||||
Vector3 clamped1, clamped2;
|
||||
bool postScanCalled = false;
|
||||
|
||||
[System.Obsolete("Use startNode instead (lowercase s)")]
|
||||
public GraphNode StartNode {
|
||||
get { return startNode; }
|
||||
}
|
||||
|
||||
[System.Obsolete("Use endNode instead (lowercase e)")]
|
||||
public GraphNode EndNode {
|
||||
get { return endNode; }
|
||||
}
|
||||
|
||||
public override void OnPostScan () {
|
||||
InternalOnPostScan();
|
||||
}
|
||||
|
||||
public void InternalOnPostScan () {
|
||||
if (EndTransform == null || StartTransform == null) return;
|
||||
|
||||
#if ASTAR_NO_POINT_GRAPH
|
||||
throw new System.Exception("Point graph is not included. Check your A* optimization settings.");
|
||||
#else
|
||||
if (AstarPath.active.data.pointGraph == null) {
|
||||
var graph = AstarPath.active.data.AddGraph(typeof(PointGraph)) as PointGraph;
|
||||
graph.name = "PointGraph (used for node links)";
|
||||
}
|
||||
|
||||
if (startNode != null && startNode.Destroyed) {
|
||||
reference.Remove(startNode);
|
||||
startNode = null;
|
||||
}
|
||||
|
||||
if (endNode != null && endNode.Destroyed) {
|
||||
reference.Remove(endNode);
|
||||
endNode = null;
|
||||
}
|
||||
|
||||
// Create new nodes on the point graph
|
||||
if (startNode == null) startNode = AstarPath.active.data.pointGraph.AddNode((Int3)StartTransform.position);
|
||||
if (endNode == null) endNode = AstarPath.active.data.pointGraph.AddNode((Int3)EndTransform.position);
|
||||
|
||||
connectedNode1 = null;
|
||||
connectedNode2 = null;
|
||||
|
||||
if (startNode == null || endNode == null) {
|
||||
startNode = null;
|
||||
endNode = null;
|
||||
return;
|
||||
}
|
||||
|
||||
postScanCalled = true;
|
||||
reference[startNode] = this;
|
||||
reference[endNode] = this;
|
||||
Apply(true);
|
||||
#endif
|
||||
}
|
||||
|
||||
public override void OnGraphsPostUpdate () {
|
||||
// Don't bother running it now since OnPostScan will be called later anyway
|
||||
if (AstarPath.active.isScanning)
|
||||
return;
|
||||
|
||||
if (connectedNode1 != null && connectedNode1.Destroyed) {
|
||||
connectedNode1 = null;
|
||||
}
|
||||
if (connectedNode2 != null && connectedNode2.Destroyed) {
|
||||
connectedNode2 = null;
|
||||
}
|
||||
|
||||
if (!postScanCalled) {
|
||||
OnPostScan();
|
||||
} else {
|
||||
Apply(false);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnEnable () {
|
||||
base.OnEnable();
|
||||
|
||||
#if !ASTAR_NO_POINT_GRAPH
|
||||
if (Application.isPlaying && AstarPath.active != null && AstarPath.active.data != null && AstarPath.active.data.pointGraph != null && !AstarPath.active.isScanning) {
|
||||
// Call OnGraphsPostUpdate as soon as possible when it is safe to update the graphs
|
||||
AstarPath.active.AddWorkItem(OnGraphsPostUpdate);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
protected override void OnDisable () {
|
||||
base.OnDisable();
|
||||
|
||||
postScanCalled = false;
|
||||
|
||||
if (startNode != null) reference.Remove(startNode);
|
||||
if (endNode != null) reference.Remove(endNode);
|
||||
|
||||
if (startNode != null && endNode != null) {
|
||||
startNode.RemoveConnection(endNode);
|
||||
endNode.RemoveConnection(startNode);
|
||||
|
||||
if (connectedNode1 != null && connectedNode2 != null) {
|
||||
startNode.RemoveConnection(connectedNode1);
|
||||
connectedNode1.RemoveConnection(startNode);
|
||||
|
||||
endNode.RemoveConnection(connectedNode2);
|
||||
connectedNode2.RemoveConnection(endNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void RemoveConnections (GraphNode node) {
|
||||
//TODO, might be better to replace connection
|
||||
node.ClearConnections(true);
|
||||
}
|
||||
|
||||
[ContextMenu("Recalculate neighbours")]
|
||||
void ContextApplyForce () {
|
||||
if (Application.isPlaying) {
|
||||
Apply(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void Apply (bool forceNewCheck) {
|
||||
//TODO
|
||||
//This function assumes that connections from the n1,n2 nodes never need to be removed in the future (e.g because the nodes move or something)
|
||||
NNConstraint nn = NNConstraint.None;
|
||||
int graph = (int)startNode.GraphIndex;
|
||||
|
||||
//Search all graphs but the one which start and end nodes are on
|
||||
nn.graphMask = ~(1 << graph);
|
||||
|
||||
startNode.SetPosition((Int3)StartTransform.position);
|
||||
endNode.SetPosition((Int3)EndTransform.position);
|
||||
|
||||
RemoveConnections(startNode);
|
||||
RemoveConnections(endNode);
|
||||
|
||||
uint cost = (uint)Mathf.RoundToInt(((Int3)(StartTransform.position-EndTransform.position)).costMagnitude*costFactor);
|
||||
startNode.AddConnection(endNode, cost);
|
||||
endNode.AddConnection(startNode, cost);
|
||||
|
||||
if (connectedNode1 == null || forceNewCheck) {
|
||||
var info = AstarPath.active.GetNearest(StartTransform.position, nn);
|
||||
connectedNode1 = info.node;
|
||||
clamped1 = info.position;
|
||||
}
|
||||
|
||||
if (connectedNode2 == null || forceNewCheck) {
|
||||
var info = AstarPath.active.GetNearest(EndTransform.position, nn);
|
||||
connectedNode2 = info.node;
|
||||
clamped2 = info.position;
|
||||
}
|
||||
|
||||
if (connectedNode2 == null || connectedNode1 == null) return;
|
||||
|
||||
//Add connections between nodes, or replace old connections if existing
|
||||
connectedNode1.AddConnection(startNode, (uint)Mathf.RoundToInt(((Int3)(clamped1 - StartTransform.position)).costMagnitude*costFactor));
|
||||
if (!oneWay) connectedNode2.AddConnection(endNode, (uint)Mathf.RoundToInt(((Int3)(clamped2 - EndTransform.position)).costMagnitude*costFactor));
|
||||
|
||||
if (!oneWay) startNode.AddConnection(connectedNode1, (uint)Mathf.RoundToInt(((Int3)(clamped1 - StartTransform.position)).costMagnitude*costFactor));
|
||||
endNode.AddConnection(connectedNode2, (uint)Mathf.RoundToInt(((Int3)(clamped2 - EndTransform.position)).costMagnitude*costFactor));
|
||||
}
|
||||
|
||||
private readonly static Color GizmosColor = new Color(206.0f/255.0f, 136.0f/255.0f, 48.0f/255.0f, 0.5f);
|
||||
private readonly static Color GizmosColorSelected = new Color(235.0f/255.0f, 123.0f/255.0f, 32.0f/255.0f, 1.0f);
|
||||
|
||||
public virtual void OnDrawGizmosSelected () {
|
||||
OnDrawGizmos(true);
|
||||
}
|
||||
|
||||
public void OnDrawGizmos () {
|
||||
OnDrawGizmos(false);
|
||||
}
|
||||
|
||||
public void OnDrawGizmos (bool selected) {
|
||||
Color color = selected ? GizmosColorSelected : GizmosColor;
|
||||
|
||||
if (StartTransform != null) {
|
||||
Draw.Gizmos.CircleXZ(StartTransform.position, 0.4f, color);
|
||||
}
|
||||
if (EndTransform != null) {
|
||||
Draw.Gizmos.CircleXZ(EndTransform.position, 0.4f, color);
|
||||
}
|
||||
|
||||
if (StartTransform != null && EndTransform != null) {
|
||||
Draw.Gizmos.Bezier(StartTransform.position, EndTransform.position, color);
|
||||
if (selected) {
|
||||
Vector3 cross = Vector3.Cross(Vector3.up, (EndTransform.position-StartTransform.position)).normalized;
|
||||
Draw.Gizmos.Bezier(StartTransform.position+cross*0.1f, EndTransform.position+cross*0.1f, color);
|
||||
Draw.Gizmos.Bezier(StartTransform.position-cross*0.1f, EndTransform.position-cross*0.1f, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static void SerializeReferences (Pathfinding.Serialization.GraphSerializationContext ctx) {
|
||||
var links = GetModifiersOfType<NodeLink2>();
|
||||
|
||||
ctx.writer.Write(links.Count);
|
||||
foreach (var link in links) {
|
||||
ctx.writer.Write(link.uniqueID);
|
||||
ctx.SerializeNodeReference(link.startNode);
|
||||
ctx.SerializeNodeReference(link.endNode);
|
||||
ctx.SerializeNodeReference(link.connectedNode1);
|
||||
ctx.SerializeNodeReference(link.connectedNode2);
|
||||
ctx.SerializeVector3(link.clamped1);
|
||||
ctx.SerializeVector3(link.clamped2);
|
||||
ctx.writer.Write(link.postScanCalled);
|
||||
}
|
||||
}
|
||||
|
||||
internal static void DeserializeReferences (Pathfinding.Serialization.GraphSerializationContext ctx) {
|
||||
int count = ctx.reader.ReadInt32();
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
var linkID = ctx.reader.ReadUInt64();
|
||||
var startNode = ctx.DeserializeNodeReference();
|
||||
var endNode = ctx.DeserializeNodeReference();
|
||||
var connectedNode1 = ctx.DeserializeNodeReference();
|
||||
var connectedNode2 = ctx.DeserializeNodeReference();
|
||||
var clamped1 = ctx.DeserializeVector3();
|
||||
var clamped2 = ctx.DeserializeVector3();
|
||||
var postScanCalled = ctx.reader.ReadBoolean();
|
||||
|
||||
GraphModifier link;
|
||||
if (usedIDs.TryGetValue(linkID, out link)) {
|
||||
var link2 = link as NodeLink2;
|
||||
if (link2 != null) {
|
||||
if (startNode != null) reference[startNode] = link2;
|
||||
if (endNode != null) reference[endNode] = link2;
|
||||
|
||||
// If any nodes happened to be registered right now
|
||||
if (link2.startNode != null) reference.Remove(link2.startNode);
|
||||
if (link2.endNode != null) reference.Remove(link2.endNode);
|
||||
|
||||
link2.startNode = startNode as PointNode;
|
||||
link2.endNode = endNode as PointNode;
|
||||
link2.connectedNode1 = connectedNode1;
|
||||
link2.connectedNode2 = connectedNode2;
|
||||
link2.postScanCalled = postScanCalled;
|
||||
link2.clamped1 = clamped1;
|
||||
link2.clamped2 = clamped2;
|
||||
} else {
|
||||
throw new System.Exception("Tried to deserialize a NodeLink2 reference, but the link was not of the correct type or it has been destroyed.\nIf a NodeLink2 is included in serialized graph data, the same NodeLink2 component must be present in the scene when loading the graph data.");
|
||||
}
|
||||
} else {
|
||||
throw new System.Exception("Tried to deserialize a NodeLink2 reference, but the link could not be found in the scene.\nIf a NodeLink2 is included in serialized graph data, the same NodeLink2 component must be present in the scene when loading the graph data.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
8
AR/Assets/AstarPathfindingProject/Core/Misc/NodeLink2.cs.meta
generated
Normal file
8
AR/Assets/AstarPathfindingProject/Core/Misc/NodeLink2.cs.meta
generated
Normal file
@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bd2cfff5dfa8c4244aa00fea9675adb2
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
313
AR/Assets/AstarPathfindingProject/Core/Misc/NodeLink3.cs
Normal file
313
AR/Assets/AstarPathfindingProject/Core/Misc/NodeLink3.cs
Normal file
@ -0,0 +1,313 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding {
|
||||
using Pathfinding.Util;
|
||||
|
||||
public class NodeLink3Node : PointNode {
|
||||
public NodeLink3 link;
|
||||
public Vector3 portalA;
|
||||
public Vector3 portalB;
|
||||
|
||||
public NodeLink3Node (AstarPath active) : base(active) {}
|
||||
|
||||
public override bool GetPortal (GraphNode other, List<Vector3> left, List<Vector3> right, bool backwards) {
|
||||
if (this.connections.Length < 2) return false;
|
||||
|
||||
if (this.connections.Length != 2) throw new System.Exception("Invalid NodeLink3Node. Expected 2 connections, found " + this.connections.Length);
|
||||
|
||||
if (left != null) {
|
||||
left.Add(portalA);
|
||||
right.Add(portalB);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public GraphNode GetOther (GraphNode a) {
|
||||
if (this.connections.Length < 2) return null;
|
||||
if (this.connections.Length != 2) throw new System.Exception("Invalid NodeLink3Node. Expected 2 connections, found " + this.connections.Length);
|
||||
|
||||
return a == connections[0].node ? (connections[1].node as NodeLink3Node).GetOtherInternal(this) : (connections[0].node as NodeLink3Node).GetOtherInternal(this);
|
||||
}
|
||||
|
||||
GraphNode GetOtherInternal (GraphNode a) {
|
||||
if (this.connections.Length < 2) return null;
|
||||
return a == connections[0].node ? connections[1].node : connections[0].node;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connects two TriangleMeshNodes (recast/navmesh graphs) as if they had shared an edge.
|
||||
/// Note: Usually you do not want to use this type of link, you want to use NodeLink2 or NodeLink (sorry for the not so descriptive names).
|
||||
/// </summary>
|
||||
[AddComponentMenu("Pathfinding/Link3")]
|
||||
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_node_link3.php")]
|
||||
public class NodeLink3 : GraphModifier {
|
||||
protected static Dictionary<GraphNode, NodeLink3> reference = new Dictionary<GraphNode, NodeLink3>();
|
||||
public static NodeLink3 GetNodeLink (GraphNode node) {
|
||||
NodeLink3 v;
|
||||
|
||||
reference.TryGetValue(node, out v);
|
||||
return v;
|
||||
}
|
||||
|
||||
/// <summary>End position of the link</summary>
|
||||
public Transform end;
|
||||
|
||||
/// <summary>
|
||||
/// The connection will be this times harder/slower to traverse.
|
||||
/// Note that values lower than one will not always make the pathfinder choose this path instead of another path even though this one should
|
||||
/// lead to a lower total cost unless you also adjust the Heuristic Scale in A* Inspector -> Settings -> Pathfinding or disable the heuristic altogether.
|
||||
/// </summary>
|
||||
public float costFactor = 1.0f;
|
||||
|
||||
/// <summary>Make a one-way connection</summary>
|
||||
public bool oneWay = false;
|
||||
|
||||
public Transform StartTransform {
|
||||
get { return transform; }
|
||||
}
|
||||
|
||||
public Transform EndTransform {
|
||||
get { return end; }
|
||||
}
|
||||
|
||||
NodeLink3Node startNode;
|
||||
NodeLink3Node endNode;
|
||||
MeshNode connectedNode1, connectedNode2;
|
||||
Vector3 clamped1, clamped2;
|
||||
bool postScanCalled = false;
|
||||
|
||||
public GraphNode StartNode {
|
||||
get { return startNode; }
|
||||
}
|
||||
|
||||
public GraphNode EndNode {
|
||||
get { return endNode; }
|
||||
}
|
||||
|
||||
public override void OnPostScan () {
|
||||
if (AstarPath.active.isScanning) {
|
||||
InternalOnPostScan();
|
||||
} else {
|
||||
AstarPath.active.AddWorkItem(new AstarWorkItem(force => {
|
||||
InternalOnPostScan();
|
||||
return true;
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
public void InternalOnPostScan () {
|
||||
#if !ASTAR_NO_POINT_GRAPH
|
||||
if (AstarPath.active.data.pointGraph == null) {
|
||||
AstarPath.active.data.AddGraph(typeof(PointGraph));
|
||||
}
|
||||
|
||||
//Get nearest nodes from the first point graph, assuming both start and end transforms are nodes
|
||||
startNode = AstarPath.active.data.pointGraph.AddNode(new NodeLink3Node(AstarPath.active), (Int3)StartTransform.position);
|
||||
startNode.link = this;
|
||||
endNode = AstarPath.active.data.pointGraph.AddNode(new NodeLink3Node(AstarPath.active), (Int3)EndTransform.position);
|
||||
endNode.link = this;
|
||||
#else
|
||||
throw new System.Exception("Point graphs are not included. Check your A* Optimization settings.");
|
||||
#endif
|
||||
connectedNode1 = null;
|
||||
connectedNode2 = null;
|
||||
|
||||
if (startNode == null || endNode == null) {
|
||||
startNode = null;
|
||||
endNode = null;
|
||||
return;
|
||||
}
|
||||
|
||||
postScanCalled = true;
|
||||
reference[startNode] = this;
|
||||
reference[endNode] = this;
|
||||
Apply(true);
|
||||
}
|
||||
|
||||
public override void OnGraphsPostUpdate () {
|
||||
if (!AstarPath.active.isScanning) {
|
||||
if (connectedNode1 != null && connectedNode1.Destroyed) {
|
||||
connectedNode1 = null;
|
||||
}
|
||||
if (connectedNode2 != null && connectedNode2.Destroyed) {
|
||||
connectedNode2 = null;
|
||||
}
|
||||
|
||||
if (!postScanCalled) {
|
||||
OnPostScan();
|
||||
} else {
|
||||
//OnPostScan will also call this method
|
||||
Apply(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnEnable () {
|
||||
base.OnEnable();
|
||||
|
||||
#if !ASTAR_NO_POINT_GRAPH
|
||||
if (Application.isPlaying && AstarPath.active != null && AstarPath.active.data != null && AstarPath.active.data.pointGraph != null) {
|
||||
OnGraphsPostUpdate();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
protected override void OnDisable () {
|
||||
base.OnDisable();
|
||||
|
||||
postScanCalled = false;
|
||||
|
||||
if (startNode != null) reference.Remove(startNode);
|
||||
if (endNode != null) reference.Remove(endNode);
|
||||
|
||||
if (startNode != null && endNode != null) {
|
||||
startNode.RemoveConnection(endNode);
|
||||
endNode.RemoveConnection(startNode);
|
||||
|
||||
if (connectedNode1 != null && connectedNode2 != null) {
|
||||
startNode.RemoveConnection(connectedNode1);
|
||||
connectedNode1.RemoveConnection(startNode);
|
||||
|
||||
endNode.RemoveConnection(connectedNode2);
|
||||
connectedNode2.RemoveConnection(endNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void RemoveConnections (GraphNode node) {
|
||||
//TODO, might be better to replace connection
|
||||
node.ClearConnections(true);
|
||||
}
|
||||
|
||||
[ContextMenu("Recalculate neighbours")]
|
||||
void ContextApplyForce () {
|
||||
if (Application.isPlaying) {
|
||||
Apply(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void Apply (bool forceNewCheck) {
|
||||
//TODO
|
||||
//This function assumes that connections from the n1,n2 nodes never need to be removed in the future (e.g because the nodes move or something)
|
||||
NNConstraint nn = NNConstraint.None;
|
||||
|
||||
nn.distanceXZ = true;
|
||||
int graph = (int)startNode.GraphIndex;
|
||||
|
||||
//Search all graphs but the one which start and end nodes are on
|
||||
nn.graphMask = ~(1 << graph);
|
||||
|
||||
bool same = true;
|
||||
|
||||
{
|
||||
var info = AstarPath.active.GetNearest(StartTransform.position, nn);
|
||||
same &= info.node == connectedNode1 && info.node != null;
|
||||
connectedNode1 = info.node as MeshNode;
|
||||
clamped1 = info.position;
|
||||
if (connectedNode1 != null) Debug.DrawRay((Vector3)connectedNode1.position, Vector3.up*5, Color.red);
|
||||
}
|
||||
|
||||
{
|
||||
var info = AstarPath.active.GetNearest(EndTransform.position, nn);
|
||||
same &= info.node == connectedNode2 && info.node != null;
|
||||
connectedNode2 = info.node as MeshNode;
|
||||
clamped2 = info.position;
|
||||
if (connectedNode2 != null) Debug.DrawRay((Vector3)connectedNode2.position, Vector3.up*5, Color.cyan);
|
||||
}
|
||||
|
||||
if (connectedNode2 == null || connectedNode1 == null) return;
|
||||
|
||||
startNode.SetPosition((Int3)StartTransform.position);
|
||||
endNode.SetPosition((Int3)EndTransform.position);
|
||||
|
||||
if (same && !forceNewCheck) return;
|
||||
|
||||
RemoveConnections(startNode);
|
||||
RemoveConnections(endNode);
|
||||
|
||||
uint cost = (uint)Mathf.RoundToInt(((Int3)(StartTransform.position-EndTransform.position)).costMagnitude*costFactor);
|
||||
startNode.AddConnection(endNode, cost);
|
||||
endNode.AddConnection(startNode, cost);
|
||||
|
||||
Int3 dir = connectedNode2.position - connectedNode1.position;
|
||||
|
||||
for (int a = 0; a < connectedNode1.GetVertexCount(); a++) {
|
||||
Int3 va1 = connectedNode1.GetVertex(a);
|
||||
Int3 va2 = connectedNode1.GetVertex((a+1) % connectedNode1.GetVertexCount());
|
||||
|
||||
if (Int3.DotLong((va2-va1).Normal2D(), dir) > 0) continue;
|
||||
|
||||
for (int b = 0; b < connectedNode2.GetVertexCount(); b++) {
|
||||
Int3 vb1 = connectedNode2.GetVertex(b);
|
||||
Int3 vb2 = connectedNode2.GetVertex((b+1) % connectedNode2.GetVertexCount());
|
||||
|
||||
if (Int3.DotLong((vb2-vb1).Normal2D(), dir) < 0) continue;
|
||||
|
||||
if (Int3.Angle((vb2-vb1), (va2-va1)) > (170.0/360.0f)*Mathf.PI*2) {
|
||||
float t1 = 0;
|
||||
float t2 = 1;
|
||||
|
||||
t2 = System.Math.Min(t2, VectorMath.ClosestPointOnLineFactor(va1, va2, vb1));
|
||||
t1 = System.Math.Max(t1, VectorMath.ClosestPointOnLineFactor(va1, va2, vb2));
|
||||
|
||||
if (t2 < t1) {
|
||||
Debug.LogError("Something went wrong! " + t1 + " " + t2 + " " + va1 + " " + va2 + " " + vb1 + " " + vb2+"\nTODO, how can this happen?");
|
||||
} else {
|
||||
Vector3 pa = (Vector3)(va2-va1)*t1 + (Vector3)va1;
|
||||
Vector3 pb = (Vector3)(va2-va1)*t2 + (Vector3)va1;
|
||||
|
||||
startNode.portalA = pa;
|
||||
startNode.portalB = pb;
|
||||
|
||||
endNode.portalA = pb;
|
||||
endNode.portalB = pa;
|
||||
|
||||
//Add connections between nodes, or replace old connections if existing
|
||||
connectedNode1.AddConnection(startNode, (uint)Mathf.RoundToInt(((Int3)(clamped1 - StartTransform.position)).costMagnitude*costFactor));
|
||||
connectedNode2.AddConnection(endNode, (uint)Mathf.RoundToInt(((Int3)(clamped2 - EndTransform.position)).costMagnitude*costFactor));
|
||||
|
||||
startNode.AddConnection(connectedNode1, (uint)Mathf.RoundToInt(((Int3)(clamped1 - StartTransform.position)).costMagnitude*costFactor));
|
||||
endNode.AddConnection(connectedNode2, (uint)Mathf.RoundToInt(((Int3)(clamped2 - EndTransform.position)).costMagnitude*costFactor));
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private readonly static Color GizmosColor = new Color(206.0f/255.0f, 136.0f/255.0f, 48.0f/255.0f, 0.5f);
|
||||
private readonly static Color GizmosColorSelected = new Color(235.0f/255.0f, 123.0f/255.0f, 32.0f/255.0f, 1.0f);
|
||||
|
||||
public virtual void OnDrawGizmosSelected () {
|
||||
OnDrawGizmos(true);
|
||||
}
|
||||
|
||||
public void OnDrawGizmos () {
|
||||
OnDrawGizmos(false);
|
||||
}
|
||||
|
||||
public void OnDrawGizmos (bool selected) {
|
||||
Color col = selected ? GizmosColorSelected : GizmosColor;
|
||||
|
||||
if (StartTransform != null) {
|
||||
Draw.Gizmos.CircleXZ(StartTransform.position, 0.4f, col);
|
||||
}
|
||||
if (EndTransform != null) {
|
||||
Draw.Gizmos.CircleXZ(EndTransform.position, 0.4f, col);
|
||||
}
|
||||
|
||||
if (StartTransform != null && EndTransform != null) {
|
||||
Draw.Gizmos.Bezier(StartTransform.position, EndTransform.position, col);
|
||||
if (selected) {
|
||||
Vector3 cross = Vector3.Cross(Vector3.up, (EndTransform.position-StartTransform.position)).normalized;
|
||||
Draw.Gizmos.Bezier(StartTransform.position+cross*0.1f, EndTransform.position+cross*0.1f, col);
|
||||
Draw.Gizmos.Bezier(StartTransform.position-cross*0.1f, EndTransform.position-cross*0.1f, col);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
8
AR/Assets/AstarPathfindingProject/Core/Misc/NodeLink3.cs.meta
generated
Normal file
8
AR/Assets/AstarPathfindingProject/Core/Misc/NodeLink3.cs.meta
generated
Normal file
@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3850d0dc2bead45568e6b5bbcc011606
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
131
AR/Assets/AstarPathfindingProject/Core/Misc/ObjectPool.cs
Normal file
131
AR/Assets/AstarPathfindingProject/Core/Misc/ObjectPool.cs
Normal file
@ -0,0 +1,131 @@
|
||||
#if !UNITY_EDITOR
|
||||
// Extra optimizations when not running in the editor, but less error checking
|
||||
#define ASTAR_OPTIMIZE_POOLING
|
||||
#endif
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding.Util {
|
||||
public interface IAstarPooledObject {
|
||||
void OnEnterPool();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lightweight object Pool for IAstarPooledObject.
|
||||
/// Handy class for pooling objects of type T which implements the IAstarPooledObject interface.
|
||||
///
|
||||
/// Usage:
|
||||
/// - Claim a new object using <code> SomeClass foo = ObjectPool<SomeClass>.Claim (); </code>
|
||||
/// - Use it and do stuff with it
|
||||
/// - Release it with <code> ObjectPool<SomeClass>.Release (foo); </code>
|
||||
///
|
||||
/// After you have released a object, you should never use it again.
|
||||
///
|
||||
/// \since Version 3.2
|
||||
/// Version: Since 3.7.6 this class is thread safe
|
||||
/// See: Pathfinding.Util.ListPool
|
||||
/// See: ObjectPoolSimple
|
||||
/// </summary>
|
||||
public static class ObjectPool<T> where T : class, IAstarPooledObject, new(){
|
||||
public static T Claim () {
|
||||
return ObjectPoolSimple<T>.Claim();
|
||||
}
|
||||
|
||||
public static void Release (ref T obj) {
|
||||
obj.OnEnterPool();
|
||||
ObjectPoolSimple<T>.Release(ref obj);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lightweight object Pool.
|
||||
/// Handy class for pooling objects of type T.
|
||||
///
|
||||
/// Usage:
|
||||
/// - Claim a new object using <code> SomeClass foo = ObjectPool<SomeClass>.Claim (); </code>
|
||||
/// - Use it and do stuff with it
|
||||
/// - Release it with <code> ObjectPool<SomeClass>.Release (foo); </code>
|
||||
///
|
||||
/// After you have released a object, you should never use it again.
|
||||
///
|
||||
/// \since Version 3.2
|
||||
/// Version: Since 3.7.6 this class is thread safe
|
||||
/// See: Pathfinding.Util.ListPool
|
||||
/// See: ObjectPool
|
||||
/// </summary>
|
||||
public static class ObjectPoolSimple<T> where T : class, new(){
|
||||
/// <summary>Internal pool</summary>
|
||||
static List<T> pool = new List<T>();
|
||||
|
||||
#if !ASTAR_NO_POOLING
|
||||
static readonly HashSet<T> inPool = new HashSet<T>();
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Claim a object.
|
||||
/// Returns a pooled object if any are in the pool.
|
||||
/// Otherwise it creates a new one.
|
||||
/// After usage, this object should be released using the Release function (though not strictly necessary).
|
||||
/// </summary>
|
||||
public static T Claim () {
|
||||
#if ASTAR_NO_POOLING
|
||||
return new T();
|
||||
#else
|
||||
lock (pool) {
|
||||
if (pool.Count > 0) {
|
||||
T ls = pool[pool.Count-1];
|
||||
pool.RemoveAt(pool.Count-1);
|
||||
inPool.Remove(ls);
|
||||
return ls;
|
||||
} else {
|
||||
return new T();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases an object.
|
||||
/// After the object has been released it should not be used anymore.
|
||||
/// The variable will be set to null to prevent silly mistakes.
|
||||
///
|
||||
/// \throws System.InvalidOperationException
|
||||
/// Releasing an object when it has already been released will cause an exception to be thrown.
|
||||
/// However enabling ASTAR_OPTIMIZE_POOLING will prevent this check.
|
||||
///
|
||||
/// See: Claim
|
||||
/// </summary>
|
||||
public static void Release (ref T obj) {
|
||||
#if !ASTAR_NO_POOLING
|
||||
lock (pool) {
|
||||
#if !ASTAR_OPTIMIZE_POOLING
|
||||
if (!inPool.Add(obj)) {
|
||||
throw new InvalidOperationException("You are trying to pool an object twice. Please make sure that you only pool it once.");
|
||||
}
|
||||
#endif
|
||||
pool.Add(obj);
|
||||
}
|
||||
#endif
|
||||
obj = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the pool for objects of this type.
|
||||
/// This is an O(n) operation, where n is the number of pooled objects.
|
||||
/// </summary>
|
||||
public static void Clear () {
|
||||
lock (pool) {
|
||||
#if !ASTAR_OPTIMIZE_POOLING && !ASTAR_NO_POOLING
|
||||
inPool.Clear();
|
||||
#endif
|
||||
pool.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Number of objects of this type in the pool</summary>
|
||||
public static int GetSize () {
|
||||
return pool.Count;
|
||||
}
|
||||
}
|
||||
}
|
7
AR/Assets/AstarPathfindingProject/Core/Misc/ObjectPool.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/Misc/ObjectPool.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 10837c5b030bd47a2a0e6e213fea0868
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
206
AR/Assets/AstarPathfindingProject/Core/Misc/PathInterpolator.cs
Normal file
206
AR/Assets/AstarPathfindingProject/Core/Misc/PathInterpolator.cs
Normal file
@ -0,0 +1,206 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding.Util {
|
||||
/// <summary>Interpolates along a sequence of points</summary>
|
||||
public class PathInterpolator {
|
||||
List<Vector3> path;
|
||||
|
||||
float distanceToSegmentStart;
|
||||
float currentDistance;
|
||||
float currentSegmentLength = float.PositiveInfinity;
|
||||
float totalDistance = float.PositiveInfinity;
|
||||
|
||||
/// <summary>Current position</summary>
|
||||
public virtual Vector3 position {
|
||||
get {
|
||||
float t = currentSegmentLength > 0.0001f ? (currentDistance - distanceToSegmentStart) / currentSegmentLength : 0f;
|
||||
return Vector3.Lerp(path[segmentIndex], path[segmentIndex+1], t);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Last point in the path</summary>
|
||||
public Vector3 endPoint {
|
||||
get {
|
||||
return path[path.Count-1];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tangent of the curve at the current position</summary>
|
||||
public Vector3 tangent {
|
||||
get {
|
||||
return path[segmentIndex+1] - path[segmentIndex];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Remaining distance until the end of the path</summary>
|
||||
public float remainingDistance {
|
||||
get {
|
||||
return totalDistance - distance;
|
||||
}
|
||||
set {
|
||||
distance = totalDistance - value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Traversed distance from the start of the path</summary>
|
||||
public float distance {
|
||||
get {
|
||||
return currentDistance;
|
||||
}
|
||||
set {
|
||||
currentDistance = value;
|
||||
|
||||
while (currentDistance < distanceToSegmentStart && segmentIndex > 0) PrevSegment();
|
||||
while (currentDistance > distanceToSegmentStart + currentSegmentLength && segmentIndex < path.Count - 2) NextSegment();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Current segment.
|
||||
/// The start and end points of the segment are path[value] and path[value+1].
|
||||
/// </summary>
|
||||
public int segmentIndex { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// True if this instance has a path set.
|
||||
/// See: SetPath
|
||||
/// </summary>
|
||||
public bool valid {
|
||||
get {
|
||||
return path != null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Appends the remaining path between <see cref="position"/> and <see cref="endPoint"/> to buffer</summary>
|
||||
public void GetRemainingPath (List<Vector3> buffer) {
|
||||
if (!valid) throw new System.Exception("PathInterpolator is not valid");
|
||||
buffer.Add(position);
|
||||
for (int i = segmentIndex+1; i < path.Count; i++) {
|
||||
buffer.Add(path[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set the path to interpolate along.
|
||||
/// This will reset all interpolation variables.
|
||||
/// </summary>
|
||||
public void SetPath (List<Vector3> path) {
|
||||
this.path = path;
|
||||
currentDistance = 0;
|
||||
segmentIndex = 0;
|
||||
distanceToSegmentStart = 0;
|
||||
|
||||
if (path == null) {
|
||||
totalDistance = float.PositiveInfinity;
|
||||
currentSegmentLength = float.PositiveInfinity;
|
||||
return;
|
||||
}
|
||||
|
||||
if (path.Count < 2) throw new System.ArgumentException("Path must have a length of at least 2");
|
||||
|
||||
currentSegmentLength = (path[1] - path[0]).magnitude;
|
||||
totalDistance = 0f;
|
||||
|
||||
var prev = path[0];
|
||||
for (int i = 1; i < path.Count; i++) {
|
||||
var current = path[i];
|
||||
totalDistance += (current - prev).magnitude;
|
||||
prev = current;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Move to the specified segment and move a fraction of the way to the next segment</summary>
|
||||
public void MoveToSegment (int index, float fractionAlongSegment) {
|
||||
if (path == null) return;
|
||||
if (index < 0 || index >= path.Count - 1) throw new System.ArgumentOutOfRangeException("index");
|
||||
while (segmentIndex > index) PrevSegment();
|
||||
while (segmentIndex < index) NextSegment();
|
||||
distance = distanceToSegmentStart + Mathf.Clamp01(fractionAlongSegment) * currentSegmentLength;
|
||||
}
|
||||
|
||||
/// <summary>Move as close as possible to the specified point</summary>
|
||||
public void MoveToClosestPoint (Vector3 point) {
|
||||
if (path == null) return;
|
||||
|
||||
float bestDist = float.PositiveInfinity;
|
||||
float bestFactor = 0f;
|
||||
int bestIndex = 0;
|
||||
|
||||
for (int i = 0; i < path.Count-1; i++) {
|
||||
float factor = VectorMath.ClosestPointOnLineFactor(path[i], path[i+1], point);
|
||||
Vector3 closest = Vector3.Lerp(path[i], path[i+1], factor);
|
||||
float dist = (point - closest).sqrMagnitude;
|
||||
|
||||
if (dist < bestDist) {
|
||||
bestDist = dist;
|
||||
bestFactor = factor;
|
||||
bestIndex = i;
|
||||
}
|
||||
}
|
||||
|
||||
MoveToSegment(bestIndex, bestFactor);
|
||||
}
|
||||
|
||||
public void MoveToLocallyClosestPoint (Vector3 point, bool allowForwards = true, bool allowBackwards = true) {
|
||||
if (path == null) return;
|
||||
|
||||
while (allowForwards && segmentIndex < path.Count - 2 && (path[segmentIndex+1] - point).sqrMagnitude <= (path[segmentIndex] - point).sqrMagnitude) {
|
||||
NextSegment();
|
||||
}
|
||||
|
||||
while (allowBackwards && segmentIndex > 0 && (path[segmentIndex-1] - point).sqrMagnitude <= (path[segmentIndex] - point).sqrMagnitude) {
|
||||
PrevSegment();
|
||||
}
|
||||
|
||||
// Check the distances to the two segments extending from the vertex path[segmentIndex]
|
||||
// and pick the position on those segments that is closest to the #point parameter.
|
||||
float factor1 = 0, factor2 = 0, d1 = float.PositiveInfinity, d2 = float.PositiveInfinity;
|
||||
if (segmentIndex > 0) {
|
||||
factor1 = VectorMath.ClosestPointOnLineFactor(path[segmentIndex-1], path[segmentIndex], point);
|
||||
d1 = (Vector3.Lerp(path[segmentIndex-1], path[segmentIndex], factor1) - point).sqrMagnitude;
|
||||
}
|
||||
|
||||
if (segmentIndex < path.Count - 1) {
|
||||
factor2 = VectorMath.ClosestPointOnLineFactor(path[segmentIndex], path[segmentIndex+1], point);
|
||||
d2 = (Vector3.Lerp(path[segmentIndex], path[segmentIndex+1], factor2) - point).sqrMagnitude;
|
||||
}
|
||||
|
||||
if (d1 < d2) MoveToSegment(segmentIndex - 1, factor1);
|
||||
else MoveToSegment(segmentIndex, factor2);
|
||||
}
|
||||
|
||||
public void MoveToCircleIntersection2D (Vector3 circleCenter3D, float radius, IMovementPlane transform) {
|
||||
if (path == null) return;
|
||||
|
||||
// Move forwards as long as we are getting closer to circleCenter3D
|
||||
while (segmentIndex < path.Count - 2 && VectorMath.ClosestPointOnLineFactor(path[segmentIndex], path[segmentIndex+1], circleCenter3D) > 1) {
|
||||
NextSegment();
|
||||
}
|
||||
|
||||
var circleCenter = transform.ToPlane(circleCenter3D);
|
||||
|
||||
// Move forwards as long as the current segment endpoint is within the circle
|
||||
while (segmentIndex < path.Count - 2 && (transform.ToPlane(path[segmentIndex+1]) - circleCenter).sqrMagnitude <= radius*radius) {
|
||||
NextSegment();
|
||||
}
|
||||
|
||||
// Calculate the intersection with the circle. This involves some math.
|
||||
var factor = VectorMath.LineCircleIntersectionFactor(circleCenter, transform.ToPlane(path[segmentIndex]), transform.ToPlane(path[segmentIndex+1]), radius);
|
||||
// Move to the intersection point
|
||||
MoveToSegment(segmentIndex, factor);
|
||||
}
|
||||
|
||||
protected virtual void PrevSegment () {
|
||||
segmentIndex--;
|
||||
currentSegmentLength = (path[segmentIndex+1] - path[segmentIndex]).magnitude;
|
||||
distanceToSegmentStart -= currentSegmentLength;
|
||||
}
|
||||
|
||||
protected virtual void NextSegment () {
|
||||
segmentIndex++;
|
||||
distanceToSegmentStart += currentSegmentLength;
|
||||
currentSegmentLength = (path[segmentIndex+1] - path[segmentIndex]).magnitude;
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/Misc/PathInterpolator.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/Misc/PathInterpolator.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9c0392dbc5e744ee28e7b9ee81aea1e2
|
||||
timeCreated: 1490125383
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
88
AR/Assets/AstarPathfindingProject/Core/Misc/PathPool.cs
Normal file
88
AR/Assets/AstarPathfindingProject/Core/Misc/PathPool.cs
Normal file
@ -0,0 +1,88 @@
|
||||
//#define ASTAR_NO_POOLING // Disable pooling for some reason. Maybe for debugging or just for measuring the difference.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding {
|
||||
/// <summary>Pools path objects to reduce load on the garbage collector</summary>
|
||||
public static class PathPool {
|
||||
static readonly Dictionary<Type, Stack<Path> > pool = new Dictionary<Type, Stack<Path> >();
|
||||
static readonly Dictionary<Type, int> totalCreated = new Dictionary<Type, int>();
|
||||
|
||||
/// <summary>
|
||||
/// Adds a path to the pool.
|
||||
/// This function should not be used directly. Instead use the Path.Claim and Path.Release functions.
|
||||
/// </summary>
|
||||
public static void Pool (Path path) {
|
||||
#if !ASTAR_NO_POOLING
|
||||
lock (pool) {
|
||||
if (((IPathInternals)path).Pooled) {
|
||||
throw new System.ArgumentException("The path is already pooled.");
|
||||
}
|
||||
|
||||
Stack<Path> poolStack;
|
||||
if (!pool.TryGetValue(path.GetType(), out poolStack)) {
|
||||
poolStack = new Stack<Path>();
|
||||
pool[path.GetType()] = poolStack;
|
||||
}
|
||||
|
||||
((IPathInternals)path).Pooled = true;
|
||||
((IPathInternals)path).OnEnterPool();
|
||||
poolStack.Push(path);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>Total created instances of paths of the specified type</summary>
|
||||
public static int GetTotalCreated (Type type) {
|
||||
int created;
|
||||
|
||||
if (totalCreated.TryGetValue(type, out created)) {
|
||||
return created;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Number of pooled instances of a path of the specified type</summary>
|
||||
public static int GetSize (Type type) {
|
||||
Stack<Path> poolStack;
|
||||
|
||||
if (pool.TryGetValue(type, out poolStack)) {
|
||||
return poolStack.Count;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Get a path from the pool or create a new one if the pool is empty</summary>
|
||||
public static T GetPath<T>() where T : Path, new() {
|
||||
#if ASTAR_NO_POOLING
|
||||
T result = new T();
|
||||
((IPathInternals)result).Reset();
|
||||
return result;
|
||||
#else
|
||||
lock (pool) {
|
||||
T result;
|
||||
Stack<Path> poolStack;
|
||||
if (pool.TryGetValue(typeof(T), out poolStack) && poolStack.Count > 0) {
|
||||
// Guaranteed to have the correct type
|
||||
result = poolStack.Pop() as T;
|
||||
} else {
|
||||
result = new T();
|
||||
|
||||
// Make sure an entry for the path type exists
|
||||
if (!totalCreated.ContainsKey(typeof(T))) {
|
||||
totalCreated[typeof(T)] = 0;
|
||||
}
|
||||
|
||||
totalCreated[typeof(T)]++;
|
||||
}
|
||||
|
||||
((IPathInternals)result).Pooled = false;
|
||||
((IPathInternals)result).Reset();
|
||||
return result;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
7
AR/Assets/AstarPathfindingProject/Core/Misc/PathPool.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/Misc/PathPool.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cefe1014ab62848a89016fb97b1f8f7b
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
587
AR/Assets/AstarPathfindingProject/Core/Misc/PathProcessor.cs
Normal file
587
AR/Assets/AstarPathfindingProject/Core/Misc/PathProcessor.cs
Normal file
@ -0,0 +1,587 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
#if UNITY_5_5_OR_NEWER
|
||||
using UnityEngine.Profiling;
|
||||
#endif
|
||||
|
||||
namespace Pathfinding {
|
||||
#if NETFX_CORE
|
||||
using Thread = Pathfinding.WindowsStore.Thread;
|
||||
#else
|
||||
using Thread = System.Threading.Thread;
|
||||
#endif
|
||||
|
||||
public class PathProcessor {
|
||||
public event System.Action<Path> OnPathPreSearch;
|
||||
public event System.Action<Path> OnPathPostSearch;
|
||||
public event System.Action OnQueueUnblocked;
|
||||
|
||||
internal readonly ThreadControlQueue queue;
|
||||
readonly AstarPath astar;
|
||||
readonly PathReturnQueue returnQueue;
|
||||
|
||||
readonly PathHandler[] pathHandlers;
|
||||
|
||||
/// <summary>References to each of the pathfinding threads</summary>
|
||||
readonly Thread[] threads;
|
||||
|
||||
/// <summary>
|
||||
/// When no multithreading is used, the IEnumerator is stored here.
|
||||
/// When no multithreading is used, a coroutine is used instead. It is not directly called with StartCoroutine
|
||||
/// but a separate function has just a while loop which increments the main IEnumerator.
|
||||
/// This is done so other functions can step the thread forward at any time, without having to wait for Unity to update it.
|
||||
/// See: CalculatePaths
|
||||
/// See: CalculatePathsHandler
|
||||
/// </summary>
|
||||
IEnumerator threadCoroutine;
|
||||
|
||||
/// <summary>
|
||||
/// Holds the next node index which has not been used by any previous node.
|
||||
/// See: nodeIndexPool
|
||||
/// </summary>
|
||||
int nextNodeIndex = 1;
|
||||
|
||||
/// <summary>
|
||||
/// Holds indices for nodes that have been destroyed.
|
||||
/// To avoid trashing a lot of memory structures when nodes are
|
||||
/// frequently deleted and created, node indices are reused.
|
||||
/// </summary>
|
||||
readonly Stack<int> nodeIndexPool = new Stack<int>();
|
||||
|
||||
readonly List<int> locks = new List<int>();
|
||||
int nextLockID = 0;
|
||||
|
||||
#if UNITY_2017_3_OR_NEWER
|
||||
CustomSampler profilingSampler;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Number of parallel pathfinders.
|
||||
/// Returns the number of concurrent processes which can calculate paths at once.
|
||||
/// When using multithreading, this will be the number of threads, if not using multithreading it is always 1 (since only 1 coroutine is used).
|
||||
/// See: threadInfos
|
||||
/// See: IsUsingMultithreading
|
||||
/// </summary>
|
||||
public int NumThreads {
|
||||
get {
|
||||
return pathHandlers.Length;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Returns whether or not multithreading is used</summary>
|
||||
public bool IsUsingMultithreading {
|
||||
get {
|
||||
return threads != null;
|
||||
}
|
||||
}
|
||||
|
||||
internal PathProcessor (AstarPath astar, PathReturnQueue returnQueue, int processors, bool multithreaded) {
|
||||
this.astar = astar;
|
||||
this.returnQueue = returnQueue;
|
||||
|
||||
if (processors < 0) {
|
||||
throw new System.ArgumentOutOfRangeException("processors");
|
||||
}
|
||||
|
||||
if (!multithreaded && processors != 1) {
|
||||
throw new System.Exception("Only a single non-multithreaded processor is allowed");
|
||||
}
|
||||
|
||||
// Set up path queue with the specified number of receivers
|
||||
queue = new ThreadControlQueue(processors);
|
||||
pathHandlers = new PathHandler[processors];
|
||||
|
||||
for (int i = 0; i < processors; i++) {
|
||||
pathHandlers[i] = new PathHandler(i, processors);
|
||||
}
|
||||
|
||||
if (multithreaded) {
|
||||
#if UNITY_2017_3_OR_NEWER
|
||||
profilingSampler = CustomSampler.Create("Calculating Path");
|
||||
#endif
|
||||
|
||||
threads = new Thread[processors];
|
||||
|
||||
// Start lots of threads
|
||||
for (int i = 0; i < processors; i++) {
|
||||
var pathHandler = pathHandlers[i];
|
||||
threads[i] = new Thread(() => CalculatePathsThreaded(pathHandler));
|
||||
#if !UNITY_SWITCH || UNITY_EDITOR
|
||||
// Note: Setting the thread name seems to crash when deploying for Switch: https://forum.arongranberg.com/t/path-processor-crashing-nintendo-switch-build/6584
|
||||
threads[i].Name = "Pathfinding Thread " + i;
|
||||
#endif
|
||||
threads[i].IsBackground = true;
|
||||
threads[i].Start();
|
||||
}
|
||||
} else {
|
||||
// Start coroutine if not using multithreading
|
||||
threadCoroutine = CalculatePaths(pathHandlers[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Prevents pathfinding from running while held</summary>
|
||||
public struct GraphUpdateLock {
|
||||
PathProcessor pathProcessor;
|
||||
int id;
|
||||
|
||||
public GraphUpdateLock (PathProcessor pathProcessor, bool block) {
|
||||
this.pathProcessor = pathProcessor;
|
||||
id = pathProcessor.Lock(block);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True while this lock is preventing the pathfinding threads from processing more paths.
|
||||
/// Note that the pathfinding threads may not be paused yet (if this lock was obtained using PausePathfinding(false)).
|
||||
/// </summary>
|
||||
public bool Held {
|
||||
get {
|
||||
return pathProcessor != null && pathProcessor.locks.Contains(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Allow pathfinding to start running again if no other locks are still held</summary>
|
||||
public void Release () {
|
||||
pathProcessor.Unlock(id);
|
||||
}
|
||||
}
|
||||
|
||||
int Lock (bool block) {
|
||||
queue.Block();
|
||||
|
||||
if (block) {
|
||||
while (!queue.AllReceiversBlocked) {
|
||||
if (IsUsingMultithreading) {
|
||||
Thread.Sleep(1);
|
||||
} else {
|
||||
TickNonMultithreaded();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
nextLockID++;
|
||||
locks.Add(nextLockID);
|
||||
return nextLockID;
|
||||
}
|
||||
|
||||
void Unlock (int id) {
|
||||
if (!locks.Remove(id)) {
|
||||
throw new System.ArgumentException("This lock has already been released");
|
||||
}
|
||||
|
||||
// Check if there are no remaining active locks
|
||||
if (locks.Count == 0) {
|
||||
if (OnQueueUnblocked != null) OnQueueUnblocked();
|
||||
|
||||
queue.Unblock();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prevents pathfinding threads from starting to calculate any new paths.
|
||||
///
|
||||
/// Returns: A lock object. You need to call Unlock on that object to allow pathfinding to resume.
|
||||
///
|
||||
/// Note: In most cases this should not be called from user code.
|
||||
/// </summary>
|
||||
/// <param name="block">If true, this call will block until all pathfinding threads are paused.
|
||||
/// otherwise the threads will be paused as soon as they are done with what they are currently doing.</param>
|
||||
public GraphUpdateLock PausePathfinding (bool block) {
|
||||
return new GraphUpdateLock(this, block);
|
||||
}
|
||||
|
||||
public void TickNonMultithreaded () {
|
||||
// Process paths
|
||||
if (threadCoroutine != null) {
|
||||
try {
|
||||
threadCoroutine.MoveNext();
|
||||
} catch (System.Exception e) {
|
||||
//This will kill pathfinding
|
||||
threadCoroutine = null;
|
||||
|
||||
// Queue termination exceptions should be ignored, they are supposed to kill the thread
|
||||
if (!(e is ThreadControlQueue.QueueTerminationException)) {
|
||||
Debug.LogException(e);
|
||||
Debug.LogError("Unhandled exception during pathfinding. Terminating.");
|
||||
queue.TerminateReceivers();
|
||||
|
||||
// This will throw an exception supposed to kill the thread
|
||||
try {
|
||||
queue.PopNoBlock(false);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Calls 'Join' on each of the threads to block until they have completed</summary>
|
||||
public void JoinThreads () {
|
||||
if (threads != null) {
|
||||
for (int i = 0; i < threads.Length; i++) {
|
||||
if (!threads[i].Join(200)) {
|
||||
Debug.LogError("Could not terminate pathfinding thread["+i+"] in 200ms, trying Thread.Abort");
|
||||
threads[i].Abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Calls 'Abort' on each of the threads</summary>
|
||||
public void AbortThreads () {
|
||||
if (threads == null) return;
|
||||
for (int i = 0; i < threads.Length; i++) {
|
||||
if (threads[i] != null && threads[i].IsAlive) threads[i].Abort();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a new global node index.
|
||||
/// Warning: This method should not be called directly. It is used by the GraphNode constructor.
|
||||
/// </summary>
|
||||
public int GetNewNodeIndex () {
|
||||
return nodeIndexPool.Count > 0 ? nodeIndexPool.Pop() : nextNodeIndex++;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes temporary path data for a node.
|
||||
/// Warning: This method should not be called directly. It is used by the GraphNode constructor.
|
||||
/// </summary>
|
||||
public void InitializeNode (GraphNode node) {
|
||||
if (!queue.AllReceiversBlocked) {
|
||||
throw new System.Exception("Trying to initialize a node when it is not safe to initialize any nodes. Must be done during a graph update. See http://arongranberg.com/astar/docs/graph-updates.php#direct");
|
||||
}
|
||||
|
||||
for (int i = 0; i < pathHandlers.Length; i++) {
|
||||
pathHandlers[i].InitializeNode(node);
|
||||
}
|
||||
|
||||
astar.hierarchicalGraph.OnCreatedNode(node);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Destroyes the given node.
|
||||
/// This is to be called after the node has been disconnected from the graph so that it cannot be reached from any other nodes.
|
||||
/// It should only be called during graph updates, that is when the pathfinding threads are either not running or paused.
|
||||
///
|
||||
/// Warning: This method should not be called by user code. It is used internally by the system.
|
||||
/// </summary>
|
||||
public void DestroyNode (GraphNode node) {
|
||||
if (node.NodeIndex == -1) return;
|
||||
|
||||
nodeIndexPool.Push(node.NodeIndex);
|
||||
|
||||
for (int i = 0; i < pathHandlers.Length; i++) {
|
||||
pathHandlers[i].DestroyNode(node);
|
||||
}
|
||||
|
||||
astar.hierarchicalGraph.AddDirtyNode(node);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Main pathfinding method (multithreaded).
|
||||
/// This method will calculate the paths in the pathfinding queue when multithreading is enabled.
|
||||
///
|
||||
/// See: CalculatePaths
|
||||
/// See: StartPath
|
||||
/// </summary>
|
||||
void CalculatePathsThreaded (PathHandler pathHandler) {
|
||||
#if UNITY_2017_3_OR_NEWER
|
||||
UnityEngine.Profiling.Profiler.BeginThreadProfiling("Pathfinding", "Pathfinding thread #" + (pathHandler.threadID+1));
|
||||
#endif
|
||||
|
||||
#if !ASTAR_FAST_BUT_NO_EXCEPTIONS
|
||||
try {
|
||||
#endif
|
||||
|
||||
// Max number of ticks we are allowed to continue working in one run.
|
||||
// One tick is 1/10000 of a millisecond.
|
||||
// We need to check once in a while if the thread should be stopped.
|
||||
long maxTicks = (long)(10*10000);
|
||||
long targetTick = System.DateTime.UtcNow.Ticks + maxTicks;
|
||||
while (true) {
|
||||
// The path we are currently calculating
|
||||
Path path = queue.Pop();
|
||||
#if UNITY_2017_3_OR_NEWER
|
||||
profilingSampler.Begin();
|
||||
#endif
|
||||
// Access the internal implementation methods
|
||||
IPathInternals ipath = (IPathInternals)path;
|
||||
|
||||
// Trying to prevent simple modding to allow more than one thread
|
||||
if (pathHandler.threadID > 0) {
|
||||
throw new System.Exception("Thread Error");
|
||||
}
|
||||
|
||||
AstarProfiler.StartFastProfile(0);
|
||||
ipath.PrepareBase(pathHandler);
|
||||
|
||||
// Now processing the path
|
||||
// Will advance to Processing
|
||||
ipath.AdvanceState(PathState.Processing);
|
||||
|
||||
// Call some callbacks
|
||||
if (OnPathPreSearch != null) {
|
||||
OnPathPreSearch(path);
|
||||
}
|
||||
|
||||
// Tick for when the path started, used for calculating how long time the calculation took
|
||||
long startTicks = System.DateTime.UtcNow.Ticks;
|
||||
|
||||
// Prepare the path
|
||||
ipath.Prepare();
|
||||
|
||||
AstarProfiler.EndFastProfile(0);
|
||||
|
||||
if (path.CompleteState == PathCompleteState.NotCalculated) {
|
||||
// For visualization purposes, we set the last computed path to p, so we can view debug info on it in the editor (scene view).
|
||||
astar.debugPathData = ipath.PathHandler;
|
||||
astar.debugPathID = path.pathID;
|
||||
|
||||
AstarProfiler.StartFastProfile(1);
|
||||
|
||||
// Initialize the path, now ready to begin search
|
||||
ipath.Initialize();
|
||||
|
||||
AstarProfiler.EndFastProfile(1);
|
||||
|
||||
// Loop while the path has not been fully calculated
|
||||
while (path.CompleteState == PathCompleteState.NotCalculated) {
|
||||
// Do some work on the path calculation.
|
||||
// The function will return when it has taken too much time
|
||||
// or when it has finished calculation
|
||||
AstarProfiler.StartFastProfile(2);
|
||||
ipath.CalculateStep(targetTick);
|
||||
AstarProfiler.EndFastProfile(2);
|
||||
|
||||
targetTick = System.DateTime.UtcNow.Ticks + maxTicks;
|
||||
|
||||
// Cancel function (and thus the thread) if no more paths should be accepted.
|
||||
// This is done when the A* object is about to be destroyed
|
||||
// The path is returned and then this function will be terminated
|
||||
if (queue.IsTerminating) {
|
||||
path.FailWithError("AstarPath object destroyed");
|
||||
}
|
||||
}
|
||||
|
||||
path.duration = (System.DateTime.UtcNow.Ticks - startTicks)*0.0001F;
|
||||
|
||||
#if ProfileAstar
|
||||
System.Threading.Interlocked.Increment(ref AstarPath.PathsCompleted);
|
||||
System.Threading.Interlocked.Add(ref AstarPath.TotalSearchTime, System.DateTime.UtcNow.Ticks - startTicks);
|
||||
#endif
|
||||
}
|
||||
|
||||
// Cleans up node tagging and other things
|
||||
ipath.Cleanup();
|
||||
|
||||
AstarProfiler.StartFastProfile(9);
|
||||
|
||||
if (path.immediateCallback != null) path.immediateCallback(path);
|
||||
|
||||
if (OnPathPostSearch != null) {
|
||||
OnPathPostSearch(path);
|
||||
}
|
||||
|
||||
// Push the path onto the return stack
|
||||
// It will be detected by the main Unity thread and returned as fast as possible (the next late update hopefully)
|
||||
returnQueue.Enqueue(path);
|
||||
|
||||
// Will advance to ReturnQueue
|
||||
ipath.AdvanceState(PathState.ReturnQueue);
|
||||
|
||||
AstarProfiler.EndFastProfile(9);
|
||||
#if UNITY_2017_3_OR_NEWER
|
||||
profilingSampler.End();
|
||||
#endif
|
||||
}
|
||||
#if !ASTAR_FAST_BUT_NO_EXCEPTIONS
|
||||
}
|
||||
catch (System.Exception e) {
|
||||
#if !NETFX_CORE
|
||||
if (e is ThreadAbortException || e is ThreadControlQueue.QueueTerminationException)
|
||||
#else
|
||||
if (e is ThreadControlQueue.QueueTerminationException)
|
||||
#endif
|
||||
{
|
||||
if (astar.logPathResults == PathLog.Heavy)
|
||||
Debug.LogWarning("Shutting down pathfinding thread #" + pathHandler.threadID);
|
||||
return;
|
||||
}
|
||||
Debug.LogException(e);
|
||||
Debug.LogError("Unhandled exception during pathfinding. Terminating.");
|
||||
// Unhandled exception, kill pathfinding
|
||||
queue.TerminateReceivers();
|
||||
} finally {
|
||||
#if UNITY_2017_3_OR_NEWER
|
||||
UnityEngine.Profiling.Profiler.EndThreadProfiling();
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
Debug.LogError("Error : This part should never be reached.");
|
||||
queue.ReceiverTerminated();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Main pathfinding method.
|
||||
/// This method will calculate the paths in the pathfinding queue.
|
||||
///
|
||||
/// See: CalculatePathsThreaded
|
||||
/// See: StartPath
|
||||
/// </summary>
|
||||
IEnumerator CalculatePaths (PathHandler pathHandler) {
|
||||
// Max number of ticks before yielding/sleeping
|
||||
long maxTicks = (long)(astar.maxFrameTime*10000);
|
||||
long targetTick = System.DateTime.UtcNow.Ticks + maxTicks;
|
||||
|
||||
while (true) {
|
||||
// The path we are currently calculating
|
||||
Path p = null;
|
||||
|
||||
AstarProfiler.StartProfile("Path Queue");
|
||||
|
||||
// Try to get the next path to be calculated
|
||||
bool blockedBefore = false;
|
||||
while (p == null) {
|
||||
try {
|
||||
p = queue.PopNoBlock(blockedBefore);
|
||||
blockedBefore |= p == null;
|
||||
} catch (ThreadControlQueue.QueueTerminationException) {
|
||||
yield break;
|
||||
}
|
||||
|
||||
if (p == null) {
|
||||
AstarProfiler.EndProfile();
|
||||
yield return null;
|
||||
AstarProfiler.StartProfile("Path Queue");
|
||||
}
|
||||
}
|
||||
|
||||
AstarProfiler.EndProfile();
|
||||
|
||||
AstarProfiler.StartProfile("Path Calc");
|
||||
|
||||
IPathInternals ip = (IPathInternals)p;
|
||||
|
||||
// Max number of ticks we are allowed to continue working in one run
|
||||
// One tick is 1/10000 of a millisecond
|
||||
maxTicks = (long)(astar.maxFrameTime*10000);
|
||||
|
||||
ip.PrepareBase(pathHandler);
|
||||
|
||||
// Now processing the path
|
||||
// Will advance to Processing
|
||||
ip.AdvanceState(PathState.Processing);
|
||||
|
||||
// Call some callbacks
|
||||
// It needs to be stored in a local variable to avoid race conditions
|
||||
var tmpOnPathPreSearch = OnPathPreSearch;
|
||||
if (tmpOnPathPreSearch != null) tmpOnPathPreSearch(p);
|
||||
|
||||
// Tick for when the path started, used for calculating how long time the calculation took
|
||||
long startTicks = System.DateTime.UtcNow.Ticks;
|
||||
long totalTicks = 0;
|
||||
|
||||
AstarProfiler.StartFastProfile(8);
|
||||
|
||||
AstarProfiler.StartFastProfile(0);
|
||||
//Prepare the path
|
||||
AstarProfiler.StartProfile("Path Prepare");
|
||||
ip.Prepare();
|
||||
AstarProfiler.EndProfile("Path Prepare");
|
||||
AstarProfiler.EndFastProfile(0);
|
||||
|
||||
// Check if the Prepare call caused the path to complete
|
||||
// If this happens the path usually failed
|
||||
if (p.CompleteState == PathCompleteState.NotCalculated) {
|
||||
// For debug uses, we set the last computed path to p, so we can view debug info on it in the editor (scene view).
|
||||
astar.debugPathData = ip.PathHandler;
|
||||
astar.debugPathID = p.pathID;
|
||||
|
||||
// Initialize the path, now ready to begin search
|
||||
AstarProfiler.StartProfile("Path Initialize");
|
||||
ip.Initialize();
|
||||
AstarProfiler.EndProfile();
|
||||
|
||||
// The error can turn up in the Init function
|
||||
while (p.CompleteState == PathCompleteState.NotCalculated) {
|
||||
// Do some work on the path calculation.
|
||||
// The function will return when it has taken too much time
|
||||
// or when it has finished calculation
|
||||
AstarProfiler.StartFastProfile(2);
|
||||
|
||||
AstarProfiler.StartProfile("Path Calc Step");
|
||||
ip.CalculateStep(targetTick);
|
||||
AstarProfiler.EndFastProfile(2);
|
||||
|
||||
AstarProfiler.EndProfile();
|
||||
|
||||
// If the path has finished calculation, we can break here directly instead of sleeping
|
||||
// Improves latency
|
||||
if (p.CompleteState != PathCompleteState.NotCalculated) break;
|
||||
|
||||
AstarProfiler.EndFastProfile(8);
|
||||
totalTicks += System.DateTime.UtcNow.Ticks-startTicks;
|
||||
// Yield/sleep so other threads can work
|
||||
|
||||
AstarProfiler.EndProfile();
|
||||
yield return null;
|
||||
AstarProfiler.StartProfile("Path Calc");
|
||||
|
||||
startTicks = System.DateTime.UtcNow.Ticks;
|
||||
AstarProfiler.StartFastProfile(8);
|
||||
|
||||
// Cancel function (and thus the thread) if no more paths should be accepted.
|
||||
// This is done when the A* object is about to be destroyed
|
||||
// The path is returned and then this function will be terminated (see similar IF statement higher up in the function)
|
||||
if (queue.IsTerminating) {
|
||||
p.FailWithError("AstarPath object destroyed");
|
||||
}
|
||||
|
||||
targetTick = System.DateTime.UtcNow.Ticks + maxTicks;
|
||||
}
|
||||
|
||||
totalTicks += System.DateTime.UtcNow.Ticks-startTicks;
|
||||
p.duration = totalTicks*0.0001F;
|
||||
|
||||
#if ProfileAstar
|
||||
System.Threading.Interlocked.Increment(ref AstarPath.PathsCompleted);
|
||||
#endif
|
||||
}
|
||||
|
||||
// Cleans up node tagging and other things
|
||||
ip.Cleanup();
|
||||
|
||||
AstarProfiler.EndFastProfile(8);
|
||||
|
||||
// Call the immediate callback
|
||||
// It needs to be stored in a local variable to avoid race conditions
|
||||
var tmpImmediateCallback = p.immediateCallback;
|
||||
if (tmpImmediateCallback != null) tmpImmediateCallback(p);
|
||||
|
||||
AstarProfiler.StartFastProfile(13);
|
||||
|
||||
// It needs to be stored in a local variable to avoid race conditions
|
||||
var tmpOnPathPostSearch = OnPathPostSearch;
|
||||
if (tmpOnPathPostSearch != null) tmpOnPathPostSearch(p);
|
||||
|
||||
AstarProfiler.EndFastProfile(13);
|
||||
|
||||
// Push the path onto the return stack
|
||||
// It will be detected by the main Unity thread and returned as fast as possible (the next late update)
|
||||
returnQueue.Enqueue(p);
|
||||
|
||||
ip.AdvanceState(PathState.ReturnQueue);
|
||||
|
||||
AstarProfiler.EndProfile();
|
||||
|
||||
// Wait a bit if we have calculated a lot of paths
|
||||
if (System.DateTime.UtcNow.Ticks > targetTick) {
|
||||
yield return null;
|
||||
targetTick = System.DateTime.UtcNow.Ticks + maxTicks;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/Misc/PathProcessor.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/Misc/PathProcessor.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f1b519f8b6e2c450aaae5cb2df6c73be
|
||||
timeCreated: 1443114816
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
@ -0,0 +1,73 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
#if UNITY_5_5_OR_NEWER
|
||||
using UnityEngine.Profiling;
|
||||
#endif
|
||||
|
||||
namespace Pathfinding {
|
||||
class PathReturnQueue {
|
||||
/// <summary>
|
||||
/// Holds all paths which are waiting to be flagged as completed.
|
||||
/// See: <see cref="ReturnPaths"/>
|
||||
/// </summary>
|
||||
Queue<Path> pathReturnQueue = new Queue<Path>();
|
||||
|
||||
/// <summary>
|
||||
/// Paths are claimed silently by some object to prevent them from being recycled while still in use.
|
||||
/// This will be set to the AstarPath object.
|
||||
/// </summary>
|
||||
System.Object pathsClaimedSilentlyBy;
|
||||
|
||||
public PathReturnQueue (System.Object pathsClaimedSilentlyBy) {
|
||||
this.pathsClaimedSilentlyBy = pathsClaimedSilentlyBy;
|
||||
}
|
||||
|
||||
public void Enqueue (Path path) {
|
||||
lock (pathReturnQueue) {
|
||||
pathReturnQueue.Enqueue(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all paths in the return stack.
|
||||
/// Paths which have been processed are put in the return stack.
|
||||
/// This function will pop all items from the stack and return them to e.g the Seeker requesting them.
|
||||
/// </summary>
|
||||
/// <param name="timeSlice">Do not return all paths at once if it takes a long time, instead return some and wait until the next call.</param>
|
||||
public void ReturnPaths (bool timeSlice) {
|
||||
Profiler.BeginSample("Calling Path Callbacks");
|
||||
|
||||
// Hard coded limit on 1.0 ms
|
||||
long targetTick = timeSlice ? System.DateTime.UtcNow.Ticks + 1 * 10000 : 0;
|
||||
|
||||
int counter = 0;
|
||||
// Loop through the linked list and return all paths
|
||||
while (true) {
|
||||
// Move to the next path
|
||||
Path path;
|
||||
lock (pathReturnQueue) {
|
||||
if (pathReturnQueue.Count == 0) break;
|
||||
path = pathReturnQueue.Dequeue();
|
||||
}
|
||||
|
||||
// Return the path
|
||||
((IPathInternals)path).ReturnPath();
|
||||
|
||||
// Will increment path state to Returned
|
||||
((IPathInternals)path).AdvanceState(PathState.Returned);
|
||||
|
||||
path.Release(pathsClaimedSilentlyBy, true);
|
||||
|
||||
counter++;
|
||||
// At least 5 paths will be returned, even if timeSlice is enabled
|
||||
if (counter > 5 && timeSlice) {
|
||||
counter = 0;
|
||||
if (System.DateTime.UtcNow.Ticks >= targetTick) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Profiler.EndSample();
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/Misc/PathReturnQueue.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/Misc/PathReturnQueue.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 70ca370ae38794366be2fa32880f362e
|
||||
timeCreated: 1443114816
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
98
AR/Assets/AstarPathfindingProject/Core/Misc/StackPool.cs
Normal file
98
AR/Assets/AstarPathfindingProject/Core/Misc/StackPool.cs
Normal file
@ -0,0 +1,98 @@
|
||||
//#define ASTAR_NO_POOLING //@SHOWINEDITOR Disable pooling for some reason. Could be debugging or just for measuring the difference.
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding.Util {
|
||||
/// <summary>
|
||||
/// Lightweight Stack Pool.
|
||||
/// Handy class for pooling stacks of type T.
|
||||
///
|
||||
/// Usage:
|
||||
/// - Claim a new stack using <code> Stack<SomeClass> foo = StackPool<SomeClass>.Claim (); </code>
|
||||
/// - Use it and do stuff with it
|
||||
/// - Release it with <code> StackPool<SomeClass>.Release (foo); </code>
|
||||
///
|
||||
/// You do not need to clear the stack before releasing it.
|
||||
/// After you have released a stack, you should never use it again.
|
||||
///
|
||||
/// Warning: This class is not thread safe
|
||||
///
|
||||
/// \since Version 3.2
|
||||
/// See: Pathfinding.Util.ListPool
|
||||
/// </summary>
|
||||
public static class StackPool<T> {
|
||||
/// <summary>Internal pool</summary>
|
||||
static readonly List<Stack<T> > pool;
|
||||
|
||||
/// <summary>Static constructor</summary>
|
||||
static StackPool () {
|
||||
pool = new List<Stack<T> >();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Claim a stack.
|
||||
/// Returns a pooled stack if any are in the pool.
|
||||
/// Otherwise it creates a new one.
|
||||
/// After usage, this stack should be released using the Release function (though not strictly necessary).
|
||||
/// </summary>
|
||||
public static Stack<T> Claim () {
|
||||
#if ASTAR_NO_POOLING
|
||||
return new Stack<T>();
|
||||
#else
|
||||
lock (pool) {
|
||||
if (pool.Count > 0) {
|
||||
Stack<T> ls = pool[pool.Count-1];
|
||||
pool.RemoveAt(pool.Count-1);
|
||||
return ls;
|
||||
}
|
||||
}
|
||||
|
||||
return new Stack<T>();
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes sure the pool contains at least count pooled items.
|
||||
/// This is good if you want to do all allocations at start.
|
||||
/// </summary>
|
||||
public static void Warmup (int count) {
|
||||
var tmp = new Stack<T>[count];
|
||||
|
||||
for (int i = 0; i < count; i++) tmp[i] = Claim();
|
||||
for (int i = 0; i < count; i++) Release(tmp[i]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases a stack.
|
||||
/// After the stack has been released it should not be used anymore.
|
||||
/// Releasing a stack twice will cause an error.
|
||||
/// </summary>
|
||||
public static void Release (Stack<T> stack) {
|
||||
#if !ASTAR_NO_POOLING
|
||||
stack.Clear();
|
||||
|
||||
lock (pool) {
|
||||
for (int i = 0; i < pool.Count; i++)
|
||||
if (pool[i] == stack) UnityEngine.Debug.LogError("The Stack is released even though it is inside the pool");
|
||||
|
||||
pool.Add(stack);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all pooled stacks of this type.
|
||||
/// This is an O(n) operation, where n is the number of pooled stacks
|
||||
/// </summary>
|
||||
public static void Clear () {
|
||||
lock (pool) {
|
||||
pool.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Number of stacks of this type in the pool</summary>
|
||||
public static int GetSize () {
|
||||
return pool.Count;
|
||||
}
|
||||
}
|
||||
}
|
7
AR/Assets/AstarPathfindingProject/Core/Misc/StackPool.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/Misc/StackPool.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: de467bbbb1ff84668ae8262caad00941
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
@ -0,0 +1,291 @@
|
||||
using System.Threading;
|
||||
|
||||
namespace Pathfinding {
|
||||
/// <summary>Queue of paths to be processed by the system</summary>
|
||||
class ThreadControlQueue {
|
||||
public class QueueTerminationException : System.Exception {
|
||||
}
|
||||
|
||||
Path head;
|
||||
Path tail;
|
||||
|
||||
readonly System.Object lockObj = new System.Object();
|
||||
|
||||
readonly int numReceivers;
|
||||
|
||||
bool blocked;
|
||||
|
||||
/// <summary>
|
||||
/// Number of receiver threads that are currently blocked.
|
||||
/// This is only modified while a thread has a lock on lockObj
|
||||
/// </summary>
|
||||
int blockedReceivers;
|
||||
|
||||
/// <summary>
|
||||
/// True while head == null.
|
||||
/// This is only modified while a thread has a lock on lockObj
|
||||
/// </summary>
|
||||
bool starving;
|
||||
|
||||
/// <summary>
|
||||
/// True after TerminateReceivers has been called.
|
||||
/// All receivers will be terminated when they next call Pop.
|
||||
/// </summary>
|
||||
bool terminate;
|
||||
|
||||
ManualResetEvent block = new ManualResetEvent(true);
|
||||
|
||||
/// <summary>
|
||||
/// Create a new queue with the specified number of receivers.
|
||||
/// It is important that the number of receivers is fixed.
|
||||
/// Properties like AllReceiversBlocked rely on knowing the exact number of receivers using the Pop (or PopNoBlock) methods.
|
||||
/// </summary>
|
||||
public ThreadControlQueue (int numReceivers) {
|
||||
this.numReceivers = numReceivers;
|
||||
}
|
||||
|
||||
/// <summary>True if the queue is empty</summary>
|
||||
public bool IsEmpty {
|
||||
get {
|
||||
return head == null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True if TerminateReceivers has been called</summary>
|
||||
public bool IsTerminating {
|
||||
get {
|
||||
return terminate;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Block queue, all calls to Pop will block until Unblock is called</summary>
|
||||
public void Block () {
|
||||
lock (lockObj) {
|
||||
blocked = true;
|
||||
block.Reset();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unblock queue.
|
||||
/// Calls to Pop will not block anymore.
|
||||
/// See: Block
|
||||
/// </summary>
|
||||
public void Unblock () {
|
||||
lock (lockObj) {
|
||||
blocked = false;
|
||||
block.Set();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Aquires a lock on this queue.
|
||||
/// Must be paired with a call to <see cref="Unlock"/>
|
||||
/// </summary>
|
||||
public void Lock () {
|
||||
Monitor.Enter(lockObj);
|
||||
}
|
||||
|
||||
/// <summary>Releases the lock on this queue</summary>
|
||||
public void Unlock () {
|
||||
Monitor.Exit(lockObj);
|
||||
}
|
||||
|
||||
/// <summary>True if blocking and all receivers are waiting for unblocking</summary>
|
||||
public bool AllReceiversBlocked {
|
||||
get {
|
||||
lock (lockObj) {
|
||||
return blocked && blockedReceivers == numReceivers;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Push a path to the front of the queue</summary>
|
||||
public void PushFront (Path path) {
|
||||
lock (lockObj) {
|
||||
// If termination is due, why add stuff to a queue which will not be read from anyway
|
||||
if (terminate) return;
|
||||
|
||||
if (tail == null) {// (tail == null) ==> (head == null)
|
||||
head = path;
|
||||
tail = path;
|
||||
|
||||
if (starving && !blocked) {
|
||||
starving = false;
|
||||
block.Set();
|
||||
} else {
|
||||
starving = false;
|
||||
}
|
||||
} else {
|
||||
path.next = head;
|
||||
head = path;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Push a path to the end of the queue</summary>
|
||||
public void Push (Path path) {
|
||||
lock (lockObj) {
|
||||
// If termination is due, why add stuff to a queue which will not be read from anyway
|
||||
if (terminate) return;
|
||||
|
||||
if (tail == null) {// (tail == null) ==> (head == null)
|
||||
head = path;
|
||||
tail = path;
|
||||
|
||||
if (starving && !blocked) {
|
||||
starving = false;
|
||||
block.Set();
|
||||
} else {
|
||||
starving = false;
|
||||
}
|
||||
} else {
|
||||
tail.next = path;
|
||||
tail = path;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Starving () {
|
||||
starving = true;
|
||||
block.Reset();
|
||||
}
|
||||
|
||||
/// <summary>All calls to Pop and PopNoBlock will now generate exceptions</summary>
|
||||
public void TerminateReceivers () {
|
||||
lock (lockObj) {
|
||||
terminate = true;
|
||||
block.Set();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pops the next item off the queue.
|
||||
/// This call will block if there are no items in the queue or if the queue is currently blocked.
|
||||
///
|
||||
/// Returns: A Path object, guaranteed to be not null.
|
||||
/// \throws QueueTerminationException if <see cref="TerminateReceivers"/> has been called.
|
||||
/// \throws System.InvalidOperationException if more receivers get blocked than the fixed count sent to the constructor
|
||||
/// </summary>
|
||||
public Path Pop () {
|
||||
Monitor.Enter(lockObj);
|
||||
try {
|
||||
if (terminate) {
|
||||
blockedReceivers++;
|
||||
throw new QueueTerminationException();
|
||||
}
|
||||
|
||||
if (head == null) {
|
||||
Starving();
|
||||
}
|
||||
|
||||
while (blocked || starving) {
|
||||
blockedReceivers++;
|
||||
|
||||
if (blockedReceivers > numReceivers) {
|
||||
throw new System.InvalidOperationException("More receivers are blocked than specified in constructor ("+blockedReceivers + " > " + numReceivers+")");
|
||||
}
|
||||
|
||||
Monitor.Exit(lockObj);
|
||||
|
||||
block.WaitOne();
|
||||
|
||||
Monitor.Enter(lockObj);
|
||||
|
||||
if (terminate) {
|
||||
throw new QueueTerminationException();
|
||||
}
|
||||
|
||||
blockedReceivers--;
|
||||
|
||||
if (head == null) {
|
||||
Starving();
|
||||
}
|
||||
}
|
||||
Path p = head;
|
||||
|
||||
var newHead = head.next;
|
||||
if (newHead == null) {
|
||||
tail = null;
|
||||
}
|
||||
head.next = null;
|
||||
head = newHead;
|
||||
|
||||
return p;
|
||||
} finally {
|
||||
// Normally this only exits via a QueueTerminationException and will always be entered in that case.
|
||||
// However the thread may also be aborted using a ThreadAbortException which can happen at any time.
|
||||
// In particular if the Unity Editor recompiles scripts and is configured to exit play mode on recompilation
|
||||
// then it will apparently abort all threads before the AstarPath.OnDestroy method is called (which would have
|
||||
// cleaned up the threads gracefully). So we need to check if we actually hold the lock before releaseing it.
|
||||
if (Monitor.IsEntered(lockObj)) {
|
||||
Monitor.Exit(lockObj);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Call when a receiver was terminated in other ways than by a QueueTerminationException.
|
||||
///
|
||||
/// After this call, the receiver should be dead and not call anything else in this class.
|
||||
/// </summary>
|
||||
public void ReceiverTerminated () {
|
||||
Monitor.Enter(lockObj);
|
||||
blockedReceivers++;
|
||||
Monitor.Exit(lockObj);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pops the next item off the queue, this call will not block.
|
||||
/// To ensure stability, the caller must follow this pattern.
|
||||
/// 1. Call PopNoBlock(false), if a null value is returned, wait for a bit (e.g yield return null in a Unity coroutine)
|
||||
/// 2. try again with PopNoBlock(true), if still null, wait for a bit
|
||||
/// 3. Repeat from step 2.
|
||||
///
|
||||
/// \throws QueueTerminationException if <see cref="TerminateReceivers"/> has been called.
|
||||
/// \throws System.InvalidOperationException if more receivers get blocked than the fixed count sent to the constructor
|
||||
/// </summary>
|
||||
public Path PopNoBlock (bool blockedBefore) {
|
||||
Monitor.Enter(lockObj);
|
||||
try {
|
||||
if (terminate) {
|
||||
blockedReceivers++;
|
||||
throw new QueueTerminationException();
|
||||
}
|
||||
|
||||
if (head == null) {
|
||||
Starving();
|
||||
}
|
||||
if (blocked || starving) {
|
||||
if (!blockedBefore) {
|
||||
blockedReceivers++;
|
||||
|
||||
if (terminate) throw new QueueTerminationException();
|
||||
|
||||
if (blockedReceivers == numReceivers) {
|
||||
//Last alive
|
||||
} else if (blockedReceivers > numReceivers) {
|
||||
throw new System.InvalidOperationException("More receivers are blocked than specified in constructor ("+blockedReceivers + " > " + numReceivers+")");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (blockedBefore) {
|
||||
blockedReceivers--;
|
||||
}
|
||||
|
||||
Path p = head;
|
||||
|
||||
var newHead = head.next;
|
||||
if (newHead == null) {
|
||||
tail = null;
|
||||
}
|
||||
head.next = null;
|
||||
head = newHead;
|
||||
return p;
|
||||
} finally {
|
||||
Monitor.Exit(lockObj);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
8
AR/Assets/AstarPathfindingProject/Core/Misc/ThreadControlQueue.cs.meta
generated
Normal file
8
AR/Assets/AstarPathfindingProject/Core/Misc/ThreadControlQueue.cs.meta
generated
Normal file
@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e6a8344fd0d1c453cbaf5c5eb8f55ca5
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
@ -0,0 +1,148 @@
|
||||
#if NETFX_CORE
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Reflection;
|
||||
using System.IO;
|
||||
using TP = System.Reflection.TypeInfo;
|
||||
#else
|
||||
using TP = System.Type;
|
||||
#endif
|
||||
|
||||
namespace Pathfinding.WindowsStore {
|
||||
public static class WindowsStoreCompatibility {
|
||||
public static System.Type GetTypeFromInfo (TP type) {
|
||||
#if NETFX_CORE
|
||||
return type.AsType();
|
||||
#else
|
||||
return type;
|
||||
#endif
|
||||
}
|
||||
|
||||
public static TP GetTypeInfo (System.Type type) {
|
||||
#if NETFX_CORE
|
||||
return type.GetTypeInfo();
|
||||
#else
|
||||
return type;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if NETFX_CORE
|
||||
public static void Close (this BinaryWriter stream) {
|
||||
stream.Dispose();
|
||||
}
|
||||
|
||||
public static void Close (this BinaryReader stream) {
|
||||
stream.Dispose();
|
||||
}
|
||||
|
||||
public static void Close (this StreamWriter stream) {
|
||||
stream.Dispose();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if NETFX_CORE
|
||||
public delegate void ParameterizedThreadStart(System.Object ob);
|
||||
public delegate void ThreadStart();
|
||||
|
||||
public class Thread {
|
||||
//
|
||||
// Fields
|
||||
//
|
||||
private Pathfinding.WindowsStore.ParameterizedThreadStart _paramThreadStart;
|
||||
|
||||
private CancellationTokenSource _taskCancellationTokenSource;
|
||||
|
||||
private Task _task = null;
|
||||
|
||||
private Pathfinding.WindowsStore.ThreadStart _threadStart;
|
||||
|
||||
private static ManualResetEvent SleepEvent = new ManualResetEvent(false);
|
||||
|
||||
//
|
||||
// Properties
|
||||
//
|
||||
public bool IsAlive {
|
||||
get {
|
||||
return this._task != null && !this._task.IsCompleted;
|
||||
}
|
||||
set {
|
||||
throw new System.NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsBackground {
|
||||
get {
|
||||
return false;
|
||||
}
|
||||
set {
|
||||
}
|
||||
}
|
||||
|
||||
public string Name {
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
//
|
||||
// Constructors
|
||||
//
|
||||
public Thread (Pathfinding.WindowsStore.ParameterizedThreadStart start) {
|
||||
this._taskCancellationTokenSource = new CancellationTokenSource();
|
||||
this._paramThreadStart = start;
|
||||
}
|
||||
|
||||
public Thread (Pathfinding.WindowsStore.ThreadStart start) {
|
||||
this._taskCancellationTokenSource = new CancellationTokenSource();
|
||||
this._threadStart = start;
|
||||
}
|
||||
|
||||
//
|
||||
// Static Methods
|
||||
//
|
||||
public static void Sleep (int ms) {
|
||||
SleepEvent.WaitOne(ms);
|
||||
}
|
||||
|
||||
//
|
||||
// Methods
|
||||
//
|
||||
public void Abort () {
|
||||
if (this._taskCancellationTokenSource != null) {
|
||||
this._taskCancellationTokenSource.Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureTask (object paramThreadStartParam = null) {
|
||||
if (this._task == null) {
|
||||
if (this._paramThreadStart != null) {
|
||||
this._task = new Task(delegate {
|
||||
this._paramThreadStart(paramThreadStartParam);
|
||||
}, this._taskCancellationTokenSource.Token);
|
||||
} else {
|
||||
if (this._threadStart != null) {
|
||||
this._task = new Task(delegate {
|
||||
this._threadStart();
|
||||
}, this._taskCancellationTokenSource.Token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool Join (int ms) {
|
||||
this.EnsureTask();
|
||||
return this._task.Wait(ms, this._taskCancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
public void Start () {
|
||||
this.EnsureTask();
|
||||
this._task.Start(TaskScheduler.Default);
|
||||
}
|
||||
|
||||
public void Start (object param) {
|
||||
this.EnsureTask(param);
|
||||
this._task.Start(TaskScheduler.Default);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
8
AR/Assets/AstarPathfindingProject/Core/Misc/WindowsStoreCompatibility.cs.meta
generated
Normal file
8
AR/Assets/AstarPathfindingProject/Core/Misc/WindowsStoreCompatibility.cs.meta
generated
Normal file
@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 810a4e97f5ccb4b5184c4c3206492974
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
338
AR/Assets/AstarPathfindingProject/Core/Misc/WorkItemProcessor.cs
Normal file
338
AR/Assets/AstarPathfindingProject/Core/Misc/WorkItemProcessor.cs
Normal file
@ -0,0 +1,338 @@
|
||||
using UnityEngine;
|
||||
#if UNITY_5_5_OR_NEWER
|
||||
using UnityEngine.Profiling;
|
||||
#endif
|
||||
|
||||
namespace Pathfinding {
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// An item of work that can be executed when graphs are safe to update.
|
||||
/// See: <see cref="AstarPath.UpdateGraphs"/>
|
||||
/// See: <see cref="AstarPath.AddWorkItem"/>
|
||||
/// </summary>
|
||||
public struct AstarWorkItem {
|
||||
/// <summary>
|
||||
/// Init function.
|
||||
/// May be null if no initialization is needed.
|
||||
/// Will be called once, right before the first call to <see cref="update"/>.
|
||||
/// </summary>
|
||||
public System.Action init;
|
||||
|
||||
/// <summary>
|
||||
/// Init function.
|
||||
/// May be null if no initialization is needed.
|
||||
/// Will be called once, right before the first call to <see cref="update"/>.
|
||||
///
|
||||
/// A context object is sent as a parameter. This can be used
|
||||
/// to for example queue a flood fill that will be executed either
|
||||
/// when a work item calls EnsureValidFloodFill or all work items have
|
||||
/// been completed. If multiple work items are updating nodes
|
||||
/// so that they need a flood fill afterwards, using the QueueFloodFill
|
||||
/// method is preferred since then only a single flood fill needs
|
||||
/// to be performed for all of the work items instead of one
|
||||
/// per work item.
|
||||
/// </summary>
|
||||
public System.Action<IWorkItemContext> initWithContext;
|
||||
|
||||
/// <summary>
|
||||
/// Update function, called once per frame when the work item executes.
|
||||
/// Takes a param force. If that is true, the work item should try to complete the whole item in one go instead
|
||||
/// of spreading it out over multiple frames.
|
||||
/// Returns: True when the work item is completed.
|
||||
/// </summary>
|
||||
public System.Func<bool, bool> update;
|
||||
|
||||
/// <summary>
|
||||
/// Update function, called once per frame when the work item executes.
|
||||
/// Takes a param force. If that is true, the work item should try to complete the whole item in one go instead
|
||||
/// of spreading it out over multiple frames.
|
||||
/// Returns: True when the work item is completed.
|
||||
///
|
||||
/// A context object is sent as a parameter. This can be used
|
||||
/// to for example queue a flood fill that will be executed either
|
||||
/// when a work item calls EnsureValidFloodFill or all work items have
|
||||
/// been completed. If multiple work items are updating nodes
|
||||
/// so that they need a flood fill afterwards, using the QueueFloodFill
|
||||
/// method is preferred since then only a single flood fill needs
|
||||
/// to be performed for all of the work items instead of one
|
||||
/// per work item.
|
||||
/// </summary>
|
||||
public System.Func<IWorkItemContext, bool, bool> updateWithContext;
|
||||
|
||||
public AstarWorkItem (System.Func<bool, bool> update) {
|
||||
this.init = null;
|
||||
this.initWithContext = null;
|
||||
this.updateWithContext = null;
|
||||
this.update = update;
|
||||
}
|
||||
|
||||
public AstarWorkItem (System.Func<IWorkItemContext, bool, bool> update) {
|
||||
this.init = null;
|
||||
this.initWithContext = null;
|
||||
this.updateWithContext = update;
|
||||
this.update = null;
|
||||
}
|
||||
|
||||
public AstarWorkItem (System.Action init, System.Func<bool, bool> update = null) {
|
||||
this.init = init;
|
||||
this.initWithContext = null;
|
||||
this.update = update;
|
||||
this.updateWithContext = null;
|
||||
}
|
||||
|
||||
public AstarWorkItem (System.Action<IWorkItemContext> init, System.Func<IWorkItemContext, bool, bool> update = null) {
|
||||
this.init = null;
|
||||
this.initWithContext = init;
|
||||
this.update = null;
|
||||
this.updateWithContext = update;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Interface to expose a subset of the WorkItemProcessor functionality</summary>
|
||||
public interface IWorkItemContext {
|
||||
/// <summary>
|
||||
/// Call during work items to queue a flood fill.
|
||||
/// An instant flood fill can be done via FloodFill()
|
||||
/// but this method can be used to batch several updates into one
|
||||
/// to increase performance.
|
||||
/// WorkItems which require a valid Flood Fill in their execution can call EnsureValidFloodFill
|
||||
/// to ensure that a flood fill is done if any earlier work items queued one.
|
||||
///
|
||||
/// Once a flood fill is queued it will be done after all WorkItems have been executed.
|
||||
///
|
||||
/// Deprecated: Avoid using. This will force a full recalculation of the connected components. In most cases the HierarchicalGraph class takes care of things automatically behind the scenes now. In pretty much all cases you should be able to remove the call to this function.
|
||||
/// </summary>
|
||||
[System.Obsolete("Avoid using. This will force a full recalculation of the connected components. In most cases the HierarchicalGraph class takes care of things automatically behind the scenes now. In pretty much all cases you should be able to remove the call to this function.")]
|
||||
void QueueFloodFill();
|
||||
|
||||
/// <summary>
|
||||
/// If a WorkItem needs to have a valid area information during execution, call this method to ensure there are no pending flood fills.
|
||||
/// If you are using the <see cref="Pathfinding.GraphNode.Area"/> property or the <see cref="Pathfinding.PathUtilities.IsPathPossible"/> method in your work items, then you might want to call this method before you use them
|
||||
/// to ensure that the data is up to date.
|
||||
///
|
||||
/// See: <see cref="Pathfinding.HierarchicalGraph"/>
|
||||
///
|
||||
/// <code>
|
||||
/// AstarPath.active.AddWorkItem(new AstarWorkItem((IWorkItemContext ctx) => {
|
||||
/// ctx.EnsureValidFloodFill();
|
||||
///
|
||||
/// // The above call guarantees that this method has up to date information about the graph
|
||||
/// if (PathUtilities.IsPathPossible(someNode, someOtherNode)) {
|
||||
/// // Do something
|
||||
/// }
|
||||
/// }));
|
||||
/// </code>
|
||||
/// </summary>
|
||||
void EnsureValidFloodFill();
|
||||
|
||||
/// <summary>
|
||||
/// Trigger a graph modification event.
|
||||
/// This will cause a <see cref="Pathfinding.GraphModifier.PostUpdate"/> event to be issued after all graph updates have finished.
|
||||
/// Some scripts listen for this event. For example off-mesh links listen to it and will recalculate which nodes they are connected to when it it sent.
|
||||
/// If a graph is dirtied multiple times, or even if multiple graphs are dirtied, the event will only be sent once.
|
||||
/// </summary>
|
||||
void SetGraphDirty(NavGraph graph);
|
||||
}
|
||||
|
||||
class WorkItemProcessor : IWorkItemContext {
|
||||
/// <summary>Used to prevent waiting for work items to complete inside other work items as that will cause the program to hang</summary>
|
||||
public bool workItemsInProgressRightNow { get; private set; }
|
||||
|
||||
readonly AstarPath astar;
|
||||
readonly IndexedQueue<AstarWorkItem> workItems = new IndexedQueue<AstarWorkItem>();
|
||||
|
||||
/// <summary>True if any work items are queued right now</summary>
|
||||
public bool anyQueued {
|
||||
get { return workItems.Count > 0; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True if any work items have queued a flood fill.
|
||||
/// See: QueueWorkItemFloodFill
|
||||
/// </summary>
|
||||
bool queuedWorkItemFloodFill = false;
|
||||
|
||||
bool anyGraphsDirty = true;
|
||||
|
||||
/// <summary>
|
||||
/// True while a batch of work items are being processed.
|
||||
/// Set to true when a work item is started to be processed, reset to false when all work items are complete.
|
||||
///
|
||||
/// Work item updates are often spread out over several frames, this flag will be true during the whole time the
|
||||
/// updates are in progress.
|
||||
/// </summary>
|
||||
public bool workItemsInProgress { get; private set; }
|
||||
|
||||
/// <summary>Similar to Queue<T> but allows random access</summary>
|
||||
class IndexedQueue<T> {
|
||||
T[] buffer = new T[4];
|
||||
int start;
|
||||
|
||||
public T this[int index] {
|
||||
get {
|
||||
if (index < 0 || index >= Count) throw new System.IndexOutOfRangeException();
|
||||
return buffer[(start + index) % buffer.Length];
|
||||
}
|
||||
set {
|
||||
if (index < 0 || index >= Count) throw new System.IndexOutOfRangeException();
|
||||
buffer[(start + index) % buffer.Length] = value;
|
||||
}
|
||||
}
|
||||
|
||||
public int Count { get; private set; }
|
||||
|
||||
public void Enqueue (T item) {
|
||||
if (Count == buffer.Length) {
|
||||
var newBuffer = new T[buffer.Length*2];
|
||||
for (int i = 0; i < Count; i++) {
|
||||
newBuffer[i] = this[i];
|
||||
}
|
||||
buffer = newBuffer;
|
||||
start = 0;
|
||||
}
|
||||
|
||||
buffer[(start + Count) % buffer.Length] = item;
|
||||
Count++;
|
||||
}
|
||||
|
||||
public T Dequeue () {
|
||||
if (Count == 0) throw new System.InvalidOperationException();
|
||||
var item = buffer[start];
|
||||
start = (start + 1) % buffer.Length;
|
||||
Count--;
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Call during work items to queue a flood fill.
|
||||
/// An instant flood fill can be done via FloodFill()
|
||||
/// but this method can be used to batch several updates into one
|
||||
/// to increase performance.
|
||||
/// WorkItems which require a valid Flood Fill in their execution can call EnsureValidFloodFill
|
||||
/// to ensure that a flood fill is done if any earlier work items queued one.
|
||||
///
|
||||
/// Once a flood fill is queued it will be done after all WorkItems have been executed.
|
||||
/// </summary>
|
||||
void IWorkItemContext.QueueFloodFill () {
|
||||
queuedWorkItemFloodFill = true;
|
||||
}
|
||||
|
||||
void IWorkItemContext.SetGraphDirty (NavGraph graph) {
|
||||
anyGraphsDirty = true;
|
||||
}
|
||||
|
||||
/// <summary>If a WorkItem needs to have a valid area information during execution, call this method to ensure there are no pending flood fills</summary>
|
||||
public void EnsureValidFloodFill () {
|
||||
if (queuedWorkItemFloodFill) {
|
||||
astar.hierarchicalGraph.RecalculateAll();
|
||||
} else {
|
||||
astar.hierarchicalGraph.RecalculateIfNecessary();
|
||||
}
|
||||
}
|
||||
|
||||
public WorkItemProcessor (AstarPath astar) {
|
||||
this.astar = astar;
|
||||
}
|
||||
|
||||
public void OnFloodFill () {
|
||||
queuedWorkItemFloodFill = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add a work item to be processed when pathfinding is paused.
|
||||
///
|
||||
/// See: ProcessWorkItems
|
||||
/// </summary>
|
||||
public void AddWorkItem (AstarWorkItem item) {
|
||||
workItems.Enqueue(item);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Process graph updating work items.
|
||||
/// Process all queued work items, e.g graph updates and the likes.
|
||||
///
|
||||
/// Returns:
|
||||
/// - false if there are still items to be processed.
|
||||
/// - true if the last work items was processed and pathfinding threads are ready to be resumed.
|
||||
///
|
||||
/// See: AddWorkItem
|
||||
/// See: threadSafeUpdateState
|
||||
/// See: Update
|
||||
/// </summary>
|
||||
public bool ProcessWorkItems (bool force) {
|
||||
if (workItemsInProgressRightNow) throw new System.Exception("Processing work items recursively. Please do not wait for other work items to be completed inside work items. " +
|
||||
"If you think this is not caused by any of your scripts, this might be a bug.");
|
||||
|
||||
UnityEngine.Physics2D.SyncTransforms();
|
||||
workItemsInProgressRightNow = true;
|
||||
astar.data.LockGraphStructure(true);
|
||||
while (workItems.Count > 0) {
|
||||
// Working on a new batch
|
||||
if (!workItemsInProgress) {
|
||||
workItemsInProgress = true;
|
||||
queuedWorkItemFloodFill = false;
|
||||
}
|
||||
|
||||
// Peek at first item in the queue
|
||||
AstarWorkItem itm = workItems[0];
|
||||
bool status;
|
||||
|
||||
try {
|
||||
// Call init the first time the item is seen
|
||||
if (itm.init != null) {
|
||||
itm.init();
|
||||
itm.init = null;
|
||||
}
|
||||
|
||||
if (itm.initWithContext != null) {
|
||||
itm.initWithContext(this);
|
||||
itm.initWithContext = null;
|
||||
}
|
||||
|
||||
// Make sure the item in the queue is up to date
|
||||
workItems[0] = itm;
|
||||
|
||||
if (itm.update != null) {
|
||||
status = itm.update(force);
|
||||
} else if (itm.updateWithContext != null) {
|
||||
status = itm.updateWithContext(this, force);
|
||||
} else {
|
||||
status = true;
|
||||
}
|
||||
} catch {
|
||||
workItems.Dequeue();
|
||||
workItemsInProgressRightNow = false;
|
||||
astar.data.UnlockGraphStructure();
|
||||
throw;
|
||||
}
|
||||
|
||||
if (!status) {
|
||||
if (force) {
|
||||
Debug.LogError("Misbehaving WorkItem. 'force'=true but the work item did not complete.\nIf force=true is passed to a WorkItem it should always return true.");
|
||||
}
|
||||
|
||||
// Still work items to process
|
||||
workItemsInProgressRightNow = false;
|
||||
astar.data.UnlockGraphStructure();
|
||||
return false;
|
||||
} else {
|
||||
workItems.Dequeue();
|
||||
}
|
||||
}
|
||||
|
||||
EnsureValidFloodFill();
|
||||
|
||||
Profiler.BeginSample("PostUpdate");
|
||||
if (anyGraphsDirty) GraphModifier.TriggerEvent(GraphModifier.EventType.PostUpdate);
|
||||
Profiler.EndSample();
|
||||
|
||||
anyGraphsDirty = false;
|
||||
workItemsInProgressRightNow = false;
|
||||
workItemsInProgress = false;
|
||||
astar.data.UnlockGraphStructure();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/Misc/WorkItemProcessor.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/Misc/WorkItemProcessor.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4236764d0fc1041abaac13b858be5118
|
||||
timeCreated: 1443114816
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
2
AR/Assets/AstarPathfindingProject/Core/Nodes.meta
generated
Normal file
2
AR/Assets/AstarPathfindingProject/Core/Nodes.meta
generated
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b41391edefb794969b06b1e03993abf4
|
811
AR/Assets/AstarPathfindingProject/Core/Nodes/GraphNode.cs
Normal file
811
AR/Assets/AstarPathfindingProject/Core/Nodes/GraphNode.cs
Normal file
@ -0,0 +1,811 @@
|
||||
using UnityEngine;
|
||||
using System.Collections.Generic;
|
||||
using Pathfinding.Serialization;
|
||||
|
||||
namespace Pathfinding {
|
||||
using Pathfinding.Util;
|
||||
|
||||
/// <summary>Represents a connection to another node</summary>
|
||||
public struct Connection {
|
||||
/// <summary>Node which this connection goes to</summary>
|
||||
public GraphNode node;
|
||||
|
||||
/// <summary>
|
||||
/// Cost of moving along this connection.
|
||||
/// A cost of 1000 corresponds approximately to the cost of moving one world unit.
|
||||
/// </summary>
|
||||
public uint cost;
|
||||
|
||||
/// <summary>
|
||||
/// Side of the node shape which this connection uses.
|
||||
/// Used for mesh nodes.
|
||||
/// A value of 0 corresponds to using the side for vertex 0 and vertex 1 on the node. 1 corresponds to vertex 1 and 2, etc.
|
||||
/// A negative value means that this connection does not use any side at all (this is mostly used for off-mesh links).
|
||||
///
|
||||
/// Note: Due to alignment, the <see cref="node"/> and <see cref="cost"/> fields use 12 bytes which will be padded
|
||||
/// to 16 bytes when used in an array even if this field would be removed.
|
||||
/// So this field does not contribute to increased memory usage.
|
||||
///
|
||||
/// See: TriangleMeshNode
|
||||
/// See: TriangleMeshNode.AddConnection
|
||||
/// </summary>
|
||||
public byte shapeEdge;
|
||||
|
||||
public Connection (GraphNode node, uint cost, byte shapeEdge = 0xFF) {
|
||||
this.node = node;
|
||||
this.cost = cost;
|
||||
this.shapeEdge = shapeEdge;
|
||||
}
|
||||
|
||||
public override int GetHashCode () {
|
||||
return node.GetHashCode() ^ (int)cost;
|
||||
}
|
||||
|
||||
public override bool Equals (object obj) {
|
||||
if (obj == null) return false;
|
||||
var conn = (Connection)obj;
|
||||
return conn.node == node && conn.cost == cost && conn.shapeEdge == shapeEdge;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Base class for all nodes</summary>
|
||||
public abstract class GraphNode {
|
||||
/// <summary>Internal unique index. Also stores some bitpacked values such as <see cref="TemporaryFlag1"/> and <see cref="TemporaryFlag2"/>.</summary>
|
||||
private int nodeIndex;
|
||||
|
||||
/// <summary>
|
||||
/// Bitpacked field holding several pieces of data.
|
||||
/// See: Walkable
|
||||
/// See: Area
|
||||
/// See: GraphIndex
|
||||
/// See: Tag
|
||||
/// </summary>
|
||||
protected uint flags;
|
||||
|
||||
#if !ASTAR_NO_PENALTY
|
||||
/// <summary>
|
||||
/// Penalty cost for walking on this node.
|
||||
/// This can be used to make it harder/slower to walk over certain nodes.
|
||||
///
|
||||
/// A penalty of 1000 (Int3.Precision) corresponds to the cost of walking one world unit.
|
||||
///
|
||||
/// See: graph-updates (view in online documentation for working links)
|
||||
/// </summary>
|
||||
private uint penalty;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Graph which this node belongs to.
|
||||
///
|
||||
/// If you know the node belongs to a particular graph type, you can cast it to that type:
|
||||
/// <code>
|
||||
/// GraphNode node = ...;
|
||||
/// GridGraph graph = node.Graph as GridGraph;
|
||||
/// </code>
|
||||
///
|
||||
/// Will return null if the node has been destroyed.
|
||||
/// </summary>
|
||||
public NavGraph Graph {
|
||||
get {
|
||||
return Destroyed ? null : AstarData.GetGraph(this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Constructor for a graph node.</summary>
|
||||
protected GraphNode (AstarPath astar) {
|
||||
if (!System.Object.ReferenceEquals(astar, null)) {
|
||||
this.nodeIndex = astar.GetNewNodeIndex();
|
||||
astar.InitializeNode(this);
|
||||
} else {
|
||||
throw new System.Exception("No active AstarPath object to bind to");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Destroys the node.
|
||||
/// Cleans up any temporary pathfinding data used for this node.
|
||||
/// The graph is responsible for calling this method on nodes when they are destroyed, including when the whole graph is destoyed.
|
||||
/// Otherwise memory leaks might present themselves.
|
||||
///
|
||||
/// Once called the <see cref="Destroyed"/> property will return true and subsequent calls to this method will not do anything.
|
||||
///
|
||||
/// Note: Assumes the current active AstarPath instance is the same one that created this node.
|
||||
///
|
||||
/// Warning: Should only be called by graph classes on their own nodes
|
||||
/// </summary>
|
||||
public void Destroy () {
|
||||
if (Destroyed) return;
|
||||
|
||||
ClearConnections(true);
|
||||
|
||||
if (AstarPath.active != null) {
|
||||
AstarPath.active.DestroyNode(this);
|
||||
}
|
||||
NodeIndex = DestroyedNodeIndex;
|
||||
}
|
||||
|
||||
public bool Destroyed {
|
||||
get {
|
||||
return NodeIndex == DestroyedNodeIndex;
|
||||
}
|
||||
}
|
||||
|
||||
// If anyone creates more than about 200 million nodes then things will not go so well, however at that point one will certainly have more pressing problems, such as having run out of RAM
|
||||
const int NodeIndexMask = 0xFFFFFFF;
|
||||
const int DestroyedNodeIndex = NodeIndexMask - 1;
|
||||
const int TemporaryFlag1Mask = 0x10000000;
|
||||
const int TemporaryFlag2Mask = 0x20000000;
|
||||
|
||||
/// <summary>
|
||||
/// Internal unique index.
|
||||
/// Every node will get a unique index.
|
||||
/// This index is not necessarily correlated with e.g the position of the node in the graph.
|
||||
/// </summary>
|
||||
public int NodeIndex { get { return nodeIndex & NodeIndexMask; } private set { nodeIndex = (nodeIndex & ~NodeIndexMask) | value; } }
|
||||
|
||||
/// <summary>
|
||||
/// Temporary flag for internal purposes.
|
||||
/// May only be used in the Unity thread. Must be reset to false after every use.
|
||||
/// </summary>
|
||||
internal bool TemporaryFlag1 { get { return (nodeIndex & TemporaryFlag1Mask) != 0; } set { nodeIndex = (nodeIndex & ~TemporaryFlag1Mask) | (value ? TemporaryFlag1Mask : 0); } }
|
||||
|
||||
/// <summary>
|
||||
/// Temporary flag for internal purposes.
|
||||
/// May only be used in the Unity thread. Must be reset to false after every use.
|
||||
/// </summary>
|
||||
internal bool TemporaryFlag2 { get { return (nodeIndex & TemporaryFlag2Mask) != 0; } set { nodeIndex = (nodeIndex & ~TemporaryFlag2Mask) | (value ? TemporaryFlag2Mask : 0); } }
|
||||
|
||||
/// <summary>
|
||||
/// Position of the node in world space.
|
||||
/// Note: The position is stored as an Int3, not a Vector3.
|
||||
/// You can convert an Int3 to a Vector3 using an explicit conversion.
|
||||
/// <code> var v3 = (Vector3)node.position; </code>
|
||||
/// </summary>
|
||||
public Int3 position;
|
||||
|
||||
#region Constants
|
||||
/// <summary>Position of the walkable bit. See: <see cref="Walkable"/></summary>
|
||||
const int FlagsWalkableOffset = 0;
|
||||
/// <summary>Mask of the walkable bit. See: <see cref="Walkable"/></summary>
|
||||
const uint FlagsWalkableMask = 1 << FlagsWalkableOffset;
|
||||
|
||||
/// <summary>Start of hierarchical node index bits. See: <see cref="HierarchicalNodeIndex"/></summary>
|
||||
const int FlagsHierarchicalIndexOffset = 1;
|
||||
/// <summary>Mask of hierarchical node index bits. See: <see cref="HierarchicalNodeIndex"/></summary>
|
||||
const uint HierarchicalIndexMask = (131072-1) << FlagsHierarchicalIndexOffset;
|
||||
|
||||
/// <summary>Start of <see cref="IsHierarchicalNodeDirty"/> bits. See: <see cref="IsHierarchicalNodeDirty"/></summary>
|
||||
const int HierarchicalDirtyOffset = 18;
|
||||
|
||||
/// <summary>Mask of the <see cref="IsHierarchicalNodeDirty"/> bit. See: <see cref="IsHierarchicalNodeDirty"/></summary>
|
||||
const uint HierarchicalDirtyMask = 1 << HierarchicalDirtyOffset;
|
||||
|
||||
/// <summary>Start of graph index bits. See: <see cref="GraphIndex"/></summary>
|
||||
const int FlagsGraphOffset = 24;
|
||||
/// <summary>Mask of graph index bits. See: <see cref="GraphIndex"/></summary>
|
||||
const uint FlagsGraphMask = (256u-1) << FlagsGraphOffset;
|
||||
|
||||
public const uint MaxHierarchicalNodeIndex = HierarchicalIndexMask >> FlagsHierarchicalIndexOffset;
|
||||
|
||||
/// <summary>Max number of graphs-1</summary>
|
||||
public const uint MaxGraphIndex = FlagsGraphMask >> FlagsGraphOffset;
|
||||
|
||||
/// <summary>Start of tag bits. See: <see cref="Tag"/></summary>
|
||||
const int FlagsTagOffset = 19;
|
||||
/// <summary>Mask of tag bits. See: <see cref="Tag"/></summary>
|
||||
const uint FlagsTagMask = (32-1) << FlagsTagOffset;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Properties
|
||||
|
||||
/// <summary>
|
||||
/// Holds various bitpacked variables.
|
||||
///
|
||||
/// Bit 0: <see cref="Walkable"/>
|
||||
/// Bits 1 through 17: <see cref="HierarchicalNodeIndex"/>
|
||||
/// Bit 18: <see cref="IsHierarchicalNodeDirty"/>
|
||||
/// Bits 19 through 23: <see cref="Tag"/>
|
||||
/// Bits 24 through 31: <see cref="GraphIndex"/>
|
||||
///
|
||||
/// Warning: You should pretty much never modify this property directly. Use the other properties instead.
|
||||
/// </summary>
|
||||
public uint Flags {
|
||||
get {
|
||||
return flags;
|
||||
}
|
||||
set {
|
||||
flags = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Penalty cost for walking on this node.
|
||||
/// This can be used to make it harder/slower to walk over certain nodes.
|
||||
/// A cost of 1000 (<see cref="Pathfinding.Int3.Precision"/>) corresponds to the cost of moving 1 world unit.
|
||||
///
|
||||
/// See: graph-updates (view in online documentation for working links)
|
||||
/// </summary>
|
||||
public uint Penalty {
|
||||
#if !ASTAR_NO_PENALTY
|
||||
get {
|
||||
return penalty;
|
||||
}
|
||||
set {
|
||||
if (value > 0xFFFFFF)
|
||||
Debug.LogWarning("Very high penalty applied. Are you sure negative values haven't underflowed?\n" +
|
||||
"Penalty values this high could with long paths cause overflows and in some cases infinity loops because of that.\n" +
|
||||
"Penalty value applied: "+value);
|
||||
penalty = value;
|
||||
}
|
||||
#else
|
||||
get { return 0U; }
|
||||
set {}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True if the node is traversable.
|
||||
///
|
||||
/// See: graph-updates (view in online documentation for working links)
|
||||
/// </summary>
|
||||
public bool Walkable {
|
||||
get {
|
||||
return (flags & FlagsWalkableMask) != 0;
|
||||
}
|
||||
set {
|
||||
flags = flags & ~FlagsWalkableMask | (value ? 1U : 0U) << FlagsWalkableOffset;
|
||||
AstarPath.active.hierarchicalGraph.AddDirtyNode(this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hierarchical Node that contains this node.
|
||||
/// The graph is divided into clusters of small hierarchical nodes in which there is a path from every node to every other node.
|
||||
/// This structure is used to speed up connected component calculations which is used to quickly determine if a node is reachable from another node.
|
||||
///
|
||||
/// See: <see cref="Pathfinding.HierarchicalGraph"/>
|
||||
///
|
||||
/// Warning: This is an internal property and you should most likely not change it.
|
||||
/// </summary>
|
||||
internal int HierarchicalNodeIndex {
|
||||
get {
|
||||
return (int)((flags & HierarchicalIndexMask) >> FlagsHierarchicalIndexOffset);
|
||||
}
|
||||
set {
|
||||
flags = (flags & ~HierarchicalIndexMask) | (uint)(value << FlagsHierarchicalIndexOffset);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Some internal bookkeeping</summary>
|
||||
internal bool IsHierarchicalNodeDirty {
|
||||
get {
|
||||
return (flags & HierarchicalDirtyMask) != 0;
|
||||
}
|
||||
set {
|
||||
flags = flags & ~HierarchicalDirtyMask | (value ? 1U : 0U) << HierarchicalDirtyOffset;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connected component that contains the node.
|
||||
/// This is visualized in the scene view as differently colored nodes (if the graph coloring mode is set to 'Areas').
|
||||
/// Each area represents a set of nodes such that there is no valid path between nodes of different colors.
|
||||
///
|
||||
/// See: https://en.wikipedia.org/wiki/Connected_component_(graph_theory)
|
||||
/// See: <see cref="Pathfinding.HierarchicalGraph"/>
|
||||
/// </summary>
|
||||
public uint Area {
|
||||
get {
|
||||
return AstarPath.active.hierarchicalGraph.GetConnectedComponent(HierarchicalNodeIndex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Graph which contains this node.
|
||||
/// See: <see cref="Pathfinding.AstarData.graphs"/>
|
||||
/// See: <see cref="Graph"/>
|
||||
/// </summary>
|
||||
public uint GraphIndex {
|
||||
get {
|
||||
return (flags & FlagsGraphMask) >> FlagsGraphOffset;
|
||||
}
|
||||
set {
|
||||
flags = flags & ~FlagsGraphMask | value << FlagsGraphOffset;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Node tag.
|
||||
/// See: tags (view in online documentation for working links)
|
||||
/// See: graph-updates (view in online documentation for working links)
|
||||
/// </summary>
|
||||
public uint Tag {
|
||||
get {
|
||||
return (flags & FlagsTagMask) >> FlagsTagOffset;
|
||||
}
|
||||
set {
|
||||
flags = flags & ~FlagsTagMask | ((value << FlagsTagOffset) & FlagsTagMask);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Inform the system that the node's connectivity has changed.
|
||||
/// This is used for recalculating the connected components of the graph.
|
||||
///
|
||||
/// See: <see cref="Pathfinding.HierarchicalGraph"/>
|
||||
///
|
||||
/// You must call this method if you change the connectivity or walkability of the node without going through the high level methods
|
||||
/// such as the <see cref="Walkable"/> property or the <see cref="AddConnection"/> method. For example if your manually change the <see cref="Pathfinding.MeshNode.connections"/> array you need to call this method.
|
||||
/// </summary>
|
||||
public void SetConnectivityDirty () {
|
||||
AstarPath.active.hierarchicalGraph.AddDirtyNode(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recalculates a node's connection costs.
|
||||
/// Deprecated: This method is deprecated because it never did anything, you can safely remove any calls to this method.
|
||||
/// </summary>
|
||||
[System.Obsolete("This method is deprecated because it never did anything, you can safely remove any calls to this method")]
|
||||
public void RecalculateConnectionCosts () {
|
||||
}
|
||||
|
||||
public virtual void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
|
||||
//Simple but slow default implementation
|
||||
pathNode.UpdateG(path);
|
||||
|
||||
handler.heap.Add(pathNode);
|
||||
|
||||
GetConnections((GraphNode other) => {
|
||||
PathNode otherPN = handler.GetPathNode(other);
|
||||
if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) other.UpdateRecursiveG(path, otherPN, handler);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calls the delegate with all connections from this node.
|
||||
/// <code>
|
||||
/// node.GetConnections(connectedTo => {
|
||||
/// Debug.DrawLine((Vector3)node.position, (Vector3)connectedTo.position, Color.red);
|
||||
/// });
|
||||
/// </code>
|
||||
///
|
||||
/// You can add all connected nodes to a list like this
|
||||
/// <code>
|
||||
/// var connections = new List<GraphNode>();
|
||||
/// node.GetConnections(connections.Add);
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public abstract void GetConnections(System.Action<GraphNode> action);
|
||||
|
||||
/// <summary>
|
||||
/// Add a connection from this node to the specified node.
|
||||
/// If the connection already exists, the cost will simply be updated and
|
||||
/// no extra connection added.
|
||||
///
|
||||
/// Note: Only adds a one-way connection. Consider calling the same function on the other node
|
||||
/// to get a two-way connection.
|
||||
///
|
||||
/// <code>
|
||||
/// AstarPath.active.AddWorkItem(new AstarWorkItem(ctx => {
|
||||
/// // Connect two nodes
|
||||
/// var node1 = AstarPath.active.GetNearest(transform.position, NNConstraint.None).node;
|
||||
/// var node2 = AstarPath.active.GetNearest(transform.position + Vector3.right, NNConstraint.None).node;
|
||||
/// var cost = (uint)(node2.position - node1.position).costMagnitude;
|
||||
/// node1.AddConnection(node2, cost);
|
||||
/// node2.AddConnection(node1, cost);
|
||||
///
|
||||
/// node1.ContainsConnection(node2); // True
|
||||
///
|
||||
/// node1.RemoveConnection(node2);
|
||||
/// node2.RemoveConnection(node1);
|
||||
/// }));
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public abstract void AddConnection(GraphNode node, uint cost);
|
||||
|
||||
/// <summary>
|
||||
/// Removes any connection from this node to the specified node.
|
||||
/// If no such connection exists, nothing will be done.
|
||||
///
|
||||
/// Note: This only removes the connection from this node to the other node.
|
||||
/// You may want to call the same function on the other node to remove its possible connection
|
||||
/// to this node.
|
||||
///
|
||||
/// <code>
|
||||
/// AstarPath.active.AddWorkItem(new AstarWorkItem(ctx => {
|
||||
/// // Connect two nodes
|
||||
/// var node1 = AstarPath.active.GetNearest(transform.position, NNConstraint.None).node;
|
||||
/// var node2 = AstarPath.active.GetNearest(transform.position + Vector3.right, NNConstraint.None).node;
|
||||
/// var cost = (uint)(node2.position - node1.position).costMagnitude;
|
||||
/// node1.AddConnection(node2, cost);
|
||||
/// node2.AddConnection(node1, cost);
|
||||
///
|
||||
/// node1.ContainsConnection(node2); // True
|
||||
///
|
||||
/// node1.RemoveConnection(node2);
|
||||
/// node2.RemoveConnection(node1);
|
||||
/// }));
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public abstract void RemoveConnection(GraphNode node);
|
||||
|
||||
/// <summary>Remove all connections from this node.</summary>
|
||||
/// <param name="alsoReverse">if true, neighbours will be requested to remove connections to this node.</param>
|
||||
public abstract void ClearConnections(bool alsoReverse);
|
||||
|
||||
/// <summary>
|
||||
/// Checks if this node has a connection to the specified node.
|
||||
///
|
||||
/// <code>
|
||||
/// AstarPath.active.AddWorkItem(new AstarWorkItem(ctx => {
|
||||
/// // Connect two nodes
|
||||
/// var node1 = AstarPath.active.GetNearest(transform.position, NNConstraint.None).node;
|
||||
/// var node2 = AstarPath.active.GetNearest(transform.position + Vector3.right, NNConstraint.None).node;
|
||||
/// var cost = (uint)(node2.position - node1.position).costMagnitude;
|
||||
/// node1.AddConnection(node2, cost);
|
||||
/// node2.AddConnection(node1, cost);
|
||||
///
|
||||
/// node1.ContainsConnection(node2); // True
|
||||
///
|
||||
/// node1.RemoveConnection(node2);
|
||||
/// node2.RemoveConnection(node1);
|
||||
/// }));
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public virtual bool ContainsConnection (GraphNode node) {
|
||||
// Simple but slow default implementation
|
||||
bool contains = false;
|
||||
|
||||
GetConnections(neighbour => {
|
||||
contains |= neighbour == node;
|
||||
});
|
||||
return contains;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add a portal from this node to the specified node.
|
||||
/// This function should add a portal to the left and right lists which is connecting the two nodes (this and other).
|
||||
///
|
||||
/// Returns: True if the call was deemed successful. False if some unknown case was encountered and no portal could be added.
|
||||
/// If both calls to node1.GetPortal (node2,...) and node2.GetPortal (node1,...) return false, the funnel modifier will fall back to adding to the path
|
||||
/// the positions of the node.
|
||||
///
|
||||
/// The default implementation simply returns false.
|
||||
///
|
||||
/// This function may add more than one portal if necessary.
|
||||
///
|
||||
/// See: http://digestingduck.blogspot.se/2010/03/simple-stupid-funnel-algorithm.html
|
||||
/// </summary>
|
||||
/// <param name="other">The node which is on the other side of the portal (strictly speaking it does not actually have to be on the other side of the portal though).</param>
|
||||
/// <param name="left">List of portal points on the left side of the funnel</param>
|
||||
/// <param name="right">List of portal points on the right side of the funnel</param>
|
||||
/// <param name="backwards">If this is true, the call was made on a node with the other node as the node before this one in the path.
|
||||
/// In this case you may choose to do nothing since a similar call will be made to the other node with this node referenced as other (but then with backwards = true).
|
||||
/// You do not have to care about switching the left and right lists, that is done for you already.</param>
|
||||
public virtual bool GetPortal (GraphNode other, List<Vector3> left, List<Vector3> right, bool backwards) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Open the node.
|
||||
/// Used internally for the A* algorithm.
|
||||
/// </summary>
|
||||
public abstract void Open(Path path, PathNode pathNode, PathHandler handler);
|
||||
|
||||
/// <summary>The surface area of the node in square world units</summary>
|
||||
public virtual float SurfaceArea () {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A random point on the surface of the node.
|
||||
/// For point nodes and other nodes which do not have a surface, this will always return the position of the node.
|
||||
/// </summary>
|
||||
public virtual Vector3 RandomPointOnSurface () {
|
||||
return (Vector3)position;
|
||||
}
|
||||
|
||||
/// <summary>Closest point on the surface of this node to the point p</summary>
|
||||
public abstract Vector3 ClosestPointOnNode(Vector3 p);
|
||||
|
||||
/// <summary>
|
||||
/// Hash code used for checking if the gizmos need to be updated.
|
||||
/// Will change when the gizmos for the node might change.
|
||||
/// </summary>
|
||||
public virtual int GetGizmoHashCode () {
|
||||
// Some hashing, the constants are just some arbitrary prime numbers. #flags contains the info for #Tag and #Walkable
|
||||
return position.GetHashCode() ^ (19 * (int)Penalty) ^ (41 * (int)(flags & ~(HierarchicalIndexMask | HierarchicalDirtyMask)));
|
||||
}
|
||||
|
||||
/// <summary>Serialized the node data to a byte array</summary>
|
||||
public virtual void SerializeNode (GraphSerializationContext ctx) {
|
||||
//Write basic node data.
|
||||
ctx.writer.Write(Penalty);
|
||||
// Save all flags except the hierarchical node index and the dirty bit
|
||||
ctx.writer.Write(Flags & ~(HierarchicalIndexMask | HierarchicalDirtyMask));
|
||||
}
|
||||
|
||||
/// <summary>Deserializes the node data from a byte array</summary>
|
||||
public virtual void DeserializeNode (GraphSerializationContext ctx) {
|
||||
Penalty = ctx.reader.ReadUInt32();
|
||||
// Load all flags except the hierarchical node index and the dirty bit (they aren't saved in newer versions and older data should just be cleared)
|
||||
// Note that the dirty bit needs to be preserved here because it may already be set (due to the node being created)
|
||||
Flags = (ctx.reader.ReadUInt32() & ~(HierarchicalIndexMask | HierarchicalDirtyMask)) | (Flags & (HierarchicalIndexMask | HierarchicalDirtyMask));
|
||||
|
||||
// Set the correct graph index (which might have changed, e.g if loading additively)
|
||||
GraphIndex = ctx.graphIndex;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Used to serialize references to other nodes e.g connections.
|
||||
/// Use the GraphSerializationContext.GetNodeIdentifier and
|
||||
/// GraphSerializationContext.GetNodeFromIdentifier methods
|
||||
/// for serialization and deserialization respectively.
|
||||
///
|
||||
/// Nodes must override this method and serialize their connections.
|
||||
/// Graph generators do not need to call this method, it will be called automatically on all
|
||||
/// nodes at the correct time by the serializer.
|
||||
/// </summary>
|
||||
public virtual void SerializeReferences (GraphSerializationContext ctx) {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Used to deserialize references to other nodes e.g connections.
|
||||
/// Use the GraphSerializationContext.GetNodeIdentifier and
|
||||
/// GraphSerializationContext.GetNodeFromIdentifier methods
|
||||
/// for serialization and deserialization respectively.
|
||||
///
|
||||
/// Nodes must override this method and serialize their connections.
|
||||
/// Graph generators do not need to call this method, it will be called automatically on all
|
||||
/// nodes at the correct time by the serializer.
|
||||
/// </summary>
|
||||
public virtual void DeserializeReferences (GraphSerializationContext ctx) {
|
||||
}
|
||||
}
|
||||
|
||||
public abstract class MeshNode : GraphNode {
|
||||
protected MeshNode (AstarPath astar) : base(astar) {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// All connections from this node.
|
||||
/// See: <see cref="AddConnection"/>
|
||||
/// See: <see cref="RemoveConnection"/>
|
||||
///
|
||||
/// Note: If you modify this array or the contents of it you must call <see cref="SetConnectivityDirty"/>.
|
||||
/// </summary>
|
||||
public Connection[] connections;
|
||||
|
||||
/// <summary>Get a vertex of this node.</summary>
|
||||
/// <param name="i">vertex index. Must be between 0 and #GetVertexCount (exclusive).</param>
|
||||
public abstract Int3 GetVertex(int i);
|
||||
|
||||
/// <summary>
|
||||
/// Number of corner vertices that this node has.
|
||||
/// For example for a triangle node this will return 3.
|
||||
/// </summary>
|
||||
public abstract int GetVertexCount();
|
||||
|
||||
/// <summary>
|
||||
/// Closest point on the surface of this node when seen from above.
|
||||
/// This is usually very similar to <see cref="ClosestPointOnNode"/> but when the node is in a slope this can be significantly different.
|
||||
/// [Open online documentation to see images]
|
||||
/// When the blue point in the above image is used as an argument this method call will return the green point while the <see cref="ClosestPointOnNode"/> method will return the red point.
|
||||
/// </summary>
|
||||
public abstract Vector3 ClosestPointOnNodeXZ(Vector3 p);
|
||||
|
||||
public override void ClearConnections (bool alsoReverse) {
|
||||
// Remove all connections to this node from our neighbours
|
||||
if (alsoReverse && connections != null) {
|
||||
for (int i = 0; i < connections.Length; i++) {
|
||||
// Null check done here because NavmeshTile.Destroy
|
||||
// requires it for some optimizations it does
|
||||
// Normally connection elements are never null
|
||||
if (connections[i].node != null) {
|
||||
connections[i].node.RemoveConnection(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ArrayPool<Connection>.Release(ref connections, true);
|
||||
AstarPath.active.hierarchicalGraph.AddDirtyNode(this);
|
||||
}
|
||||
|
||||
public override void GetConnections (System.Action<GraphNode> action) {
|
||||
if (connections == null) return;
|
||||
for (int i = 0; i < connections.Length; i++) action(connections[i].node);
|
||||
}
|
||||
|
||||
public override bool ContainsConnection (GraphNode node) {
|
||||
for (int i = 0; i < connections.Length; i++) if (connections[i].node == node) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
|
||||
pathNode.UpdateG(path);
|
||||
|
||||
handler.heap.Add(pathNode);
|
||||
|
||||
for (int i = 0; i < connections.Length; i++) {
|
||||
GraphNode other = connections[i].node;
|
||||
PathNode otherPN = handler.GetPathNode(other);
|
||||
if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) {
|
||||
other.UpdateRecursiveG(path, otherPN, handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add a connection from this node to the specified node.
|
||||
///
|
||||
/// If the connection already exists, the cost will simply be updated and
|
||||
/// no extra connection added.
|
||||
///
|
||||
/// Note: Only adds a one-way connection. Consider calling the same function on the other node
|
||||
/// to get a two-way connection.
|
||||
/// </summary>
|
||||
/// <param name="node">Node to add a connection to</param>
|
||||
/// <param name="cost">Cost of traversing the connection. A cost of 1000 corresponds approximately to the cost of moving 1 world unit.</param>
|
||||
public override void AddConnection (GraphNode node, uint cost) {
|
||||
AddConnection(node, cost, -1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add a connection from this node to the specified node.
|
||||
/// See: Pathfinding.Connection.edge
|
||||
///
|
||||
/// If the connection already exists, the cost will simply be updated and
|
||||
/// no extra connection added.
|
||||
///
|
||||
/// Note: Only adds a one-way connection. Consider calling the same function on the other node
|
||||
/// to get a two-way connection.
|
||||
/// </summary>
|
||||
/// <param name="node">Node to add a connection to</param>
|
||||
/// <param name="cost">Cost of traversing the connection. A cost of 1000 corresponds approximately to the cost of moving 1 world unit.</param>
|
||||
/// <param name="shapeEdge">Which edge on the shape of this node to use or -1 if no edge is used.</param>
|
||||
public void AddConnection (GraphNode node, uint cost, int shapeEdge) {
|
||||
if (node == null) throw new System.ArgumentNullException();
|
||||
|
||||
// Check if we already have a connection to the node
|
||||
if (connections != null) {
|
||||
for (int i = 0; i < connections.Length; i++) {
|
||||
if (connections[i].node == node) {
|
||||
// Just update the cost for the existing connection
|
||||
connections[i].cost = cost;
|
||||
// Update edge only if it was a definite edge, otherwise reuse the existing one
|
||||
// This makes it possible to use the AddConnection(node,cost) overload to only update the cost
|
||||
// without changing the edge which is required for backwards compatibility.
|
||||
connections[i].shapeEdge = shapeEdge >= 0 ? (byte)shapeEdge : connections[i].shapeEdge;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create new arrays which include the new connection
|
||||
int connLength = connections != null ? connections.Length : 0;
|
||||
|
||||
var newconns = ArrayPool<Connection>.ClaimWithExactLength(connLength+1);
|
||||
for (int i = 0; i < connLength; i++) {
|
||||
newconns[i] = connections[i];
|
||||
}
|
||||
|
||||
newconns[connLength] = new Connection(node, cost, (byte)shapeEdge);
|
||||
|
||||
if (connections != null) {
|
||||
ArrayPool<Connection>.Release(ref connections, true);
|
||||
}
|
||||
|
||||
connections = newconns;
|
||||
AstarPath.active.hierarchicalGraph.AddDirtyNode(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes any connection from this node to the specified node.
|
||||
/// If no such connection exists, nothing will be done.
|
||||
///
|
||||
/// Note: This only removes the connection from this node to the other node.
|
||||
/// You may want to call the same function on the other node to remove its eventual connection
|
||||
/// to this node.
|
||||
/// </summary>
|
||||
public override void RemoveConnection (GraphNode node) {
|
||||
if (connections == null) return;
|
||||
|
||||
// Iterate through all connections and check if there are any to the node
|
||||
for (int i = 0; i < connections.Length; i++) {
|
||||
if (connections[i].node == node) {
|
||||
// Create new arrays which have the specified node removed
|
||||
int connLength = connections.Length;
|
||||
|
||||
var newconns = ArrayPool<Connection>.ClaimWithExactLength(connLength-1);
|
||||
for (int j = 0; j < i; j++) {
|
||||
newconns[j] = connections[j];
|
||||
}
|
||||
for (int j = i+1; j < connLength; j++) {
|
||||
newconns[j-1] = connections[j];
|
||||
}
|
||||
|
||||
if (connections != null) {
|
||||
ArrayPool<Connection>.Release(ref connections, true);
|
||||
}
|
||||
|
||||
connections = newconns;
|
||||
AstarPath.active.hierarchicalGraph.AddDirtyNode(this);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Checks if point is inside the node when seen from above</summary>
|
||||
public virtual bool ContainsPoint (Int3 point) {
|
||||
return ContainsPoint((Vector3)point);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if point is inside the node when seen from above.
|
||||
///
|
||||
/// Note that <see cref="ContainsPointInGraphSpace"/> is faster than this method as it avoids
|
||||
/// some coordinate transformations. If you are repeatedly calling this method
|
||||
/// on many different nodes but with the same point then you should consider
|
||||
/// transforming the point first and then calling ContainsPointInGraphSpace.
|
||||
/// <code>
|
||||
/// Int3 p = (Int3)graph.transform.InverseTransform(point);
|
||||
///
|
||||
/// node.ContainsPointInGraphSpace(p);
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public abstract bool ContainsPoint(Vector3 point);
|
||||
|
||||
/// <summary>
|
||||
/// Checks if point is inside the node in graph space.
|
||||
///
|
||||
/// In graph space the up direction is always the Y axis so in principle
|
||||
/// we project the triangle down on the XZ plane and check if the point is inside the 2D triangle there.
|
||||
/// </summary>
|
||||
public abstract bool ContainsPointInGraphSpace(Int3 point);
|
||||
|
||||
public override int GetGizmoHashCode () {
|
||||
var hash = base.GetGizmoHashCode();
|
||||
|
||||
if (connections != null) {
|
||||
for (int i = 0; i < connections.Length; i++) {
|
||||
hash ^= 17 * connections[i].GetHashCode();
|
||||
}
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
public override void SerializeReferences (GraphSerializationContext ctx) {
|
||||
if (connections == null) {
|
||||
ctx.writer.Write(-1);
|
||||
} else {
|
||||
ctx.writer.Write(connections.Length);
|
||||
for (int i = 0; i < connections.Length; i++) {
|
||||
ctx.SerializeNodeReference(connections[i].node);
|
||||
ctx.writer.Write(connections[i].cost);
|
||||
ctx.writer.Write(connections[i].shapeEdge);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void DeserializeReferences (GraphSerializationContext ctx) {
|
||||
int count = ctx.reader.ReadInt32();
|
||||
|
||||
if (count == -1) {
|
||||
connections = null;
|
||||
} else {
|
||||
connections = ArrayPool<Connection>.ClaimWithExactLength(count);
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
connections[i] = new Connection(
|
||||
ctx.DeserializeNodeReference(),
|
||||
ctx.reader.ReadUInt32(),
|
||||
ctx.meta.version < AstarSerializer.V4_1_0 ? (byte)0xFF : ctx.reader.ReadByte()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
12
AR/Assets/AstarPathfindingProject/Core/Nodes/GraphNode.cs.meta
generated
Normal file
12
AR/Assets/AstarPathfindingProject/Core/Nodes/GraphNode.cs.meta
generated
Normal file
@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a660e0d66fb3b49d19d438de51ac6744
|
||||
timeCreated: 1486987492
|
||||
licenseType: Pro
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
845
AR/Assets/AstarPathfindingProject/Core/Path.cs
Normal file
845
AR/Assets/AstarPathfindingProject/Core/Path.cs
Normal file
@ -0,0 +1,845 @@
|
||||
//#define ASTAR_POOL_DEBUG //@SHOWINEDITOR Enables debugging of path pooling. Will log warnings and info messages about paths not beeing pooled correctly.
|
||||
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding {
|
||||
/// <summary>
|
||||
/// Provides additional traversal information to a path request.
|
||||
/// See: turnbased (view in online documentation for working links)
|
||||
/// </summary>
|
||||
public interface ITraversalProvider {
|
||||
bool CanTraverse(Path path, GraphNode node);
|
||||
uint GetTraversalCost(Path path, GraphNode node);
|
||||
}
|
||||
|
||||
/// <summary>Convenience class to access the default implementation of the ITraversalProvider</summary>
|
||||
public static class DefaultITraversalProvider {
|
||||
public static bool CanTraverse (Path path, GraphNode node) {
|
||||
return node.Walkable && (path.enabledTags >> (int)node.Tag & 0x1) != 0;
|
||||
}
|
||||
|
||||
public static uint GetTraversalCost (Path path, GraphNode node) {
|
||||
return path.GetTagPenalty((int)node.Tag) + node.Penalty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Base class for all path types</summary>
|
||||
public abstract class Path : IPathInternals {
|
||||
#if ASTAR_POOL_DEBUG
|
||||
private string pathTraceInfo = "";
|
||||
private List<string> claimInfo = new List<string>();
|
||||
~Path() {
|
||||
Debug.Log("Destroying " + GetType().Name + " instance");
|
||||
if (claimed.Count > 0) {
|
||||
Debug.LogWarning("Pool Is Leaking. See list of claims:\n" +
|
||||
"Each message below will list what objects are currently claiming the path." +
|
||||
" These objects have removed their reference to the path object but has not called .Release on it (which is bad).\n" + pathTraceInfo+"\n");
|
||||
for (int i = 0; i < claimed.Count; i++) {
|
||||
Debug.LogWarning("- Claim "+ (i+1) + " is by a " + claimed[i].GetType().Name + "\n"+claimInfo[i]);
|
||||
}
|
||||
} else {
|
||||
Debug.Log("Some scripts are not using pooling.\n" + pathTraceInfo + "\n");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>Data for the thread calculating this path</summary>
|
||||
protected PathHandler pathHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Callback to call when the path is complete.
|
||||
/// This is usually sent to the Seeker component which post processes the path and then calls a callback to the script which requested the path
|
||||
/// </summary>
|
||||
public OnPathDelegate callback;
|
||||
|
||||
/// <summary>
|
||||
/// Immediate callback to call when the path is complete.
|
||||
/// Warning: This may be called from a separate thread. Usually you do not want to use this one.
|
||||
///
|
||||
/// See: callback
|
||||
/// </summary>
|
||||
public OnPathDelegate immediateCallback;
|
||||
|
||||
/// <summary>Returns the state of the path in the pathfinding pipeline</summary>
|
||||
public PathState PipelineState { get; private set; }
|
||||
System.Object stateLock = new object();
|
||||
|
||||
/// <summary>
|
||||
/// Provides additional traversal information to a path request.
|
||||
/// See: turnbased (view in online documentation for working links)
|
||||
/// </summary>
|
||||
public ITraversalProvider traversalProvider;
|
||||
|
||||
|
||||
/// <summary>Backing field for <see cref="CompleteState"/></summary>
|
||||
protected PathCompleteState completeState;
|
||||
|
||||
/// <summary>
|
||||
/// Current state of the path.
|
||||
/// \bug This may currently be set to Complete before the path has actually been fully calculated. In particular the vectorPath and path lists may not have been fully constructed.
|
||||
/// This can lead to race conditions when using multithreading. Try to avoid using this method to check for if the path is calculated right now, use <see cref="IsDone"/> instead.
|
||||
/// </summary>
|
||||
public PathCompleteState CompleteState {
|
||||
get { return completeState; }
|
||||
protected set {
|
||||
// Locking is used to avoid multithreading race conditions
|
||||
// in which the error state is set on the main thread to cancel the path and then a pathfinding thread marks the path as
|
||||
// completed which would replace the error state (if a lock and check would not have been used).
|
||||
lock (stateLock) {
|
||||
// Once the path is put in the error state, it cannot be set to any other state
|
||||
if (completeState != PathCompleteState.Error) completeState = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// If the path failed, this is true.
|
||||
/// See: <see cref="errorLog"/>
|
||||
/// See: This is equivalent to checking path.CompleteState == PathCompleteState.Error
|
||||
/// </summary>
|
||||
public bool error { get { return CompleteState == PathCompleteState.Error; } }
|
||||
|
||||
/// <summary>
|
||||
/// Additional info on why a path failed.
|
||||
/// See: <see cref="AstarPath.logPathResults"/>
|
||||
/// </summary>
|
||||
public string errorLog { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Holds the path as a Node array. All nodes the path traverses.
|
||||
/// This may not be the same nodes as the post processed path traverses.
|
||||
/// </summary>
|
||||
public List<GraphNode> path;
|
||||
|
||||
/// <summary>Holds the (possibly post processed) path as a Vector3 list</summary>
|
||||
public List<Vector3> vectorPath;
|
||||
|
||||
/// <summary>The node currently being processed</summary>
|
||||
protected PathNode currentR;
|
||||
|
||||
/// <summary>How long it took to calculate this path in milliseconds</summary>
|
||||
public float duration;
|
||||
|
||||
/// <summary>Number of nodes this path has searched</summary>
|
||||
public int searchedNodes { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// True if the path is currently pooled.
|
||||
/// Do not set this value. Only read. It is used internally.
|
||||
///
|
||||
/// See: PathPool
|
||||
/// Version: Was named 'recycled' in 3.7.5 and earlier.
|
||||
/// </summary>
|
||||
bool IPathInternals.Pooled { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// True if the path is currently recycled (i.e in the path pool).
|
||||
/// Do not set this value. Only read. It is used internally.
|
||||
///
|
||||
/// Deprecated: Has been renamed to 'pooled' to use more widely underestood terminology
|
||||
/// </summary>
|
||||
[System.Obsolete("Has been renamed to 'Pooled' to use more widely underestood terminology", true)]
|
||||
internal bool recycled { get { return false; } }
|
||||
|
||||
/// <summary>
|
||||
/// True if the Reset function has been called.
|
||||
/// Used to alert users when they are doing something wrong.
|
||||
/// </summary>
|
||||
protected bool hasBeenReset;
|
||||
|
||||
/// <summary>Constraint for how to search for nodes</summary>
|
||||
public NNConstraint nnConstraint = PathNNConstraint.Default;
|
||||
|
||||
/// <summary>
|
||||
/// Internal linked list implementation.
|
||||
/// Warning: This is used internally by the system. You should never change this.
|
||||
/// </summary>
|
||||
internal Path next;
|
||||
|
||||
/// <summary>Determines which heuristic to use</summary>
|
||||
public Heuristic heuristic;
|
||||
|
||||
/// <summary>
|
||||
/// Scale of the heuristic values.
|
||||
/// See: AstarPath.heuristicScale
|
||||
/// </summary>
|
||||
public float heuristicScale = 1F;
|
||||
|
||||
/// <summary>ID of this path. Used to distinguish between different paths</summary>
|
||||
public ushort pathID { get; private set; }
|
||||
|
||||
/// <summary>Target to use for H score calculation. Used alongside <see cref="hTarget"/>.</summary>
|
||||
protected GraphNode hTargetNode;
|
||||
|
||||
/// <summary>Target to use for H score calculations. See: Pathfinding.Node.H</summary>
|
||||
protected Int3 hTarget;
|
||||
|
||||
/// <summary>
|
||||
/// Which graph tags are traversable.
|
||||
/// This is a bitmask so -1 = all bits set = all tags traversable.
|
||||
/// For example, to set bit 5 to true, you would do
|
||||
/// <code> myPath.enabledTags |= 1 << 5; </code>
|
||||
/// To set it to false, you would do
|
||||
/// <code> myPath.enabledTags &= ~(1 << 5); </code>
|
||||
///
|
||||
/// The Seeker has a popup field where you can set which tags to use.
|
||||
/// Note: If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath.
|
||||
/// So you need to change the Seeker value via script, not set this value if you want to change it via script.
|
||||
///
|
||||
/// See: CanTraverse
|
||||
/// </summary>
|
||||
public int enabledTags = -1;
|
||||
|
||||
/// <summary>List of zeroes to use as default tag penalties</summary>
|
||||
static readonly int[] ZeroTagPenalties = new int[32];
|
||||
|
||||
/// <summary>
|
||||
/// The tag penalties that are actually used.
|
||||
/// If manualTagPenalties is null, this will be ZeroTagPenalties
|
||||
/// See: tagPenalties
|
||||
/// </summary>
|
||||
protected int[] internalTagPenalties;
|
||||
|
||||
/// <summary>
|
||||
/// Tag penalties set by other scripts
|
||||
/// See: tagPenalties
|
||||
/// </summary>
|
||||
protected int[] manualTagPenalties;
|
||||
|
||||
/// <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.
|
||||
///
|
||||
/// When assigning an array to this property it must have a length of 32.
|
||||
///
|
||||
/// Note: Setting this to null, or trying to assign an array which does not have a length of 32, will make all tag penalties be treated as if they are zero.
|
||||
///
|
||||
/// Note: If you are using a Seeker. The Seeker will set this value to what is set in the inspector field when you call seeker.StartPath.
|
||||
/// So you need to change the Seeker's value via script, not set this value.
|
||||
///
|
||||
/// See: Seeker.tagPenalties
|
||||
/// </summary>
|
||||
public int[] tagPenalties {
|
||||
get {
|
||||
return manualTagPenalties;
|
||||
}
|
||||
set {
|
||||
if (value == null || value.Length != 32) {
|
||||
manualTagPenalties = null;
|
||||
internalTagPenalties = ZeroTagPenalties;
|
||||
} else {
|
||||
manualTagPenalties = value;
|
||||
internalTagPenalties = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True for paths that want to search all nodes and not jump over nodes as optimizations.
|
||||
/// This disables Jump Point Search when that is enabled to prevent e.g ConstantPath and FloodPath
|
||||
/// to become completely useless.
|
||||
/// </summary>
|
||||
public virtual bool FloodingPath {
|
||||
get {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Total Length of the path.
|
||||
/// Calculates the total length of the <see cref="vectorPath"/>.
|
||||
/// Cache this rather than call this function every time since it will calculate the length every time, not just return a cached value.
|
||||
/// Returns: Total length of <see cref="vectorPath"/>, if <see cref="vectorPath"/> is null positive infinity is returned.
|
||||
/// </summary>
|
||||
public float GetTotalLength () {
|
||||
if (vectorPath == null) return float.PositiveInfinity;
|
||||
float tot = 0;
|
||||
for (int i = 0; i < vectorPath.Count-1; i++) tot += Vector3.Distance(vectorPath[i], vectorPath[i+1]);
|
||||
return tot;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until this path has been calculated and returned.
|
||||
/// Allows for very easy scripting.
|
||||
/// <code>
|
||||
/// IEnumerator Start () {
|
||||
/// var path = seeker.StartPath(transform.position, transform.position + transform.forward*10, null);
|
||||
/// yield return StartCoroutine(path.WaitForPath());
|
||||
/// // The path is calculated now
|
||||
/// }
|
||||
/// </code>
|
||||
///
|
||||
/// Note: Do not confuse this with AstarPath.WaitForPath. This one will wait using yield until it has been calculated
|
||||
/// while AstarPath.WaitForPath will halt all operations until the path has been calculated.
|
||||
///
|
||||
/// \throws System.InvalidOperationException if the path is not started. Send the path to Seeker.StartPath or AstarPath.StartPath before calling this function.
|
||||
///
|
||||
/// See: <see cref="BlockUntilCalculated"/>
|
||||
/// See: https://docs.unity3d.com/Manual/Coroutines.html
|
||||
/// </summary>
|
||||
public IEnumerator WaitForPath () {
|
||||
if (PipelineState == PathState.Created) throw new System.InvalidOperationException("This path has not been started yet");
|
||||
|
||||
while (PipelineState != PathState.Returned) yield return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Blocks until this path has been calculated and returned.
|
||||
/// Normally it takes a few frames for a path to be calculated and returned.
|
||||
/// This function will ensure that the path will be calculated when this function returns
|
||||
/// and that the callback for that path has been called.
|
||||
///
|
||||
/// Use this function only if you really need to.
|
||||
/// There is a point to spreading path calculations out over several frames.
|
||||
/// It smoothes out the framerate and makes sure requesting a large
|
||||
/// number of paths at the same time does not cause lag.
|
||||
///
|
||||
/// Note: Graph updates and other callbacks might get called during the execution of this function.
|
||||
///
|
||||
/// <code>
|
||||
/// Path p = seeker.StartPath (transform.position, transform.position + Vector3.forward * 10);
|
||||
/// p.BlockUntilCalculated();
|
||||
/// // The path is calculated now
|
||||
/// </code>
|
||||
///
|
||||
/// See: This is equivalent to calling AstarPath.BlockUntilCalculated(Path)
|
||||
/// See: WaitForPath
|
||||
/// </summary>
|
||||
public void BlockUntilCalculated () {
|
||||
AstarPath.BlockUntilCalculated(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Estimated cost from the specified node to the target.
|
||||
/// See: https://en.wikipedia.org/wiki/A*_search_algorithm
|
||||
/// </summary>
|
||||
internal uint CalculateHScore (GraphNode node) {
|
||||
uint h;
|
||||
|
||||
switch (heuristic) {
|
||||
case Heuristic.Euclidean:
|
||||
h = (uint)(((GetHTarget() - node.position).costMagnitude)*heuristicScale);
|
||||
return h;
|
||||
case Heuristic.Manhattan:
|
||||
Int3 p2 = node.position;
|
||||
h = (uint)((System.Math.Abs(hTarget.x-p2.x) + System.Math.Abs(hTarget.y-p2.y) + System.Math.Abs(hTarget.z-p2.z))*heuristicScale);
|
||||
return h;
|
||||
case Heuristic.DiagonalManhattan:
|
||||
Int3 p = GetHTarget() - node.position;
|
||||
p.x = System.Math.Abs(p.x);
|
||||
p.y = System.Math.Abs(p.y);
|
||||
p.z = System.Math.Abs(p.z);
|
||||
int diag = System.Math.Min(p.x, p.z);
|
||||
int diag2 = System.Math.Max(p.x, p.z);
|
||||
h = (uint)((((14*diag)/10) + (diag2-diag) + p.y) * heuristicScale);
|
||||
return h;
|
||||
}
|
||||
return 0U;
|
||||
}
|
||||
|
||||
/// <summary>Returns penalty for the given tag.</summary>
|
||||
/// <param name="tag">A value between 0 (inclusive) and 32 (exclusive).</param>
|
||||
public uint GetTagPenalty (int tag) {
|
||||
return (uint)internalTagPenalties[tag];
|
||||
}
|
||||
|
||||
protected Int3 GetHTarget () {
|
||||
return hTarget;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns if the node can be traversed.
|
||||
/// This per default equals to if the node is walkable and if the node's tag is included in <see cref="enabledTags"/>
|
||||
/// </summary>
|
||||
public bool CanTraverse (GraphNode node) {
|
||||
// Use traversal provider if set, otherwise fall back on default behaviour
|
||||
// This method is hot, but this branch is extremely well predicted so it
|
||||
// doesn't affect performance much (profiling indicates it is just above
|
||||
// the noise level, somewhere around 0%-0.3%)
|
||||
if (traversalProvider != null)
|
||||
return traversalProvider.CanTraverse(this, node);
|
||||
|
||||
// Manually inlined code from DefaultITraversalProvider
|
||||
unchecked { return node.Walkable && (enabledTags >> (int)node.Tag & 0x1) != 0; }
|
||||
}
|
||||
|
||||
/// <summary>Returns the cost of traversing the given node</summary>
|
||||
public uint GetTraversalCost (GraphNode node) {
|
||||
#if ASTAR_NO_TRAVERSAL_COST
|
||||
return 0;
|
||||
#else
|
||||
// Use traversal provider if set, otherwise fall back on default behaviour
|
||||
if (traversalProvider != null)
|
||||
return traversalProvider.GetTraversalCost(this, node);
|
||||
|
||||
unchecked { return GetTagPenalty((int)node.Tag) + node.Penalty; }
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// May be called by graph nodes to get a special cost for some connections.
|
||||
/// Nodes may call it when PathNode.flag2 is set to true, for example mesh nodes, which have
|
||||
/// a very large area can be marked on the start and end nodes, this method will be called
|
||||
/// to get the actual cost for moving from the start position to its neighbours instead
|
||||
/// of as would otherwise be the case, from the start node's position to its neighbours.
|
||||
/// The position of a node and the actual start point on the node can vary quite a lot.
|
||||
///
|
||||
/// The default behaviour of this method is to return the previous cost of the connection,
|
||||
/// essentiall making no change at all.
|
||||
///
|
||||
/// This method should return the same regardless of the order of a and b.
|
||||
/// That is f(a,b) == f(b,a) should hold.
|
||||
/// </summary>
|
||||
/// <param name="a">Moving from this node</param>
|
||||
/// <param name="b">Moving to this node</param>
|
||||
/// <param name="currentCost">The cost of moving between the nodes. Return this value if there is no meaningful special cost to return.</param>
|
||||
public virtual uint GetConnectionSpecialCost (GraphNode a, GraphNode b, uint currentCost) {
|
||||
return currentCost;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True if this path is done calculating.
|
||||
///
|
||||
/// Note: The callback for the path might not have been called yet.
|
||||
///
|
||||
/// \since Added in 3.0.8
|
||||
///
|
||||
/// See: \reflink{Seeker.IsDone} which also takes into account if the %path %callback has been called and had modifiers applied.
|
||||
/// </summary>
|
||||
public bool IsDone () {
|
||||
return PipelineState > PathState.Processing;
|
||||
}
|
||||
|
||||
/// <summary>Threadsafe increment of the state</summary>
|
||||
void IPathInternals.AdvanceState (PathState s) {
|
||||
lock (stateLock) {
|
||||
PipelineState = (PathState)System.Math.Max((int)PipelineState, (int)s);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// State of the path in the pathfinding pipeline.
|
||||
/// Deprecated: Use the <see cref="Pathfinding.Path.PipelineState"/> property instead
|
||||
/// </summary>
|
||||
[System.Obsolete("Use the 'PipelineState' property instead")]
|
||||
public PathState GetState () {
|
||||
return PipelineState;
|
||||
}
|
||||
|
||||
/// <summary>Causes the path to fail and sets <see cref="errorLog"/> to msg</summary>
|
||||
public void FailWithError (string msg) {
|
||||
Error();
|
||||
if (errorLog != "") errorLog += "\n" + msg;
|
||||
else errorLog = msg;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs an error.
|
||||
/// Deprecated: Use <see cref="FailWithError"/> instead
|
||||
/// </summary>
|
||||
[System.Obsolete("Use FailWithError instead")]
|
||||
protected void LogError (string msg) {
|
||||
Log(msg);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Appends a message to the <see cref="errorLog"/>.
|
||||
/// Nothing is logged to the console.
|
||||
///
|
||||
/// Note: If AstarPath.logPathResults is PathLog.None and this is a standalone player, nothing will be logged as an optimization.
|
||||
///
|
||||
/// Deprecated: Use <see cref="FailWithError"/> instead
|
||||
/// </summary>
|
||||
[System.Obsolete("Use FailWithError instead")]
|
||||
protected void Log (string msg) {
|
||||
errorLog += msg;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Aborts the path because of an error.
|
||||
/// Sets <see cref="error"/> to true.
|
||||
/// This function is called when an error has occurred (e.g a valid path could not be found).
|
||||
/// See: <see cref="FailWithError"/>
|
||||
/// </summary>
|
||||
public void Error () {
|
||||
CompleteState = PathCompleteState.Error;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs some error checking.
|
||||
/// Makes sure the user isn't using old code paths and that no major errors have been made.
|
||||
///
|
||||
/// Causes the path to fail if any errors are found.
|
||||
/// </summary>
|
||||
private void ErrorCheck () {
|
||||
if (!hasBeenReset) FailWithError("Please use the static Construct function for creating paths, do not use the normal constructors.");
|
||||
if (((IPathInternals)this).Pooled) FailWithError("The path is currently in a path pool. Are you sending the path for calculation twice?");
|
||||
if (pathHandler == null) FailWithError("Field pathHandler is not set. Please report this bug.");
|
||||
if (PipelineState > PathState.Processing) FailWithError("This path has already been processed. Do not request a path with the same path object twice.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when the path enters the pool.
|
||||
/// This method should release e.g pooled lists and other pooled resources
|
||||
/// The base version of this method releases vectorPath and path lists.
|
||||
/// Reset() will be called after this function, not before.
|
||||
/// Warning: Do not call this function manually.
|
||||
/// </summary>
|
||||
protected virtual void OnEnterPool () {
|
||||
if (vectorPath != null) Pathfinding.Util.ListPool<Vector3>.Release(ref vectorPath);
|
||||
if (path != null) Pathfinding.Util.ListPool<GraphNode>.Release(ref path);
|
||||
// Clear the callback to remove a potential memory leak
|
||||
// while the path is in the pool (which it could be for a long time).
|
||||
callback = null;
|
||||
immediateCallback = null;
|
||||
traversalProvider = null;
|
||||
pathHandler = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reset all values to their default values.
|
||||
///
|
||||
/// Note: All inheriting path types (e.g ConstantPath, RandomPath, etc.) which declare their own variables need to
|
||||
/// override this function, resetting ALL their variables to enable pooling of paths.
|
||||
/// If this is not done, trying to use that path type for pooling could result in weird behaviour.
|
||||
/// The best way is to reset to default values the variables declared in the extended path type and then
|
||||
/// call the base function in inheriting types with base.Reset().
|
||||
/// </summary>
|
||||
protected virtual void Reset () {
|
||||
#if ASTAR_POOL_DEBUG
|
||||
pathTraceInfo = "This path was got from the pool or created from here (stacktrace):\n";
|
||||
pathTraceInfo += System.Environment.StackTrace;
|
||||
#endif
|
||||
|
||||
if (System.Object.ReferenceEquals(AstarPath.active, null))
|
||||
throw new System.NullReferenceException("No AstarPath object found in the scene. " +
|
||||
"Make sure there is one or do not create paths in Awake");
|
||||
|
||||
hasBeenReset = true;
|
||||
PipelineState = (int)PathState.Created;
|
||||
releasedNotSilent = false;
|
||||
|
||||
pathHandler = null;
|
||||
callback = null;
|
||||
immediateCallback = null;
|
||||
errorLog = "";
|
||||
completeState = PathCompleteState.NotCalculated;
|
||||
|
||||
path = Pathfinding.Util.ListPool<GraphNode>.Claim();
|
||||
vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim();
|
||||
|
||||
currentR = null;
|
||||
|
||||
duration = 0;
|
||||
searchedNodes = 0;
|
||||
|
||||
nnConstraint = PathNNConstraint.Default;
|
||||
next = null;
|
||||
|
||||
heuristic = AstarPath.active.heuristic;
|
||||
heuristicScale = AstarPath.active.heuristicScale;
|
||||
|
||||
enabledTags = -1;
|
||||
tagPenalties = null;
|
||||
|
||||
pathID = AstarPath.active.GetNextPathID();
|
||||
|
||||
hTarget = Int3.zero;
|
||||
hTargetNode = null;
|
||||
|
||||
traversalProvider = null;
|
||||
}
|
||||
|
||||
/// <summary>List of claims on this path with reference objects</summary>
|
||||
private List<System.Object> claimed = new List<System.Object>();
|
||||
|
||||
/// <summary>
|
||||
/// True if the path has been released with a non-silent call yet.
|
||||
///
|
||||
/// See: Release
|
||||
/// See: Claim
|
||||
/// </summary>
|
||||
private bool releasedNotSilent;
|
||||
|
||||
/// <summary>
|
||||
/// Claim this path (pooling).
|
||||
/// A claim on a path will ensure that it is not pooled.
|
||||
/// If you are using a path, you will want to claim it when you first get it and then release it when you will not
|
||||
/// use it anymore. When there are no claims on the path, it will be reset and put in a pool.
|
||||
///
|
||||
/// This is essentially just reference counting.
|
||||
///
|
||||
/// The object passed to this method is merely used as a way to more easily detect when pooling is not done correctly.
|
||||
/// It can be any object, when used from a movement script you can just pass "this". This class will throw an exception
|
||||
/// if you try to call Claim on the same path twice with the same object (which is usually not what you want) or
|
||||
/// if you try to call Release with an object that has not been used in a Claim call for that path.
|
||||
/// The object passed to the Claim method needs to be the same as the one you pass to this method.
|
||||
///
|
||||
/// See: Release
|
||||
/// See: Pool
|
||||
/// See: pooling (view in online documentation for working links)
|
||||
/// See: https://en.wikipedia.org/wiki/Reference_counting
|
||||
/// </summary>
|
||||
public void Claim (System.Object o) {
|
||||
if (System.Object.ReferenceEquals(o, null)) throw new System.ArgumentNullException("o");
|
||||
|
||||
for (int i = 0; i < claimed.Count; i++) {
|
||||
// Need to use ReferenceEquals because it might be called from another thread
|
||||
if (System.Object.ReferenceEquals(claimed[i], o))
|
||||
throw new System.ArgumentException("You have already claimed the path with that object ("+o+"). Are you claiming the path with the same object twice?");
|
||||
}
|
||||
|
||||
claimed.Add(o);
|
||||
#if ASTAR_POOL_DEBUG
|
||||
claimInfo.Add(o.ToString() + "\n\nClaimed from:\n" + System.Environment.StackTrace);
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the path silently (pooling).
|
||||
/// Deprecated: Use Release(o, true) instead
|
||||
/// </summary>
|
||||
[System.Obsolete("Use Release(o, true) instead")]
|
||||
internal void ReleaseSilent (System.Object o) {
|
||||
Release(o, true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases a path claim (pooling).
|
||||
/// Removes the claim of the path by the specified object.
|
||||
/// When the claim count reaches zero, the path will be pooled, all variables will be cleared and the path will be put in a pool to be used again.
|
||||
/// This is great for performance since fewer allocations are made.
|
||||
///
|
||||
/// If the silent parameter is true, this method will remove the claim by the specified object
|
||||
/// but the path will not be pooled if the claim count reches zero unless a Release call (not silent) has been made earlier.
|
||||
/// This is used by the internal pathfinding components such as Seeker and AstarPath so that they will not cause paths to be pooled.
|
||||
/// This enables users to skip the claim/release calls if they want without the path being pooled by the Seeker or AstarPath and
|
||||
/// thus causing strange bugs.
|
||||
///
|
||||
/// See: Claim
|
||||
/// See: PathPool
|
||||
/// </summary>
|
||||
public void Release (System.Object o, bool silent = false) {
|
||||
if (o == null) throw new System.ArgumentNullException("o");
|
||||
|
||||
for (int i = 0; i < claimed.Count; i++) {
|
||||
// Need to use ReferenceEquals because it might be called from another thread
|
||||
if (System.Object.ReferenceEquals(claimed[i], o)) {
|
||||
claimed.RemoveAt(i);
|
||||
#if ASTAR_POOL_DEBUG
|
||||
claimInfo.RemoveAt(i);
|
||||
#endif
|
||||
if (!silent) {
|
||||
releasedNotSilent = true;
|
||||
}
|
||||
|
||||
if (claimed.Count == 0 && releasedNotSilent) {
|
||||
PathPool.Pool(this);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (claimed.Count == 0) {
|
||||
throw new System.ArgumentException("You are releasing a path which is not claimed at all (most likely it has been pooled already). " +
|
||||
"Are you releasing the path with the same object ("+o+") twice?" +
|
||||
"\nCheck out the documentation on path pooling for help.");
|
||||
}
|
||||
throw new System.ArgumentException("You are releasing a path which has not been claimed with this object ("+o+"). " +
|
||||
"Are you releasing the path with the same object twice?\n" +
|
||||
"Check out the documentation on path pooling for help.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Traces the calculated path from the end node to the start.
|
||||
/// This will build an array (<see cref="path)"/> of the nodes this path will pass through and also set the <see cref="vectorPath"/> array to the <see cref="path"/> arrays positions.
|
||||
/// Assumes the <see cref="vectorPath"/> and <see cref="path"/> are empty and not null (which will be the case for a correctly initialized path).
|
||||
/// </summary>
|
||||
protected virtual void Trace (PathNode from) {
|
||||
// Current node we are processing
|
||||
PathNode c = from;
|
||||
int count = 0;
|
||||
|
||||
while (c != null) {
|
||||
c = c.parent;
|
||||
count++;
|
||||
if (count > 2048) {
|
||||
Debug.LogWarning("Infinite loop? >2048 node path. Remove this message if you really have that long paths (Path.cs, Trace method)");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure capacities for lists
|
||||
AstarProfiler.StartProfile("Check List Capacities");
|
||||
|
||||
if (path.Capacity < count) path.Capacity = count;
|
||||
if (vectorPath.Capacity < count) vectorPath.Capacity = count;
|
||||
|
||||
AstarProfiler.EndProfile();
|
||||
|
||||
c = from;
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
path.Add(c.node);
|
||||
c = c.parent;
|
||||
}
|
||||
|
||||
// Reverse
|
||||
int half = count/2;
|
||||
for (int i = 0; i < half; i++) {
|
||||
var tmp = path[i];
|
||||
path[i] = path[count-i-1];
|
||||
path[count - i - 1] = tmp;
|
||||
}
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
vectorPath.Add((Vector3)path[i].position);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes text shared for all overrides of DebugString to the string builder.
|
||||
/// See: DebugString
|
||||
/// </summary>
|
||||
protected void DebugStringPrefix (PathLog logMode, System.Text.StringBuilder text) {
|
||||
text.Append(error ? "Path Failed : " : "Path Completed : ");
|
||||
text.Append("Computation Time ");
|
||||
text.Append(duration.ToString(logMode == PathLog.Heavy ? "0.000 ms " : "0.00 ms "));
|
||||
|
||||
text.Append("Searched Nodes ").Append(searchedNodes);
|
||||
|
||||
if (!error) {
|
||||
text.Append(" Path Length ");
|
||||
text.Append(path == null ? "Null" : path.Count.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes text shared for all overrides of DebugString to the string builder.
|
||||
/// See: DebugString
|
||||
/// </summary>
|
||||
protected void DebugStringSuffix (PathLog logMode, System.Text.StringBuilder text) {
|
||||
if (error) {
|
||||
text.Append("\nError: ").Append(errorLog);
|
||||
}
|
||||
|
||||
// Can only print this from the Unity thread
|
||||
// since otherwise an exception might be thrown
|
||||
if (logMode == PathLog.Heavy && !AstarPath.active.IsUsingMultithreading) {
|
||||
text.Append("\nCallback references ");
|
||||
if (callback != null) text.Append(callback.Target.GetType().FullName).AppendLine();
|
||||
else text.AppendLine("NULL");
|
||||
}
|
||||
|
||||
text.Append("\nPath Number ").Append(pathID).Append(" (unique id)");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a string with information about it.
|
||||
/// More information is emitted when logMode == Heavy.
|
||||
/// An empty string is returned if logMode == None
|
||||
/// or logMode == OnlyErrors and this path did not fail.
|
||||
/// </summary>
|
||||
protected virtual string DebugString (PathLog logMode) {
|
||||
if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors)) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// Get a cached string builder for this thread
|
||||
System.Text.StringBuilder text = pathHandler.DebugStringBuilder;
|
||||
text.Length = 0;
|
||||
|
||||
DebugStringPrefix(logMode, text);
|
||||
DebugStringSuffix(logMode, text);
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Calls callback to return the calculated path. See: <see cref="callback"/></summary>
|
||||
protected virtual void ReturnPath () {
|
||||
if (callback != null) {
|
||||
callback(this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prepares low level path variables for calculation.
|
||||
/// Called before a path search will take place.
|
||||
/// Always called before the Prepare, Initialize and CalculateStep functions
|
||||
/// </summary>
|
||||
protected void PrepareBase (PathHandler pathHandler) {
|
||||
//Path IDs have overflowed 65K, cleanup is needed
|
||||
//Since pathIDs are handed out sequentially, we can do this
|
||||
if (pathHandler.PathID > pathID) {
|
||||
pathHandler.ClearPathIDs();
|
||||
}
|
||||
|
||||
//Make sure the path has a reference to the pathHandler
|
||||
this.pathHandler = pathHandler;
|
||||
//Assign relevant path data to the pathHandler
|
||||
pathHandler.InitializeForPath(this);
|
||||
|
||||
// Make sure that internalTagPenalties is an array which has the length 32
|
||||
if (internalTagPenalties == null || internalTagPenalties.Length != 32)
|
||||
internalTagPenalties = ZeroTagPenalties;
|
||||
|
||||
try {
|
||||
ErrorCheck();
|
||||
} catch (System.Exception e) {
|
||||
FailWithError(e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called before the path is started.
|
||||
/// Called right before Initialize
|
||||
/// </summary>
|
||||
protected abstract void Prepare();
|
||||
|
||||
/// <summary>
|
||||
/// Always called after the path has been calculated.
|
||||
/// Guaranteed to be called before other paths have been calculated on
|
||||
/// the same thread.
|
||||
/// Use for cleaning up things like node tagging and similar.
|
||||
/// </summary>
|
||||
protected virtual void Cleanup () {}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the path.
|
||||
/// Sets up the open list and adds the first node to it
|
||||
/// </summary>
|
||||
protected abstract void Initialize();
|
||||
|
||||
/// <summary>Calculates the until it is complete or the time has progressed past targetTick</summary>
|
||||
protected abstract void CalculateStep(long targetTick);
|
||||
|
||||
PathHandler IPathInternals.PathHandler { get { return pathHandler; } }
|
||||
void IPathInternals.OnEnterPool () { OnEnterPool(); }
|
||||
void IPathInternals.Reset () { Reset(); }
|
||||
void IPathInternals.ReturnPath () { ReturnPath(); }
|
||||
void IPathInternals.PrepareBase (PathHandler handler) { PrepareBase(handler); }
|
||||
void IPathInternals.Prepare () { Prepare(); }
|
||||
void IPathInternals.Cleanup () { Cleanup(); }
|
||||
void IPathInternals.Initialize () { Initialize(); }
|
||||
void IPathInternals.CalculateStep (long targetTick) { CalculateStep(targetTick); }
|
||||
string IPathInternals.DebugString (PathLog logMode) { return DebugString(logMode); }
|
||||
}
|
||||
|
||||
/// <summary>Used for hiding internal methods of the Path class</summary>
|
||||
internal interface IPathInternals {
|
||||
PathHandler PathHandler { get; }
|
||||
bool Pooled { get; set; }
|
||||
void AdvanceState(PathState s);
|
||||
void OnEnterPool();
|
||||
void Reset();
|
||||
void ReturnPath();
|
||||
void PrepareBase(PathHandler handler);
|
||||
void Prepare();
|
||||
void Initialize();
|
||||
void Cleanup();
|
||||
void CalculateStep(long targetTick);
|
||||
string DebugString(PathLog logMode);
|
||||
}
|
||||
}
|
7
AR/Assets/AstarPathfindingProject/Core/Path.cs.meta
generated
Normal file
7
AR/Assets/AstarPathfindingProject/Core/Path.cs.meta
generated
Normal file
@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b179046d83ec84f0c91efc5335f78a30
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
209
AR/Assets/AstarPathfindingProject/Core/PathHandler.cs
Normal file
209
AR/Assets/AstarPathfindingProject/Core/PathHandler.cs
Normal file
@ -0,0 +1,209 @@
|
||||
#define DECREASE_KEY
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Pathfinding {
|
||||
/// <summary>
|
||||
/// Stores temporary node data for a single pathfinding request.
|
||||
/// Every node has one PathNode per thread used.
|
||||
/// It stores e.g G score, H score and other temporary variables needed
|
||||
/// for path calculation, but which are not part of the graph structure.
|
||||
///
|
||||
/// See: Pathfinding.PathHandler
|
||||
/// See: https://en.wikipedia.org/wiki/A*_search_algorithm
|
||||
/// </summary>
|
||||
public class PathNode {
|
||||
/// <summary>Reference to the actual graph node</summary>
|
||||
public GraphNode node;
|
||||
|
||||
/// <summary>Parent node in the search tree</summary>
|
||||
public PathNode parent;
|
||||
|
||||
/// <summary>The path request (in this thread, if multithreading is used) which last used this node</summary>
|
||||
public ushort pathID;
|
||||
|
||||
#if DECREASE_KEY
|
||||
/// <summary>
|
||||
/// Index of the node in the binary heap.
|
||||
/// The open list in the A* algorithm is backed by a binary heap.
|
||||
/// To support fast 'decrease key' operations, the index of the node
|
||||
/// is saved here.
|
||||
/// </summary>
|
||||
public ushort heapIndex = BinaryHeap.NotInHeap;
|
||||
#endif
|
||||
|
||||
/// <summary>Bitpacked variable which stores several fields</summary>
|
||||
private uint flags;
|
||||
|
||||
/// <summary>Cost uses the first 28 bits</summary>
|
||||
private const uint CostMask = (1U << 28) - 1U;
|
||||
|
||||
/// <summary>Flag 1 is at bit 28</summary>
|
||||
private const int Flag1Offset = 28;
|
||||
private const uint Flag1Mask = (uint)(1 << Flag1Offset);
|
||||
|
||||
/// <summary>Flag 2 is at bit 29</summary>
|
||||
private const int Flag2Offset = 29;
|
||||
private const uint Flag2Mask = (uint)(1 << Flag2Offset);
|
||||
|
||||
public uint cost {
|
||||
get {
|
||||
return flags & CostMask;
|
||||
}
|
||||
set {
|
||||
flags = (flags & ~CostMask) | value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use as temporary flag during pathfinding.
|
||||
/// Pathfinders (only) can use this during pathfinding to mark
|
||||
/// nodes. When done, this flag should be reverted to its default state (false) to
|
||||
/// avoid messing up other pathfinding requests.
|
||||
/// </summary>
|
||||
public bool flag1 {
|
||||
get {
|
||||
return (flags & Flag1Mask) != 0;
|
||||
}
|
||||
set {
|
||||
flags = (flags & ~Flag1Mask) | (value ? Flag1Mask : 0U);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use as temporary flag during pathfinding.
|
||||
/// Pathfinders (only) can use this during pathfinding to mark
|
||||
/// nodes. When done, this flag should be reverted to its default state (false) to
|
||||
/// avoid messing up other pathfinding requests.
|
||||
/// </summary>
|
||||
public bool flag2 {
|
||||
get {
|
||||
return (flags & Flag2Mask) != 0;
|
||||
}
|
||||
set {
|
||||
flags = (flags & ~Flag2Mask) | (value ? Flag2Mask : 0U);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Backing field for the G score</summary>
|
||||
private uint g;
|
||||
|
||||
/// <summary>Backing field for the H score</summary>
|
||||
private uint h;
|
||||
|
||||
/// <summary>G score, cost to get to this node</summary>
|
||||
public uint G { get { return g; } set { g = value; } }
|
||||
|
||||
/// <summary>H score, estimated cost to get to to the target</summary>
|
||||
public uint H { get { return h; } set { h = value; } }
|
||||
|
||||
/// <summary>F score. H score + G score</summary>
|
||||
public uint F { get { return g+h; } }
|
||||
|
||||
public void UpdateG (Path path) {
|
||||
#if ASTAR_NO_TRAVERSAL_COST
|
||||
g = parent.g + cost;
|
||||
#else
|
||||
g = parent.g + cost + path.GetTraversalCost(node);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Handles thread specific path data.</summary>
|
||||
public class PathHandler {
|
||||
/// <summary>
|
||||
/// Current PathID.
|
||||
/// See: <see cref="PathID"/>
|
||||
/// </summary>
|
||||
private ushort pathID;
|
||||
|
||||
public readonly int threadID;
|
||||
public readonly int totalThreadCount;
|
||||
|
||||
/// <summary>
|
||||
/// Binary heap to keep track of nodes on the "Open list".
|
||||
/// See: https://en.wikipedia.org/wiki/A*_search_algorithm
|
||||
/// </summary>
|
||||
public readonly BinaryHeap heap = new BinaryHeap(128);
|
||||
|
||||
/// <summary>ID for the path currently being calculated or last path that was calculated</summary>
|
||||
public ushort PathID { get { return pathID; } }
|
||||
|
||||
/// <summary>Array of all PathNodes</summary>
|
||||
public PathNode[] nodes = new PathNode[0];
|
||||
|
||||
/// <summary>
|
||||
/// StringBuilder that paths can use to build debug strings.
|
||||
/// Better for performance and memory usage to use a single StringBuilder instead of each path creating its own
|
||||
/// </summary>
|
||||
public readonly System.Text.StringBuilder DebugStringBuilder = new System.Text.StringBuilder();
|
||||
|
||||
public PathHandler (int threadID, int totalThreadCount) {
|
||||
this.threadID = threadID;
|
||||
this.totalThreadCount = totalThreadCount;
|
||||
}
|
||||
|
||||
public void InitializeForPath (Path p) {
|
||||
pathID = p.pathID;
|
||||
heap.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Internal method to clean up node data</summary>
|
||||
public void DestroyNode (GraphNode node) {
|
||||
PathNode pn = GetPathNode(node);
|
||||
|
||||
// Clean up references to help the GC
|
||||
pn.node = null;
|
||||
pn.parent = null;
|
||||
// This is not required for pathfinding, but not clearing it may confuse gizmo drawing for a fraction of a second.
|
||||
// Especially when 'Show Search Tree' is enabled
|
||||
pn.pathID = 0;
|
||||
pn.G = 0;
|
||||
pn.H = 0;
|
||||
}
|
||||
|
||||
/// <summary>Internal method to initialize node data</summary>
|
||||
public void InitializeNode (GraphNode node) {
|
||||
//Get the index of the node
|
||||
int ind = node.NodeIndex;
|
||||
|
||||
if (ind >= nodes.Length) {
|
||||
// Grow by a factor of 2
|
||||
PathNode[] newNodes = new PathNode[System.Math.Max(128, nodes.Length*2)];
|
||||
nodes.CopyTo(newNodes, 0);
|
||||
// Initialize all PathNode instances at once
|
||||
// It is important that we do this here and don't for example leave the entries as NULL and initialize
|
||||
// them lazily. By allocating them all at once we are much more likely to allocate the PathNodes close
|
||||
// to each other in memory (most systems use some kind of bumb-allocator) and this improves cache locality
|
||||
// and reduces false sharing (which would happen if we allocated PathNodes for the different threads close
|
||||
// to each other). This has been profiled to give around a 4% difference in overall pathfinding performance.
|
||||
for (int i = nodes.Length; i < newNodes.Length; i++) newNodes[i] = new PathNode();
|
||||
nodes = newNodes;
|
||||
}
|
||||
|
||||
nodes[ind].node = node;
|
||||
}
|
||||
|
||||
public PathNode GetPathNode (int nodeIndex) {
|
||||
return nodes[nodeIndex];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the PathNode corresponding to the specified node.
|
||||
/// The PathNode is specific to this PathHandler since multiple PathHandlers
|
||||
/// are used at the same time if multithreading is enabled.
|
||||
/// </summary>
|
||||
public PathNode GetPathNode (GraphNode node) {
|
||||
return nodes[node.NodeIndex];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Set all nodes' pathIDs to 0.
|
||||
/// See: Pathfinding.PathNode.pathID
|
||||
/// </summary>
|
||||
public void ClearPathIDs () {
|
||||
for (int i = 0; i < nodes.Length; i++) {
|
||||
if (nodes[i] != null) nodes[i].pathID = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
8
AR/Assets/AstarPathfindingProject/Core/PathHandler.cs.meta
generated
Normal file
8
AR/Assets/AstarPathfindingProject/Core/PathHandler.cs.meta
generated
Normal file
@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7cc885607b0534cc6a4a34c4caa58d89
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user