Sump/Flashbacks/FlashbackNav.cs

Grid-based navigation for the flashback arenas: samples a walkable grid with physics traces, stores per-cell step flags, and runs A* with path straightening. Also contains NavAgent, a per-walker path follower with replanning and unstick behavior.

using System;
using System.Collections.Generic;

/// <summary>
/// The way round walls for everybody who walks in a flashback. The arenas are built at run time
/// out of boxes, so there is no baked navmesh: this samples its own grid over the crowd's floor
/// (<see cref="FlashbackCrowd.Centre"/> and its half sizes). A cell is walkable if there is floor
/// under it and a person-sized box fits at chest height; the step from a cell to each neighbour
/// is open if that box can be swept between them, so thin walls and narrow doors come out right.
/// Paths are A* over the cells, pulled straight where the grid shows a clear line.
/// Sampling and planning are spread over the physics ticks, so nothing happens all in one frame.
/// One per arena, on the arena's root. Walkers get a <see cref="NavAgent"/> from <see cref="Agent"/>.
/// Call <see cref="MarkDirty(BBox)"/> when a door opens or shuts, <see cref="Rebuild"/> for everything.
/// </summary>
[Title( "Flashback Nav" ), Category( "Sump" ), Icon( "route" )]
public sealed class FlashbackNav : Component
{
	/// <summary>Draws the blocked cells and shut steps near the player, and everybody's path.</summary>
	[Property] public bool DebugDraw { get; set; }

	/// <summary>Size of one cell of the grid, in inches.</summary>
	[Property] public float CellSize { get; set; } = 44f;

	/// <summary>A search gives up (and heads for the nearest it got) after opening this many cells.</summary>
	[Property] public int MaxExpanded { get; set; } = 6000;

	/// <summary>No more than this many paths are planned in one physics tick.</summary>
	[Property] public int PlansPerTick { get; set; } = 2;

	/// <summary>Whose floor this covers.</summary>
	public FlashbackCrowd Crowd { get; set; }

	/// <summary>Never counted as a wall.</summary>
	public GameObject Player { get; set; }

	/// <summary>True once the whole grid has been sampled. Until then everybody walks straight.</summary>
	public bool Ready { get; private set; }

	/// <summary>Goes up whenever the grid changes; paths planned on an older one are planned again.</summary>
	public int Version { get; private set; }

	public float Cell => _cell;

	// The box that has to fit: a little wider than a person (radius 12, guards 13.4), chest height.
	const float AgentRadius = 17f, ChestLow = 18f, ChestHigh = 62f;
	/// <summary>A step up or down taller than this between two cells is a wall.</summary>
	const float MaxStep = 14f;
	const byte Walk = 1, East = 2, North = 4, NorthEast = 8, NorthWest = 16;

	static readonly BBox Body = new( new Vector3( -AgentRadius, -AgentRadius, 0f ), new Vector3( AgentRadius, AgentRadius, ChestHigh - ChestLow ) );
	static readonly BBox Slim = new( new Vector3( -10f, -10f, 0f ), new Vector3( 10f, 10f, 40f ) );
	static readonly int[] StepX = { 1, 0, -1, 0, 1, -1, -1, 1 };
	static readonly int[] StepY = { 0, 1, 0, -1, 1, 1, -1, -1 };

	sealed class Job
	{
		public int X0, Y0, X1, Y1, Phase, Cursor;
		public bool Full;
		public float NotBefore;
	}

	// The grid. A cell's flags say whether it is walkable and which of its steps east, north,
	// north-east and north-west are open; the other four steps are read from the neighbour.
	byte[] _flags;
	float[] _floor;
	int _w, _h;
	float _cell = 44f, _floorZ;
	Vector3 _min;
	readonly List<Job> _jobs = new();

	// The search.
	float[] _g;
	int[] _parent, _seen, _closed, _heapCell;
	float[] _heapKey;
	int _heapCount, _search;
	readonly List<int> _cells = new();
	readonly List<Vector3> _points = new();

	readonly Queue<NavAgent> _queue = new();
	readonly List<NavAgent> _agents = new();

