public void Reset() { g = 0; h = 0; parent = null; State = CellState.Empty; Path = PathState.None; }
/** 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 recycling of paths. * If this is not done, trying to use that path type for pooling might result in weird behaviour. * The best way is to reset to default values the variables declared in the extended path type and then * call this base function in inheriting types with base.Reset (). * * \warning This function should not be called manually. */ public 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; state = (int)PathState.Created; releasedNotSilent = false; pathHandler = null; callback = null; _errorLog = ""; pathCompleteState = PathCompleteState.NotCalculated; path = Pathfinding.Util.ListPool <GraphNode> .Claim(); vectorPath = Pathfinding.Util.ListPool <Vector3> .Claim(); currentR = null; duration = 0; searchIterations = 0; searchedNodes = 0; //calltime nnConstraint = PathNNConstraint.Default; next = null; radius = 0; walkabilityMask = -1; height = 0; turnRadius = 0; speed = 0; //heuristic = (Heuristic)0; //heuristicScale = 1F; heuristic = AstarPath.active.heuristic; heuristicScale = AstarPath.active.heuristicScale; pathID = 0; enabledTags = -1; tagPenalties = null; callTime = System.DateTime.UtcNow; pathID = AstarPath.active.GetNextPathID(); hTarget = Int3.zero; hTargetNode = null; }
void IPathInternals.AdvanceState(PathState s) { object obj = this.stateLock; lock (obj) { this.PipelineState = (PathState)Math.Max((int)this.PipelineState, (int)s); } }
public static void WriteJson(this PathState value, Utf8JsonWriter writer) { switch (value) { case PathState.Static: JsonSerializer.Serialize(writer, "static"); break; case PathState.Dynamic: JsonSerializer.Serialize(writer, "dynamic"); break; } }
public Path(Node start, List <Node> targets, PathRegistry registry) { IsT0 = false; Start = start; Targets = targets; State = PathState.InitialCalulation; _registry = registry; _registry.ActivePaths.Add(this); }
public void AdvanceState(PathState s) { object stateLock = this.stateLock; lock (stateLock) { this.state = (PathState)Math.Max((int)this.state, (int)s); } }
public void Initialize(Node node) { this.node = node; this.state = node.State as PathState; material = GetComponent <MeshRenderer>().material; UpdateVisual(); }
public PathContext(ReadOnlySpan <char> text) { _text = text; _state = PathState.None; _index = 0; _character = '\0'; _count = 0; _whitespaces = 0; _errorMessage = null; }
public PathContext( DiagnosticMessages diagnosticMessages, FileSystemWatcher watcher, ApplicationEventsPresenter applicationEventsPresenter, PathStates pathStates) { _diagnosticMessages = diagnosticMessages; _watcher = watcher; _applicationEventsPresenter = applicationEventsPresenter; _pathStates = pathStates; _currentState = _pathStates.PathNotDetectedState(); }
/** 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 recycling of paths. * If this is not done, trying to use that path type for pooling might result in weird behaviour. * The best way is to reset to default values the variables declared in the extended path type and then * call this base function in inheriting types with base.Reset (). * * \warning This function should not be called manually. */ public virtual void Reset() { if (ReferenceEquals(AstarPath.active, null)) { throw new NullReferenceException("No AstarPath object found in the scene. " + "Make sure there is one or do not create paths in Awake"); } hasBeenReset = true; state = (int)PathState.Created; releasedNotSilent = false; pathHandler = null; callback = null; _errorLog = ""; pathCompleteState = PathCompleteState.NotCalculated; path = ListPool <GraphNode> .Claim(); vectorPath = ListPool <Vector3> .Claim(); currentR = null; duration = 0; searchIterations = 0; searchedNodes = 0; //calltime nnConstraint = PathNNConstraint.Default; next = null; radius = 0; walkabilityMask = -1; height = 0; turnRadius = 0; speed = 0; //heuristic = (Heuristic)0; //heuristicScale = 1F; heuristic = AstarPath.active.heuristic; heuristicScale = AstarPath.active.heuristicScale; pathID = 0; enabledTags = -1; tagPenalties = null; callTime = DateTime.UtcNow; pathID = AstarPath.active.GetNextPathID(); hTarget = Int3.zero; hTargetNode = null; }
/// <summary> /// Measures layout entities and defines unassigned properties. /// </summary> /// <param name="State">Current drawing state.</param> /// <param name="PathState">Current path state.</param> public void Measure(DrawingState State, PathState PathState) { if (this.HasChildren) { foreach (ILayoutElement E in this.Children) { if (E.IsVisible && E is ISegment Segment) { Segment.Measure(State, PathState); } } } }
/// <summary> /// Draws the segments of the path. /// </summary> /// <param name="State">Current drawing state.</param> /// <param name="PathState">Current path state.</param> /// <param name="Path">Path being generated.</param> public void Draw(DrawingState State, PathState PathState, SKPath Path) { if (this.HasChildren) { foreach (ILayoutElement E in this.Children) { if (E.IsVisible && E is ISegment Segment) { Segment.Draw(State, PathState, Path); } } } }
void Update() { if (!IsEnabled && State != PathState.Disabled) { State = PathState.Disabled; ToggleTiles(); } else if (IsEnabled && State != PathState.Enabled) { State = PathState.Enabled; ToggleTiles(); } }
public PathFollowing setStateToPlaying() { currentState = PathState.Playing; currentPoint = 0; Animator anim = GetComponent <Animator>(); if (anim != null) { anim.SetBool("HorizontalMovement", true); } return(this); }
public PathState DepthFirstSearch( Point from, Func <PathState, bool> func, Func <PathState, bool> isForbidden = null) { if (isForbidden == null) { isForbidden = x => false; } var visited = new HashSet <Point>() { from }; var stack = new Stack <PathState>(); stack.Push(new PathState() { Point = from }); while (stack.Any()) { var state = stack.Pop(); foreach (var newPoint in state.Point.AdjacentPoints()) { var pathState = new PathState() { Point = newPoint, Depth = state.Depth + 1, PreviousState = state }; if (!IsWall(newPoint) && !visited.Contains(newPoint) && !isForbidden(pathState)) { if (func(pathState)) { return(pathState); } visited.Add(newPoint); stack.Push(pathState); } } } return(null); }
public PathState BreadthFirstSearch( Point from, Func <PathState, bool> func, Func <PathState, bool> isForbidden = null) { if (isForbidden == null) { isForbidden = x => false; } var visited = new HashSet <Point>() { from }; var queue = new PriorityQueue <PathState>((lhs, rhs) => lhs.Depth > rhs.Depth); queue.Push(new PathState() { Point = from }); while (!queue.IsEmpty()) { var state = queue.Pop(); foreach (var newPoint in state.Point.AdjacentPoints()) { var pathState = new PathState() { Point = newPoint, Depth = state.Depth + 1, PreviousState = state }; if (!IsWall(newPoint) && !visited.Contains(newPoint) && !isForbidden(pathState)) { if (func(pathState)) { return(pathState); } visited.Add(newPoint); queue.Push(pathState); } } } return(null); }
static int AdvanceState(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); Pathfinding.Path obj = (Pathfinding.Path)ToLua.CheckObject <Pathfinding.Path>(L, 1); PathState arg0 = (PathState)ToLua.CheckObject(L, 2, typeof(PathState)); obj.AdvanceState(arg0); return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static int GetState(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); Pathfinding.Path obj = (Pathfinding.Path)ToLua.CheckObject <Pathfinding.Path>(L, 1); PathState o = obj.GetState(); ToLua.Push(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
public virtual void Reset() { if (object.ReferenceEquals(AstarPath.active, null)) { Debug.LogError("No AstarPath object found in the scene. Make sure there is one or do not create paths in Awake"); } this.hasBeenReset = true; this.state = PathState.Created; this.releasedNotSilent = false; this.pathHandler = null; this.callback = null; this._errorLog = string.Empty; this.pathCompleteState = PathCompleteState.NotCalculated; this.path = ListPool <GraphNode> .Claim(64); this.vectorPath = ListPool <VInt3> .Claim(64); this.currentR = null; this.duration = 0f; this.searchIterations = 0; this.searchedNodes = 0; this.nnConstraint = PathNNConstraint.Default; this.next = null; this.radius = 0; this.walkabilityMask = -1; this.height = 0; this.turnRadius = 0; this.speed = 0; this.pathID = 0; this.enabledTags = -1; this.tagPenalties = null; this.callTime = DateTime.get_UtcNow(); AstarPath active = AstarPath.active; if (active != null) { this.pathID = AstarPath.active.GetNextPathID(); this.heuristic = AstarPath.active.heuristic; this.heuristicScale = AstarPath.active.heuristicScale; } else { this.heuristic = Heuristic.Manhattan; this.heuristicScale = 1f; } this.hTarget = VInt3.zero; this.hTargetNode = null; }
//stops everything and gets a path. If it cannot find a path in the milliseconds given, it returns null. public List <Vector3> GetPathBlockingCall(Vector3 start, Vector3 finish, int maxMillisecondsToBlock) { PriorityTree newNodeQueue = null; PathState pathState = PathState.NULL; float pathLength = 0; List <int> path = GetPath(GetClosestNode(start), GetClosestNode(finish), null, DateTime.Now.AddMilliseconds(maxMillisecondsToBlock), out newNodeQueue, out pathState, out pathLength); List <Vector3> ptsPath = null; if (path != null) { ptsPath = new List <Vector3>(); foreach (int node in path) { ptsPath.Add(pts[node]); } } return(ptsPath); }
/// <inheritdoc /> protected override Vector3 Start(GameObject entity, long currentTime) { //We don't need to deal with time when a position change occurs. //TODO: This is demo code, we should handle actual movement differently. //This sets the initial position for the path, offset by the timestamp in the movement data. //entity.transform.position; State = ComputeInitialPathState(currentTime); //If pathing was disabled it means we're at the end when we start, we need to set to last point if (isFinished) { return(entity.transform.position = MovementData.MovementPath[MovementData.MovementPath.Count - 1]); } //Just call update, which will set the position. return(InternalUpdate(entity, currentTime)); }
/// <summary> /// Move the path follower along the Path. Set PathState to Arrived once the follower /// has no more points to move toward /// </summary> protected virtual void MoveAlongPath() { if (nextPoint == Vector3.zero && !path.GetNextPoint(ref nextPoint)) { pathState = PathState.Arrived; return; } Vector2 delta = nextPoint - transform.position; if (delta.magnitude <= distToTargetNextPoint && !path.GetNextPoint(ref nextPoint)) { pathState = PathState.Arrived; return; } transform.position = MoveTowardsNextPoint(); }
/// <summary> /// Create an action where the Old Man walks on a set path /// </summary> /// <param name="priority">How important the action is</param> /// <param name="name">The name of this action</param> /// <param name="points">Array of all points</param> /// <param name="startPoint">Start index for this point</param> /// <param name="thoughtItem">The sprite to put in the thought bubble. Can be left null for no item to be shown</param> /// <param name="discardTime">The amount of time this action can spend in the queue without being discarded. 0 for infinite.</param> public OM_Action_Path(float priority, string name, OM_MoveData[] points, int startPoint = 0, Sprite thoughtItem = null, float discardTime = 0) : base(priority, name, OM_ActionType.Path, thoughtItem, discardTime) { this.points = points; //Keep the start point in bounds if (startPoint >= points.Length || startPoint < 0) { target = 0; } else { target = startPoint; } state = PathState.Walking; waitTimer = 0; }
public Grid2D(int gridSizeX, int gridSizeY) { sizeX = gridSizeX; sizeY = gridSizeY; nodes = new List <Node>(); for (int y = 0; y < sizeY; y++) { for (int x = 0; x < sizeX; x++) { PathState pathState = new PathState(x, y, TerrainType.Grass, true); Node newNode = new Node(pathState); nodes.Add(newNode); } } Instance = this; }
public void Recalculate(Node removedNode, VoxelGraph graph) { if (State.Equals(PathState.Recalculation)) { Thread.Abort(); } if (Nodes[Nodes.Count - 1].Equals(removedNode)) { State = PathState.Invalid; } else { State = PathState.Recalculation; var currentNode = GetNode(_currentNode); if (currentNode == null) { State = PathState.Invalid; } else { var p2 = Calculate(graph, currentNode.Position, Targets.Select(t => t.Position).ToList()); if (p2 == null) { State = PathState.Invalid; } else { Thread = p2.Thread; p2.OnFinish = () => { Nodes = p2.Nodes; Start = p2.Start; Length = p2.Length; IsT0 = p2.IsT0; State = p2.State; p2.Dispose(); }; } } } }
public void GenerateHeadToPath(Vector2 headToPosition) { Vector2 dir = (headToPosition - (Vector2)transform.position).normalized; float distance = Vector2.Distance((Vector2)transform.position, headToPosition); int numChunks = Mathf.RoundToInt(distance / chunkSize); pathSize = numChunks; pathLR.positionCount = numChunks; pathLR.loop = false; //path = new Path[numChunks]; if (numChunks > 0) { path[0] = new Path((Vector2)transform.position, Vector2.zero); for (int i = 0; i < numChunks; i++) { path[i].end = path[i].start + dir * chunkSize + new Vector2(0f, Random.Range(-yOffset, yOffset)); if (i < numChunks - 1) { //path[i + 1] = new Path(path[i].end, Vector2.zero); path[i + 1].start = path[i].end; } } path[numChunks - 1].end = headToPosition; } else { //path[0] = new Path((Vector2)transform.position, headToPosition); path[0].start = (Vector2)transform.position; path[0].end = headToPosition; } for (int i = 0; i < numChunks; i++) { pathLR.SetPosition(i, path[i].start); } pathState = PathState.HEAD_TO; }
public void ValidationPath() { if (!Directory.Exists(Importer.DestinationPath)) { State = PathState.PathError; return; } string fullPath = GetDestinationPath(Importer.DestinationPath, Importer.resourceRoots, Importer.resourceDestinationType); if (!Misc.IsValidPath(fullPath)) { State = PathState.PathError; } else if (File.Exists(fullPath)) { State = PathState.Overwrite; } else { State = PathState.Writable; } }
/// <summary> /// Code for the action that gets called in OldMan's update /// </summary> /// <param name="om">The Old Man script</param> public override void ExecuteAction(OldMan om) { if (!Active || Completed) { return; } //State control switch (state) { case PathState.Walking: if (!om.Agent.pathPending && om.Agent.remainingDistance < 0.3f) { //Wait if there is a value passed in, otherwise go to the next point if (points[target].WaitAfterReaching > 0) { waitTimer = 0; state = PathState.Waiting; } else { SetNextPoint(om); } } break; //Wait for a set amount of seconds case PathState.Waiting: waitTimer += Time.deltaTime; if (waitTimer > points[target].WaitAfterReaching) { state = PathState.Walking; SetNextPoint(om); } break; } }
public void ValidationPath(string targetDirPath) { if (!Directory.Exists(targetDirPath)) { State = PathState.PathError; return; } string fullPath = Path.Combine(targetDirPath, DestinationName); fullPath = Misc.BackSlashToSlash(fullPath); if (!Misc.IsValidPath(fullPath)) { State = PathState.PathError; } else if (File.Exists(fullPath)) { State = PathState.Overwrite; } else { State = PathState.Writable; } }
/// <summary> /// Draws the shape at a given position & direction. /// </summary> /// <param name="State">Current drawing state.</param> /// <param name="DefaultPen">Default pen, if any, null otherwise</param> /// <param name="DefaultFill">Default fill, if any, null otherwise.</param> /// <param name="X"></param> /// <param name="Y"></param> /// <param name="Direction"></param> public void Draw(DrawingState State, SKPaint DefaultPen, SKPaint DefaultFill, float X, float Y, float Direction) { if (this.HasChildren) { SKPaint PenBak = null; SKPaint FillBak = null; SKPath Path = null; PathState PathState = null; bool HasPenBak = false; bool HasFillBak = false; if (!(DefaultPen is null)) { PenBak = State.ShapePen; State.ShapePen = DefaultPen; HasPenBak = true; } if (!(DefaultFill is null)) { FillBak = State.ShapeFill; State.ShapeFill = DefaultFill; HasFillBak = true; } try { foreach (ILayoutElement Element in this.Children) { if (Element is ISegment Segment) { if (Path is null) { Path = new SKPath(); PathState = new PathState(null, Path, false, false); } PathState.Set0(X, Y); PathState.TurnTowards(Direction); Path.MoveTo(X, Y); Segment.Draw(State, PathState, Path); } else { if (!(Path is null)) { PathState.FlushSpline(); if (!(DefaultFill is null)) { State.Canvas.DrawPath(Path, DefaultFill); } if (!(DefaultPen is null)) { State.Canvas.DrawPath(Path, DefaultPen); } Path.Dispose(); Path = null; PathState = null; } Element.Draw(State); } } if (!(Path is null)) { PathState.FlushSpline(); if (!(DefaultFill is null)) { State.Canvas.DrawPath(Path, DefaultFill); } if (!(DefaultPen is null)) { State.Canvas.DrawPath(Path, DefaultPen); } } } finally { if (HasPenBak) { State.ShapePen = PenBak; } if (HasFillBak) { State.ShapeFill = FillBak; } Path?.Dispose(); } } }
/** 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 recycling of paths. * If this is not done, trying to use that path type for pooling might result in weird behaviour. * The best way is to reset to default values the variables declared in the extended path type and then * call this base function in inheriting types with base.Reset (). * * \warning This function should not be called manually. */ public virtual void Reset () { 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; state = (int)PathState.Created; releasedNotSilent = false; pathHandler = null; callback = null; _errorLog = ""; pathCompleteState = PathCompleteState.NotCalculated; path = Pathfinding.Util.ListPool<GraphNode>.Claim(); vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim(); currentR = null; duration = 0; searchIterations = 0; searchedNodes = 0; //calltime nnConstraint = PathNNConstraint.Default; next = null; heuristic = AstarPath.active.heuristic; heuristicScale = AstarPath.active.heuristicScale; enabledTags = -1; tagPenalties = null; callTime = System.DateTime.UtcNow; pathID = AstarPath.active.GetNextPathID (); hTarget = Int3.zero; hTargetNode = null; }
/** Threadsafe increment of the state */ public void AdvanceState (PathState s) { lock (stateLock) { state = (PathState)System.Math.Max ((int)state, (int)s); } }
/// <summary> /// Test a path between current position and destination. /// </summary> private void TestPath(Vector3D destination, MyEntity destEntity, short runId, bool isAlternate, bool tryAlternates, bool slowDown = false) { if (!lock_testPath.TryAcquireExclusive()) { m_logger.debugLog("Already running, requeue (destination:" + destination + ", destEntity: " + destEntity + ", runId :" + runId + ", isAlternate: " + isAlternate + ", tryAlternates: " + tryAlternates + ", slowDown: " + slowDown + ")", "TestPath()"); LockedQueue<Action> queue = isAlternate ? m_pathLow : m_pathHigh; queue.Enqueue(() => TestPath(destination, destEntity, runId, isAlternate, tryAlternates)); return; } m_logger.debugLog("Running, (destination:" + destination + ", destEntity: " + destEntity + ", runId :" + runId + ", isAlternate: " + isAlternate + ", tryAlternates: " + tryAlternates + ", slowDown: " + slowDown + ")", "TestPath()"); try { if (!isAlternate && !tryAlternates) m_logger.debugLog("velocity based test follows", "TestPath()", Logger.severity.INFO); if (runId != m_runId) { m_logger.debugLog("destination changed, abort", "TestPath()", Logger.severity.DEBUG); return; } if (m_pathChecker.TestFast(m_navBlock, destination, m_ignoreAsteroid, destEntity, m_landing)) { m_logger.debugLog("path is clear (fast)", "TestPath()", Logger.severity.TRACE); PathClear(ref destination, runId, isAlternate, slowDown); return; } MyEntity obstructing; IMyCubeGrid obsGrid; Vector3? pointOfObstruction; if (m_pathChecker.TestSlow(out obstructing, out obsGrid, out pointOfObstruction)) { m_logger.debugLog("path is clear (slow)", "TestPath()", Logger.severity.TRACE); PathClear(ref destination, runId, isAlternate, slowDown); return; } if (runId != m_runId) { m_logger.debugLog("destination changed, abort", "TestPath()", Logger.severity.DEBUG); return; } if (slowDown) { Vector3 displacement = pointOfObstruction.Value - m_navBlock.WorldPosition; m_navSet.Settings_Task_NavWay.SpeedMaxRelative = Vector3.Distance(pointOfObstruction.Value, m_navBlock.WorldPosition) / LookAheadSpeed_Seconds; m_logger.debugLog("Set MaxRelativeSpeed to " + m_navSet.Settings_Task_NavWay.SpeedMaxRelative, "TestPath()", Logger.severity.TRACE); return; } m_pathState = PathState.Searching; m_logger.debugLog("path is blocked by " + obstructing.getBestName() + " at " + pointOfObstruction + ", destEntity: " + destEntity.getBestName(), "TestPath()", Logger.severity.TRACE); if (tryAlternates) { m_pathHigh.Clear(); Vector3 displacement = pointOfObstruction.Value - m_navBlock.WorldPosition; if (m_canChangeCourse) { FindAlternate_AroundObstruction(displacement, pointOfObstruction.Value, obstructing.GetLinearVelocity(), runId); FindAlternate_JustMove(runId); } FindAlternate_HalfwayObstruction(displacement, runId); m_pathLow.Enqueue(() => m_pathState = PathState.Path_Blocked); } } finally { lock_testPath.ReleaseExclusive(); RunItem(); } }
public virtual void Reset() { if (object.ReferenceEquals(AstarPath.active, null)) { throw new NullReferenceException("No AstarPath object found in the scene. Make sure there is one or do not create paths in Awake"); } this.hasBeenReset = true; this.state = PathState.Created; this.releasedNotSilent = false; this.pathHandler = null; this.callback = null; this._errorLog = string.Empty; this.pathCompleteState = PathCompleteState.NotCalculated; this.path = ListPool<GraphNode>.Claim(); this.vectorPath = ListPool<Vector3>.Claim(); this.currentR = null; this.duration = 0f; this.searchIterations = 0; this.searchedNodes = 0; this.nnConstraint = PathNNConstraint.Default; this.next = null; this.heuristic = AstarPath.active.heuristic; this.heuristicScale = AstarPath.active.heuristicScale; this.enabledTags = -1; this.tagPenalties = null; this.callTime = DateTime.UtcNow; this.pathID = AstarPath.active.GetNextPathID(); this.hTarget = Int3.zero; this.hTargetNode = null; }
public abstract bool SetSegmentState(PathState st);
private void PathClear(ref Vector3D destination, byte runId, bool isAlternate, bool slowDown) { if (runId == m_runId) { if (isAlternate) { m_logger.debugLog("Setting waypoint: " + destination, "PathClear()", Logger.severity.DEBUG); new GOLIS(m_mover, m_navSet, destination, true); } if (slowDown) { m_logger.debugLog("Removing speed limit", "PathClear()"); m_navSet.Settings_Task_NavWay.SpeedMaxRelative = float.MaxValue; } m_pathState = PathState.No_Obstruction; m_pathLow.Clear(); } else m_logger.debugLog("destination changed, abort", "PathClear()", Logger.severity.DEBUG); return; }
/** 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 recycling of paths. * If this is not done, trying to use that path type for pooling might result in weird behaviour. * The best way is to reset to default values the variables declared in the extended path type and then * call this base function in inheriting types with base.Reset (). * * \warning This function should not be called manually. */ public 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 (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; state = (int)PathState.Created; releasedNotSilent = false; pathHandler = null; callback = null; _errorLog = ""; pathCompleteState = PathCompleteState.NotCalculated; path = Pathfinding.Util.ListPool<GraphNode>.Claim(); vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim(); currentR = null; duration = 0; searchIterations = 0; searchedNodes = 0; //calltime nnConstraint = PathNNConstraint.Default; next = null; radius = 0; walkabilityMask = -1; height = 0; turnRadius = 0; speed = 0; //heuristic = (Heuristic)0; //heuristicScale = 1F; heuristic = AstarPath.active.heuristic; heuristicScale = AstarPath.active.heuristicScale; pathID = 0; enabledTags = -1; tagPenalties = null; callTime = System.DateTime.UtcNow; pathID = AstarPath.active.GetNextPathID (); hTarget = Int3.zero; }
public void Commit(Path newPath) { CelestialBody.FakeHasGravitationalTurret = false; CelestialBody.FakeHasGravitationalTurretLv2 = false; CelestialBody = null; PathState = PathState.None; }
public void DeferredRollBack() { PathState = PathState.None; }
public PlayerState(GUIPlayer player) { Player = player; CelestialBody = null; PathState = PathState.None; }
/** 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 recycling of paths. * If this is not done, trying to use that path type for pooling might result in weird behaviour. * The best way is to reset to default values the variables declared in the extended path type and then * call this base function in inheriting types with base.Reset (). * * \warning This function should not be called manually. */ public virtual void Reset() { if (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; state = (int)PathState.Created; releasedNotSilent = false; runData = null; callback = null; _errorLog = ""; pathCompleteState = PathCompleteState.NotCalculated; path = Pathfinding.Util.ListPool<Node>.Claim(); vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim(); currentR = null; duration = 0; searchIterations = 0; searchedNodes = 0; //calltime nnConstraint = PathNNConstraint.Default; next = null; radius = 0; walkabilityMask = -1; height = 0; turnRadius = 0; speed = 0; //heuristic = (Heuristic)0; //heuristicScale = 1F; heuristic = AstarPath.active.heuristic; heuristicScale = AstarPath.active.heuristicScale; pathID = 0; enabledTags = -1; tagPenalties = null; callTime = System.DateTime.UtcNow; pathID = AstarPath.active.GetNextPathID (); }
public void TestPath(Vector3 destination, bool landing) { if (m_navSet.Settings_Current.DestinationChanged) { m_logger.debugLog("new destination: " + destination, "TestPath()", Logger.severity.INFO); m_navSet.Settings_Task_NavWay.DestinationChanged = false; m_runId++; m_pathLow.Clear(); m_pathState = PathState.Not_Running; } //else // m_logger.debugLog("destination unchanged", "TestPath()"); if (Globals.UpdateCount < m_nextRunPath) return; m_nextRunPath = Globals.UpdateCount + 10ul; if (m_pathLow.Count != 0) { m_logger.debugLog("path low is running", "TestPath()"); return; } m_navBlock = m_navSet.Settings_Current.NavigationBlock; m_destination = destination; m_ignoreAsteroid = m_navSet.Settings_Current.IgnoreAsteroid; m_landing = landing; m_canChangeCourse = m_navSet.Settings_Current.PathfinderCanChangeCourse; MyEntity destEntity = m_navSet.Settings_Current.DestinationEntity as MyEntity; m_logger.debugLog("DestinationEntity: " + m_navSet.Settings_Current.DestinationEntity.getBestName(), "TestPath()"); byte runId = m_runId; const float minimumDistance = 100f; const float minDistSquared = minimumDistance * minimumDistance; const float seconds = 10f; const float distOverSeconds = minimumDistance / seconds; Vector3 displacement = destination - m_navBlock.WorldPosition; float distanceSquared = displacement.LengthSquared(); float testDistance; Vector3 move_direction = m_grid.Physics.LinearVelocity; float speedSquared = move_direction.LengthSquared(); if (distanceSquared > minDistSquared) { // only look ahead 10 s / 100 m testDistance = speedSquared < distOverSeconds ? minimumDistance : (float)Math.Sqrt(speedSquared) * seconds; if (testDistance * testDistance < distanceSquared) { Vector3 direction = displacement / (float)Math.Sqrt(distanceSquared); destination = m_navBlock.WorldPosition + testDistance * direction; m_logger.debugLog("moved destination: " + destination + ", distance: " + testDistance + ", direction: " + direction, "TestPath()"); } } else m_logger.debugLog("using actual destination: " + destination, "TestPath()"); m_pathHigh.Enqueue(() => TestPath(destination, destEntity, runId, isAlternate: false, tryAlternates: true)); // given velocity and distance, calculate destination if (speedSquared > 1f) { Vector3 moveDest = m_navBlock.WorldPosition + move_direction * LookAheadSpeed_Seconds; m_pathHigh.Enqueue(() => TestPath(moveDest, destEntity, runId, isAlternate: false, tryAlternates: false)); m_pathHigh.Enqueue(() => TestPath(moveDest, null, runId, isAlternate: false, tryAlternates: false, slowDown: true)); } else m_navSet.Settings_Task_NavWay.SpeedMaxRelative = float.MaxValue; RunItem(); }
public void AdvanceState(PathState s) { object obj = this.stateLock; lock (obj) { this.state = (PathState)Math.Max((int)this.state, (int)s); } }
public void ChangeState(PathState state, Path newPath, CelestialBody cb) { CelestialBody = cb; PathState = state; switch (state) { case PathState.ObjectAdded: cb.FakeHasGravitationalTurret = true; newPath.AddCelestialBody(cb, true); break; case PathState.ObjectRemoved: newPath.RemoveCelestialBody(cb); break; case PathState.ObjectUpgraded: cb.FakeHasGravitationalTurretLv2 = true; break; } }
public void TestRotate(Vector3 displacement) { if (Globals.UpdateCount < m_nextRunRotate) return; m_nextRunRotate = Globals.UpdateCount + 10ul; m_navBlock = m_navSet.Settings_Current.NavigationBlock; m_pathHigh.Enqueue(() => { Vector3 axis; Vector3.Normalize(ref displacement, out axis); IMyEntity obstruction; if (m_rotateChecker.TestRotate(axis, m_ignoreAsteroid, out obstruction)) m_rotateState = PathState.No_Obstruction; else m_rotateState = PathState.Path_Blocked; RotateObstruction = obstruction; RunItem(); }); RunItem(); }
public void RollBack(Path newPath) { if (PathState == PathState.None) return; switch (PathState) { case PathState.ObjectAdded: newPath.RemoveCelestialBody(CelestialBody); CelestialBody.FakeHasGravitationalTurret = false; break; case PathState.ObjectRemoved: newPath.AddCelestialBody(CelestialBody, false); break; case PathState.ObjectUpgraded: CelestialBody.FakeHasGravitationalTurretLv2 = false; break; } CelestialBody = null; PathState = PathState.None; }
/// <summary> /// Test a path between current position and destination. /// </summary> private void TestPath(Vector3D destination, MyEntity destEntity, byte runId, bool isAlternate, bool tryAlternates, bool slowDown = false) { if (runId != m_runId) { m_logger.debugLog("destination changed, abort", "TestPath()", Logger.severity.DEBUG); return; } if (!lock_testPath.TryAcquireExclusive()) { m_logger.debugLog("Already running, requeue (destination:" + destination + ", destEntity: " + destEntity + ", runId :" + runId + ", isAlternate: " + isAlternate + ", tryAlternates: " + tryAlternates + ", slowDown: " + slowDown + ")", "TestPath()"); LockedQueue<Action> queue = isAlternate ? m_pathLow : m_pathHigh; queue.Enqueue(() => TestPath(destination, destEntity, runId, isAlternate, tryAlternates)); return; } try { if (m_grid != m_navBlock.Grid) { m_logger.debugLog("Grid has changed, from " + m_grid.DisplayName + " to " + m_navBlock.Grid.DisplayName + ", nav block: " + m_navBlock.Block.getBestName(), "TestPath()", Logger.severity.WARNING); return; } m_logger.debugLog("Running, (destination:" + destination + ", destEntity: " + destEntity + ", runId :" + runId + ", isAlternate: " + isAlternate + ", tryAlternates: " + tryAlternates + ", slowDown: " + slowDown + ")", "TestPath()"); MyEntity obstructing; Vector3? pointOfObstruction; if ((isAlternate || tryAlternates) && !m_pathChecker.GravityTest(new LineSegmentD(m_navBlock.WorldPosition, destination), m_destination, out obstructing, out pointOfObstruction)) { m_pathState = PathState.Searching; m_logger.debugLog("blocked by gravity at " + pointOfObstruction, "TestGravity()", Logger.severity.DEBUG); if (tryAlternates) { Vector3D point = pointOfObstruction.Value; Vector3 direction = m_navBlock.WorldPosition - obstructing.GetCentre(); direction.Normalize(); float distance = Vector3.Distance(m_navBlock.WorldPosition, pointOfObstruction.Value); float minDist = m_navSet.Settings_Current.DestinationRadius; if (minDist < 1000f) { minDist = 1500f; m_navSet.Settings_Current.DestinationRadius = 1000f; } else minDist *= 1.5f; m_pathHigh.Clear(); FindAlternate_AroundObstruction(pointOfObstruction.Value, direction, distance, minDist * minDist, runId); m_pathLow.Enqueue(() => m_pathState = PathState.Path_Blocked); } return; } if (m_pathChecker.TestFast(m_navBlock, destination, m_ignoreAsteroid, destEntity, m_landing)) { m_logger.debugLog("path is clear (fast)", "TestPath()", Logger.severity.TRACE); PathClear(ref destination, runId, isAlternate, slowDown); return; } if (m_pathChecker.TestSlow(out obstructing, out pointOfObstruction)) { m_logger.debugLog("path is clear (slow)", "TestPath()", Logger.severity.TRACE); PathClear(ref destination, runId, isAlternate, slowDown); return; } if (runId != m_runId) { m_logger.debugLog("destination changed, abort", "TestPath()", Logger.severity.DEBUG); return; } if (slowDown) { Vector3 displacement = pointOfObstruction.Value - m_navBlock.WorldPosition; m_navSet.Settings_Task_NavWay.SpeedMaxRelative = Vector3.Distance(pointOfObstruction.Value, m_navBlock.WorldPosition) / LookAheadSpeed_Seconds; m_logger.debugLog("Set MaxRelativeSpeed to " + m_navSet.Settings_Task_NavWay.SpeedMaxRelative, "TestPath()", Logger.severity.TRACE); return; } m_pathState = PathState.Searching; m_logger.debugLog("path is blocked by " + obstructing.getBestName() + " at " + pointOfObstruction + ", destEntity: " + destEntity.getBestName(), "TestPath()", isAlternate ? Logger.severity.TRACE : Logger.severity.DEBUG); m_logger.debugLog(obstructing is IMyCubeBlock, "grid: " + obstructing.GetTopMostParent().DisplayName, "TestPath()", isAlternate ? Logger.severity.TRACE : Logger.severity.DEBUG); if (tryAlternates) TryAlternates(runId, pointOfObstruction.Value, obstructing); } finally { lock_testPath.ReleaseExclusive(); RunItem(); } }
private PathState CalculateAStartPath(int startX, int startY, int startZ, int targetX, int targetY, int targetZ, int searchLimit, List <int> steps) { MiniMapSector[] sectors = new MiniMapSector[4]; sectors[0] = AcquireSector(startX - Constants.PathMatrixCenter, startY - Constants.PathMatrixCenter, startZ, false); sectors[1] = AcquireSector(startX - Constants.PathMatrixCenter, startY + Constants.PathMatrixCenter, startZ, false); sectors[2] = AcquireSector(startX + Constants.PathMatrixCenter, startY + Constants.PathMatrixCenter, startZ, false); sectors[3] = AcquireSector(startX + Constants.PathMatrixCenter, startY - Constants.PathMatrixCenter, startZ, false); // initial sector position (start position in minimap storage) var sectorMaxX = sectors[0].SectorX + Constants.MiniMapSectorSize; var sextorMaxY = sectors[0].SectorY + Constants.MiniMapSectorSize; var closedList = new Dictionary <int, PathItem>(); var openList = new Utils.PriorityQueue <KeyValuePair <PathItem, int> >(Comparer <KeyValuePair <PathItem, int> > .Create(ComparePathNodes)); PathItem currentNode = new PathItem(startX, startY); closedList.Add(Hash2DPosition(startX, startY), currentNode); PathItem foundNode = null; PathState ret = PathState.PathErrorInternal; while (currentNode != null) { if (closedList.Count > searchLimit) { ret = PathState.PathErrorTooFar; break; } if (currentNode.X == targetX && currentNode.Y == targetY && (foundNode == null || currentNode.PathCost < foundNode.PathCost)) { foundNode = currentNode; } if (foundNode != null && (currentNode.PathHeuristic >= foundNode.PathCost)) { break; } for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (i == 0 && j == 0) { continue; } int currentPosX = currentNode.X + i; int currentPosY = currentNode.Y + j; int sectorIndex; if (currentPosX < sectorMaxX) { sectorIndex = currentPosY < sextorMaxY ? 0 : 1; } else { sectorIndex = currentPosY < sextorMaxY ? 3 : 2; } int cost = sectors[sectorIndex].GetCost(currentPosX, currentPosY, startZ); if (cost >= Constants.PathCostObstacle) { continue; } int modifier = 1; if ((i * j) != 0) { modifier = 3; } int pathCost = currentNode.PathCost + modifier * cost; var direction = DirectionFromPosToPos(currentNode.X, currentNode.Y, currentPosX, currentPosY); PathItem neighborNode; if (closedList.TryGetValue(Hash2DPosition(currentPosX, currentPosY), out PathItem handledNode)) { neighborNode = handledNode; if (neighborNode.PathCost <= pathCost) { continue; } } else { neighborNode = new PathItem(currentPosX, currentPosY); closedList.Add(Hash2DPosition(currentPosX, currentPosY), neighborNode); } neighborNode.Predecessor = currentNode; neighborNode.Cost = cost; neighborNode.PathCost = pathCost; neighborNode.PathHeuristic = neighborNode.PathCost + Distance(currentPosX, currentPosY, targetX, targetY); neighborNode.Direction = direction; openList.Push(new KeyValuePair <PathItem, int>(neighborNode, neighborNode.PathHeuristic)); } } if (openList.Count > 0) { currentNode = openList.Pop().Key; } else { currentNode = null; } } if (foundNode != null) { currentNode = foundNode; while (currentNode != null) { steps.Add((int)currentNode.Direction | currentNode.Cost << 16); if (steps.Count + 1 >= Constants.PathMaxSteps) { break; } currentNode = currentNode.Predecessor; } steps.RemoveAt(steps.Count - 1); steps.Reverse(); ret = PathState.PathExists; } return(ret); }
private void TryAlternates(byte runId, Vector3 pointOfObstruction, IMyEntity obstructing) { try { m_pathHigh.Clear(); } catch (IndexOutOfRangeException ioore) { m_logger.debugLog("Caught IndexOutOfRangeException", "TryAlternates()", Logger.severity.ERROR); m_logger.debugLog("Count: " + m_pathHigh.Count, "TryAlternates()", Logger.severity.ERROR); m_logger.debugLog("Exception: " + ioore, "TryAlternates()", Logger.severity.ERROR); throw ioore; } Vector3 displacement = pointOfObstruction - m_navBlock.WorldPosition; if (m_canChangeCourse) { FindAlternate_AroundObstruction(displacement, pointOfObstruction, obstructing.GetLinearVelocity(), runId); FindAlternate_JustMove(runId); } FindAlternate_HalfwayObstruction(displacement, runId); m_pathLow.Enqueue(() => m_pathState = PathState.Path_Blocked); }