	/// <summary>A walker's own path through this grid.</summary>
	public NavAgent Agent()
	{
		var agent = new NavAgent( this );
		_agents.Add( agent );
		return agent;
	}

	internal void Request( NavAgent agent ) => _queue.Enqueue( agent );

	// ---- Keeping the grid up to date ------------------------------------------------------------

	/// <summary>Samples the whole floor again (the arena was built, or changed all over).</summary>
	public void Rebuild()
	{
		if ( !Crowd.IsValid() ) return;

		float cell = MathF.Max( CellSize, 16f );
		float halfX = Crowd.HalfX + cell, halfY = Crowd.HalfY + cell;
		var min = (Crowd.Centre - new Vector3( halfX, halfY, 0f )).WithZ( 0f );
		int w = Math.Clamp( (int)MathF.Ceiling( halfX * 2f / cell ), 1, 400 );
		int h = Math.Clamp( (int)MathF.Ceiling( halfY * 2f / cell ), 1, 400 );

		if ( _flags is null || w != _w || h != _h || cell != _cell || min != _min )
		{
			_w = w; _h = h; _cell = cell; _min = min;
			_flags = new byte[w * h];
			_floor = new float[w * h];
			_g = new float[w * h];
			_parent = new int[w * h];
			_seen = new int[w * h];
			_closed = new int[w * h];
			_heapCell = new int[Math.Max( w * h, 1024 )];
			_heapKey = new float[_heapCell.Length];
			_search = 0;
			Ready = false;
		}

		_floorZ = Crowd.FloorZ;
		_jobs.Clear();
		_jobs.Add( new Job { X0 = 0, Y0 = 0, X1 = w - 1, Y1 = h - 1, Full = true, NotBefore = Time.Now + 0.05f } );
	}

	/// <summary>Something inside these world bounds opened, shut or moved: that part is sampled again.</summary>
	public void MarkDirty( BBox bounds )
	{
		if ( _flags is null ) return;   // not built yet: the first build will see it
		float pad = AgentRadius + 2f;
		int x0 = Math.Clamp( (int)MathF.Floor( (bounds.Mins.x - pad - _min.x) / _cell ), 0, _w - 1 );
		int x1 = Math.Clamp( (int)MathF.Floor( (bounds.Maxs.x + pad - _min.x) / _cell ), 0, _w - 1 );
		int y0 = Math.Clamp( (int)MathF.Floor( (bounds.Mins.y - pad - _min.y) / _cell ), 0, _h - 1 );
		int y1 = Math.Clamp( (int)MathF.Floor( (bounds.Maxs.y + pad - _min.y) / _cell ), 0, _h - 1 );
		_jobs.Add( new Job { X0 = x0, Y0 = y0, X1 = x1, Y1 = y1, NotBefore = Time.Now + 0.05f } );
	}

	/// <summary>One of the arena's boxes (a door) was switched on or off, or is about to be.</summary>
	public void MarkDirty( GameObject block )
	{
		if ( !block.IsValid() ) return;
		var half = block.WorldScale * 25f;   // the arena's blocks are 50 unit cubes, never turned
		half = new Vector3( MathF.Abs( half.x ), MathF.Abs( half.y ), MathF.Abs( half.z ) );
		MarkDirty( new BBox( block.WorldPosition - half, block.WorldPosition + half ) );
	}

	protected override void OnFixedUpdate()
	{
		if ( Scene.IsEditor ) return;
		if ( _flags is null && _jobs.Count == 0 ) Rebuild();
		Sample();

		for ( int n = 0; n < PlansPerTick && _queue.Count > 0; n++ )
			_queue.Dequeue().RunPlan();
	}

	/// <summary>Works through the waiting jobs, a budget of traces per tick: first the cells, then the steps between them.</summary>
	void Sample()
	{
		int budget = Ready ? 1200 : 8000;
		while ( budget > 0 && _jobs.Count > 0 )
		{
			var job = _jobs[0];
			if ( Time.Now < job.NotBefore ) return;   // give the physics a moment to notice the change

			// The steps of the cells just outside the changed part lead into it, so they go again too.
			bool edges = job.Phase == 1;
			int x0 = edges ? Math.Max( job.X0 - 1, 0 ) : job.X0;
			int x1 = edges ? Math.Min( job.X1 + 1, _w - 1 ) : job.X1;
			int y0 = edges ? Math.Max( job.Y0 - 1, 0 ) : job.Y0;
			int span = x1 - x0 + 1;
			int total = span * (job.Y1 - y0 + 1);

			while ( job.Cursor < total && budget > 0 )
			{
				int x = x0 + job.Cursor % span, y = y0 + job.Cursor / span;
				budget -= edges ? SampleSteps( x, y ) : SampleCell( x, y );
				job.Cursor++;
			}
			if ( job.Cursor < total ) return;

			if ( !edges ) { job.Phase = 1; job.Cursor = 0; continue; }
			_jobs.RemoveAt( 0 );
			if ( job.Full ) Ready = true;
			Version++;
		}
	}

	/// <summary>Only the place itself counts: not people, not the player, not loose things, not triggers.</summary>
	SceneTrace Solid( SceneTrace trace )
	{
		trace = trace.WithoutTags( "crowd", "fatguy", "debris", BodyOverride.StandInTag ).IgnoreDynamic();
		return Player.IsValid() ? trace.IgnoreGameObjectHierarchy( Player ) : trace;
	}

	Vector3 CentreOf( int x, int y ) => new( _min.x + (x + 0.5f) * _cell, _min.y + (y + 0.5f) * _cell, _floor[x + y * _w] );

	bool CellAt( Vector3 p, out int x, out int y )
	{
		x = (int)MathF.Floor( (p.x - _min.x) / _cell );
		y = (int)MathF.Floor( (p.y - _min.y) / _cell );
		return x >= 0 && y >= 0 && x < _w && y < _h;
	}

	/// <summary>Is there floor here, and room to stand on it? Returns the number of traces it took.</summary>
	int SampleCell( int x, int y )
	{
		int i = x + y * _w;
		_flags[i] = 0;
		_floor[i] = _floorZ;

		var at = CentreOf( x, y );
		var down = Solid( Scene.Trace.Ray( at + Vector3.Up * 36f, at + Vector3.Down * 30f ) ).Run();
		if ( !down.Hit || down.StartedSolid ) return 1;   // nothing to stand on, or inside something

		float floor = down.HitPosition.z;
		var feet = at.WithZ( floor + ChestLow );
		if ( Solid( Scene.Trace.Box( Body, feet, feet + Vector3.Up ) ).Run().Hit ) return 2;

		_floor[i] = floor;
		_flags[i] = Walk;
		return 2;
	}

	/// <summary>Which of a cell's four own steps are open. Returns the number of traces it took.</summary>
	int SampleSteps( int x, int y )
	{
		int i = x + y * _w;
		byte flags = (byte)(_flags[i] & Walk);
		int traces = 1;
		if ( flags != 0 )
		{
			if ( StepOpen( x, y, x + 1, y, ref traces ) ) flags |= East;
			if ( StepOpen( x, y, x, y + 1, ref traces ) ) flags |= North;
			if ( StepOpen( x, y, x + 1, y + 1, ref traces ) ) flags |= NorthEast;
			if ( StepOpen( x, y, x - 1, y + 1, ref traces ) ) flags |= NorthWest;
		}
		_flags[i] = flags;
		return traces;
	}

	bool StepOpen( int x, int y, int nx, int ny, ref int traces )
	{
		if ( nx < 0 || ny < 0 || nx >= _w || ny >= _h ) return false;
		int from = x + y * _w, to = nx + ny * _w;
		if ( (_flags[to] & Walk) == 0 || MathF.Abs( _floor[to] - _floor[from] ) > MaxStep ) return false;

		traces++;
		var a = CentreOf( x, y ) + Vector3.Up * ChestLow;
		var b = CentreOf( nx, ny ) + Vector3.Up * ChestLow;
		return !Solid( Scene.Trace.Box( Body, a, b ) ).Run().Hit;
	}

	/// <summary>Can somebody step from a cell to the neighbour at (dx, dy)? Never diagonally across a corner.</summary>
	bool CanStep( int x, int y, int dx, int dy )
	{
		int nx = x + dx, ny = y + dy;
		if ( nx < 0 || ny < 0 || nx >= _w || ny >= _h ) return false;
		int a = x + y * _w, b = nx + ny * _w;
		if ( (_flags[a] & _flags[b] & Walk) == 0 ) return false;
		if ( dy == 0 ) return ((dx > 0 ? _flags[a] : _flags[b]) & East) != 0;
		if ( dx == 0 ) return ((dy > 0 ? _flags[a] : _flags[b]) & North) != 0;

		if ( (_flags[nx + y * _w] & _flags[x + ny * _w] & Walk) == 0 ) return false;
		int low = dy > 0 ? a : b;                 // the southern cell of the two holds the flag
		bool east = dy > 0 ? dx > 0 : dx < 0;     // which way the step leans, seen from that cell
		return (_flags[low] & (east ? NorthEast : NorthWest)) != 0;
	}

	// ---- Questions ------------------------------------------------------------------------------

	/// <summary>True if the grid shows a clear straight walk between two world points.</summary>
	public bool Los( Vector3 from, Vector3 to )
	{
		if ( !Ready ) return false;
		if ( !CellAt( from, out int px, out int py ) || (_flags[px + py * _w] & Walk) == 0 ) return false;

		var line = (to - from).WithZ( 0f );
		int steps = Math.Max( 1, (int)MathF.Ceiling( line.Length / (_cell * 0.25f) ) );
		if ( steps > 4000 ) return false;

		for ( int s = 1; s <= steps; s++ )
		{
			if ( !CellAt( from + line * (s / (float)steps), out int x, out int y ) ) return false;
			if ( x == px && y == py ) continue;
			if ( Math.Abs( x - px ) > 1 || Math.Abs( y - py ) > 1 || !CanStep( px, py, x - px, y - py ) ) return false;
			px = x; py = y;
		}
		return true;
	}

	/// <summary>True if somebody can simply walk straight there: clear on the grid, and nothing solid in between right now.</summary>
	public bool ClearWalk( Vector3 from, Vector3 to )
	{
		if ( !Los( from, to ) ) return false;
		var a = from + Vector3.Up * ChestLow;
		var b = to.WithZ( from.z ) + Vector3.Up * ChestLow;
		return !Solid( Scene.Trace.Box( Slim, a, b ) ).Run().Hit;
	}

	/// <summary>
	/// The walkable cell nearest a point, or -1. Of the cells round it, one that can be seen from
	/// the point is preferred, so nobody is sent to the far side of the wall they are leaning on.
	/// </summary>
	int NearestWalkable( Vector3 p, int reach )
	{
		CellAt( p, out int cx, out int cy );
		cx = Math.Clamp( cx, 0, _w - 1 );
		cy = Math.Clamp( cy, 0, _h - 1 );
		if ( Stands( cx, cy, p ) ) return cx + cy * _w;

		int fallback = -1;
		float fallbackDistance = float.MaxValue;
		var eye = p + Vector3.Up * 30f;
		for ( int ring = 1; ring <= reach; ring++ )
		{
			int best = -1;
			float bestDistance = float.MaxValue;
			for ( int y = cy - ring; y <= cy + ring; y++ )
			for ( int x = cx - ring; x <= cx + ring; x++ )
			{
				if ( Math.Max( Math.Abs( x - cx ), Math.Abs( y - cy ) ) != ring ) continue;
				if ( x < 0 || y < 0 || x >= _w || y >= _h || !Stands( x, y, p ) ) continue;

				var centre = CentreOf( x, y );
				float distance = (centre - p).WithZ( 0f ).LengthSquared;
				if ( distance < fallbackDistance ) { fallbackDistance = distance; fallback = x + y * _w; }
				if ( distance >= bestDistance ) continue;
				if ( Solid( Scene.Trace.Ray( eye, centre.WithZ( eye.z ) ) ).Run().Hit ) continue;
				bestDistance = distance;
				best = x + y * _w;
			}
			if ( best >= 0 ) return best;
		}
		return fallback;
	}

	/// <summary>Walkable, and on the same level as the point (not the top of the table beside it).</summary>
	bool Stands( int x, int y, Vector3 p )
	{
		int i = x + y * _w;
		return (_flags[i] & Walk) != 0 && MathF.Abs( _floor[i] - p.z ) < 40f;
	}

	/// <summary>
	/// Plans the walk from one world point to another: the corners to walk at, in order, not
	/// counting the goal itself. False if there is nowhere to start from. <paramref name="partial"/>
	/// is set when the goal cannot be reached and the points only lead as near as it gets.
	/// </summary>
	internal bool Plan( Vector3 from, Vector3 goal, List<Vector3> into, out bool partial )
	{
		into.Clear();
		partial = false;
		if ( !Ready ) return false;

		int start = NearestWalkable( from, 3 );
		if ( start < 0 ) return false;
		int end = NearestWalkable( goal, 4 );
		if ( end < 0 )
		{
			CellAt( goal, out int gx, out int gy );
			end = Math.Clamp( gx, 0, _w - 1 ) + Math.Clamp( gy, 0, _h - 1 ) * _w;
		}

		// A*, eight ways, over the open steps.
		_search++;
		_heapCount = 0;
		int ex = end % _w, ey = end / _w;
		int nearest = start;
		float nearestH = Heuristic( start % _w, start / _w, ex, ey );
		_g[start] = 0f;
		_parent[start] = -1;
		_seen[start] = _search;
		Push( start, nearestH );

		bool found = false;
		int expanded = 0;
		while ( _heapCount > 0 )
		{
			int current = Pop();
			if ( _closed[current] == _search ) continue;
			_closed[current] = _search;
			if ( current == end ) { found = true; break; }
			if ( ++expanded > MaxExpanded ) break;

			int cx = current % _w, cy = current / _w;
			for ( int d = 0; d < 8; d++ )
			{
				if ( !CanStep( cx, cy, StepX[d], StepY[d] ) ) continue;
				int nx = cx + StepX[d], ny = cy + StepY[d];
				int next = nx + ny * _w;
				if ( _closed[next] == _search ) continue;

				float g = _g[current] + (d < 4 ? 1f : 1.4142f);
				if ( _seen[next] == _search && g >= _g[next] ) continue;
				_seen[next] = _search;
				_g[next] = g;
				_parent[next] = current;

				float h = Heuristic( nx, ny, ex, ey );
				if ( h < nearestH ) { nearestH = h; nearest = next; }
				Push( next, g + h );
			}
		}
		partial = !found;

		// Back along the parents, then pulled straight: from each corner, on to the furthest cell in plain view.
		_cells.Clear();
		for ( int c = found ? end : nearest; c >= 0 && _cells.Count < 4096; c = _parent[c] ) _cells.Add( c );
		_points.Clear();
		for ( int i = _cells.Count - 1; i >= 0; i-- ) _points.Add( CentreOf( _cells[i] % _w, _cells[i] / _w ) );

		var anchor = from;
		for ( int i = 0; i < _points.Count; )
		{
			int j = i;
			while ( j + 1 < _points.Count && Los( anchor, _points[j + 1] ) ) j++;
			into.Add( _points[j] );
			anchor = _points[j];
			i = j + 1;
		}

		// The last corners are not needed if the goal itself is in plain view from the one before.
		if ( !partial )
			while ( into.Count > 0 && Los( into.Count > 1 ? into[into.Count - 2] : from, goal ) )
				into.RemoveAt( into.Count - 1 );
		return true;
	}

	static float Heuristic( int x, int y, int ex, int ey )
	{
		int dx = Math.Abs( x - ex ), dy = Math.Abs( y - ey );
		return Math.Max( dx, dy ) + 0.4142f * Math.Min( dx, dy );
	}

	void Push( int cell, float key )
	{
		if ( _heapCount == _heapCell.Length )
		{
			var cells = new int[_heapCount * 2];
			var keys = new float[_heapCount * 2];
			Array.Copy( _heapCell, cells, _heapCount );
			Array.Copy( _heapKey, keys, _heapCount );
			_heapCell = cells;
			_heapKey = keys;
		}

		int i = _heapCount++;
		while ( i > 0 )
		{
			int parent = (i - 1) >> 1;
			if ( _heapKey[parent] <= key ) break;
			_heapCell[i] = _heapCell[parent];
			_heapKey[i] = _heapKey[parent];
			i = parent;
		}
		_heapCell[i] = cell;
		_heapKey[i] = key;
	}

	int Pop()
	{
		int top = _heapCell[0];
		int last = --_heapCount;
		if ( last <= 0 ) return top;

		int cell = _heapCell[last];
		float key = _heapKey[last];
		int i = 0;
		while ( true )
		{
			int child = i * 2 + 1;
			if ( child >= last ) break;
			if ( child + 1 < last && _heapKey[child + 1] < _heapKey[child] ) child++;
			if ( _heapKey[child] >= key ) break;
			_heapCell[i] = _heapCell[child];
			_heapKey[i] = _heapKey[child];
			i = child;
		}
		_heapCell[i] = cell;
		_heapKey[i] = key;
		return top;
	}

	// ---- Debug ----------------------------------------------------------------------------------

	protected override void OnUpdate()
	{
		if ( !DebugDraw || !Ready || Scene.IsEditor ) return;

		var none = new Transform( Vector3.Zero );
		var eye = Player.IsValid() ? Player.WorldPosition : (Crowd.IsValid() ? Crowd.Centre : WorldPosition);
		CellAt( eye, out int cx, out int cy );
		int reach = (int)(700f / _cell);
		float half = _cell * 0.5f - 2f;
		var red = new Color( 1f, 0.15f, 0.1f, 0.7f );
		var orange = new Color( 1f, 0.6f, 0.1f );

		for ( int y = Math.Max( cy - reach, 0 ); y <= Math.Min( cy + reach, _h - 1 ); y++ )
		for ( int x = Math.Max( cx - reach, 0 ); x <= Math.Min( cx + reach, _w - 1 ); x++ )
		{
			int i = x + y * _w;
			var centre = CentreOf( x, y ) + Vector3.Up * 3f;
			if ( (_flags[i] & Walk) == 0 )
			{
				DebugOverlay.Box( new BBox( centre - new Vector3( half, half, 1f ), centre + new Vector3( half, half, 1f ) ), red, 0f, none, false );
				continue;
			}
			// A shut step between two cells that are both walkable: a thin wall or a shut door.
			if ( x + 1 < _w && (_flags[i + 1] & Walk) != 0 && (_flags[i] & East) == 0 )
				DebugOverlay.Line( centre, CentreOf( x + 1, y ) + Vector3.Up * 3f, orange, 0f, none, false );
			if ( y + 1 < _h && (_flags[i + _w] & Walk) != 0 && (_flags[i] & North) == 0 )
				DebugOverlay.Line( centre, CentreOf( x, y + 1 ) + Vector3.Up * 3f, orange, 0f, none, false );
		}

		foreach ( var agent in _agents )
			agent.Draw( DebugOverlay, none );
	}
}

/// <summary>
/// One walker's way through a <see cref="FlashbackNav"/>: ask <see cref="Steer"/> every step
/// where to walk at. It keeps its path, has it planned again (a few times a second at most) when
/// the goal moves or the grid changes, cuts corners it can see past, and gets itself unstuck.
/// With no grid, no path, or the goal in plain view, the answer is simply the goal.
/// </summary>
public sealed class NavAgent
{
	readonly FlashbackNav _nav;
	readonly List<Vector3> _path = new();
	int _index, _version, _fails;
	bool _hasPath, _partial, _direct, _queued, _replan;
	Vector3 _from, _goal, _plannedGoal, _sidestep;
	float _lastCall = -100f, _nextLook, _nextPlan, _retryAt, _progressAt, _best = float.MaxValue, _sidestepUntil;

	internal NavAgent( FlashbackNav nav ) => _nav = nav;

	/// <summary>
	/// The point to walk at next, on the way from where it stands to its goal. The goal itself
	/// means walk straight; its own position means wait (there is no way any nearer).
	/// </summary>
	public Vector3 Steer( Vector3 from, Vector3 goal )
	{
		if ( !_nav.IsValid() || !_nav.Ready ) return goal;

		float now = Time.Now;
		bool moved = (from - _from).WithZ( 0f ).LengthSquared > 100f * 100f;
		if ( moved || now - _lastCall > 0.5f )
		{
			// Picked up again after standing about, lying on the floor, or being put somewhere else.
			if ( moved ) _hasPath = false;
			_nextLook = 0f;
			Progress( now );
		}
		_lastCall = now;
		_from = from;
		_goal = goal;

		if ( now < _sidestepUntil ) return from + _sidestep;

		// A look round, a few times a second: is the goal in plain view, or the corner after next?
		if ( now >= _nextLook )
		{
			_nextLook = now + Game.Random.Float( 0.22f, 0.32f );
			_direct = _nav.ClearWalk( from, goal );
			if ( !_direct && _hasPath && _index + 1 < _path.Count && _nav.Los( from, _path[_index + 1] ) )
			{
				_index++;
				Progress( now );
			}
		}
		if ( _direct ) { _fails = 0; return goal; }

		float cell = _nav.Cell;
		bool stale = !_hasPath || _replan || _version != _nav.Version
			|| (goal - _plannedGoal).WithZ( 0f ).LengthSquared > cell * cell * 4f
			|| (_partial && now >= _retryAt);
		if ( stale && !_queued && now >= _nextPlan )
		{
			_queued = true;
			_nav.Request( this );
		}
		if ( !_hasPath ) return goal;

		while ( _index < _path.Count && (_path[_index] - from).WithZ( 0f ).LengthSquared < 26f * 26f )
		{
			_index++;
			_fails = 0;
			Progress( now );
		}
		if ( _index >= _path.Count )
		{
			// Past the last corner. If the path never got there (a shut door), wait at the end of it.
			return !_partial || (goal - from).WithZ( 0f ).Length < cell * 3f ? goal : from;
		}

		// Unstick: no nearer the corner for a second means plan again from here; three times
		// running, a step back and to one side first.
		var next = _path[_index];
		float left = (next - from).WithZ( 0f ).Length;
		if ( left < _best - 6f ) { _best = left; _progressAt = now; }
		else if ( now - _progressAt > 1f )
		{
			_fails++;
			_replan = true;
			_nextPlan = MathF.Min( _nextPlan, now );
			Progress( now );
			if ( _fails >= 3 )
			{
				_fails = 0;
				var ahead = (next - from).WithZ( 0f ).Normal;
				var side = new Vector3( -ahead.y, ahead.x, 0f ) * (Game.Random.Next( 2 ) == 0 ? 1f : -1f);
				_sidestep = (side * 0.9f - ahead * 0.35f) * 100f;
				_sidestepUntil = now + 0.6f;
				return from + _sidestep;
			}
		}
		return next;
	}

	void Progress( float now )
	{
		_progressAt = now;
		_best = float.MaxValue;
	}

	/// <summary>Its turn in the nav's queue: plan from where it last was to where it last wanted to go.</summary>
	internal void RunPlan()
	{
		_queued = false;
		float now = Time.Now;
		_hasPath = _nav.Plan( _from, _goal, _path, out _partial );
		_index = 0;
		_plannedGoal = _goal;
		_version = _nav.Version;
		_replan = false;
		_nextPlan = now + Game.Random.Float( 0.4f, 0.6f );
		_retryAt = now + 1.2f;
		Progress( now );
	}

	internal void Draw( DebugOverlaySystem overlay, Transform none )
	{
		if ( Time.Now - _lastCall > 0.5f ) return;
		var lift = Vector3.Up * 30f;
		var colour = _direct ? Color.Cyan : _partial ? Color.Yellow : Color.Green;
		var at = _from + lift;
		if ( !_direct && _hasPath )
			for ( int i = _index; i < _path.Count; i++ )
			{
				overlay.Line( at, _path[i].WithZ( at.z ), colour, 0f, none, false );
				at = _path[i].WithZ( at.z );
			}
		overlay.Line( at, _goal.WithZ( at.z ), colour, 0f, none, false );
	}
}