Rampage/Humans/PopulaceMap.cs

Static map facade for the human populace. Exposes delegates that integration wires to RampageWorld for street points, ground height, town size, landmarks and cover, and falls back to a generated flat grid town when nothing is wired. Also builds a spatial hash of street points and answers nearest-street, escape-direction and random-street queries.

using System;
using System.Collections.Generic;

/// <summary>
/// What the humans know about the town: where the streets are, how high the ground is, how far the
/// place goes and where the landmarks stand. The world module owns all of that, so the populace
/// asks through here, and integration wires the delegates up (see the comment on each). Anything
/// left empty falls back to a flat square of 16,000 inches with a street every 1,600.
/// </summary>
public static class PopulaceMap
{
	// ---- To be wired by integration (all optional) ------------------------------------------------

	/// <summary>True once the town is built. Wire to <c>() => RampageWorld.Ready</c>. Empty: ready at once.</summary>
	public static Func<bool> Ready { get; set; }

	/// <summary>Points along the streets, where people stand and walk. Wire to <c>() => RampageWorld.StreetPoints</c>.</summary>
	public static Func<IReadOnlyList<Vector3>> StreetPoints { get; set; }

	/// <summary>Height of the ground at a point. Wire to <c>RampageWorld.GroundHeightAt</c>. Empty: flat, at the height of <see cref="Centre"/>.</summary>
	public static Func<Vector3, float> GroundHeight { get; set; }

	/// <summary>Half the width of the (square) town. Wire to <c>RampageWorld.HalfSize</c>.</summary>
	public static float HalfSize { get; set; } = 8000f;

	/// <summary>The middle of the town.</summary>
	public static Vector3 Centre { get; set; }

	/// <summary>Landmarks and their names, in the same order. Wire to <c>RampageWorld.Landmarks</c> and <c>LandmarkNames</c>.</summary>
	public static Func<IReadOnlyList<Vector3>> Landmarks { get; set; }
	public static Func<IReadOnlyList<string>> LandmarkNames { get; set; }

	/// <summary>Optional: false where nobody can walk (inside a building). Empty: everywhere is walkable.</summary>
	public static Func<Vector3, bool> Walkable { get; set; }

	/// <summary>Optional: things to hide behind (parked cars). Empty: nobody hides.</summary>
	public static Func<IReadOnlyList<Vector3>> Cover { get; set; }

	/// <summary>Back to the flat fallback town. Call before wiring a new scene.</summary>
	public static void Reset()
	{
		Ready = null; StreetPoints = null; GroundHeight = null; Landmarks = null; LandmarkNames = null; Walkable = null; Cover = null;
		HalfSize = 8000f;
		Centre = Vector3.Zero;
		_fallbackStreets = null;
		_grid.Clear();
		_gridPoints = null;
	}

	// ---- What the populace asks ------------------------------------------------------------------

	public static bool IsReady
	{
		get
		{
			return Ready is null || Ready();
		}
	}

	/// <summary>The street points: the world's, or the fallback grid.</summary>
	public static IReadOnlyList<Vector3> Streets()
	{
		var points = StreetPoints?.Invoke();
		if ( points is not null && points.Count > 0 ) return points;
		return _fallbackStreets ??= FallbackStreets();
	}

	public static float GroundAt( Vector3 point )
	{
		return GroundHeight is null ? Centre.z : GroundHeight( point );
	}

	public static bool CanWalk( Vector3 point )
	{
		if ( MathF.Abs( point.x - Centre.x ) > HalfSize - 60f || MathF.Abs( point.y - Centre.y ) > HalfSize - 60f ) return false;
		return Walkable is null || Walkable( point );
	}

	/// <summary>Keeps a point inside the town.</summary>
	public static Vector3 Contain( Vector3 p ) => new(
		Math.Clamp( p.x, Centre.x - HalfSize + 80f, Centre.x + HalfSize - 80f ),
		Math.Clamp( p.y, Centre.y - HalfSize + 80f, Centre.y + HalfSize - 80f ), p.z );

	public static IReadOnlyList<Vector3> CoverPoints()
	{
		return Cover?.Invoke();
	}

	/// <summary>
	/// The landmark whose name holds one of these words ("farm", "barn"). With no landmarks wired
	/// at all, each district gets a corner of the fallback town so the cast still turns up.
	/// </summary>
	public static bool FindLandmark( string[] words, int fallbackCorner, out Vector3 where )
	{
		where = default;
		var points = Landmarks?.Invoke();
		var names = LandmarkNames?.Invoke();

		if ( points is null || names is null || points.Count == 0 )
		{
			float x = (fallbackCorner & 1) == 0 ? -0.55f : 0.55f, y = (fallbackCorner & 2) == 0 ? -0.55f : 0.55f;
			where = Centre + new Vector3( x * HalfSize, y * HalfSize, 0f );
			return true;
		}

		int count = Math.Min( points.Count, names.Count );
		for ( int i = 0; i < count; i++ )
		{
			string name = names[i]?.ToLowerInvariant() ?? "";
			foreach ( var word in words )
				if ( name.Contains( word ) ) { where = points[i]; return true; }
		}
		return false;
	}

	// ---- The fallback town -------------------------------------------------------------------------

	const float FallbackBlock = 1600f, FallbackStep = 400f;
	[SkipHotload] static List<Vector3> _fallbackStreets;

	/// <summary>A grid of streets every 1,600 inches, as points every 400 along each.</summary>
	static List<Vector3> FallbackStreets()
	{
		var points = new List<Vector3>();
		int lines = Math.Max( (int)(HalfSize / FallbackBlock), 1 );
		for ( int line = -lines; line <= lines; line++ )
		{
			float across = line * FallbackBlock;
			if ( MathF.Abs( across ) > HalfSize - 200f ) continue;
			for ( float along = -HalfSize + 200f; along <= HalfSize - 200f; along += FallbackStep )
			{
				points.Add( Centre + new Vector3( along, across, 0f ) );
				points.Add( Centre + new Vector3( across, along, 0f ) );
			}
		}
		return points;
	}

	// ---- Finding the nearest bit of street, fast --------------------------------------------------

	const float GridSize = 600f;
	static readonly Dictionary<long, List<int>> _grid = new();
	[SkipHotload] static IReadOnlyList<Vector3> _gridPoints;

	/// <summary>True if the street points are close enough together to follow like a lane (not just crossroads).</summary>
	public static bool StreetsAreLanes { get; private set; }

	/// <summary>Sorts the street points into a grid. Call once the town is ready.</summary>
	public static void BuildStreetGrid()
	{
		_grid.Clear();
		// A copy of our own: the town's list can be emptied under us (a hotload does it), and the
		// grid's indices must never point past the end of what they index.
		var source = Streets();
		var copy = new Vector3[source.Count];
		for ( int i = 0; i < copy.Length; i++ ) copy[i] = source[i];
		_gridPoints = copy;
		for ( int i = 0; i < _gridPoints.Count; i++ )
		{
			long key = Key( _gridPoints[i] );
			if ( !_grid.TryGetValue( key, out var list ) ) _grid[key] = list = new List<int>();
			list.Add( i );
		}

		// Lanes if a typical point has a neighbour within a few strides.
		int tested = 0, close = 0;
		int stride = Math.Max( _gridPoints.Count / 60, 1 );
		for ( int i = 0; i < _gridPoints.Count; i += stride )
		{
			tested++;
			if ( NearestStreet( _gridPoints[i], out _, i ) < 700f ) close++;
		}
		StreetsAreLanes = tested > 0 && close * 2 > tested;
	}

	static long Key( Vector3 p ) => ((long)(int)MathF.Floor( p.x / GridSize ) << 32) ^ (uint)(int)MathF.Floor( p.y / GridSize );
	static long Key( int x, int y ) => ((long)x << 32) ^ (uint)y;

	/// <summary>The nearest street point within about a block, and how far it is (flat). A huge distance if there is none.</summary>
	public static float NearestStreet( Vector3 from, out Vector3 nearest, int skip = -1 )
	{
		nearest = from;
		float best = float.MaxValue;
		if ( _gridPoints is null ) return best;
		int count = _gridPoints.Count;

		int cx = (int)MathF.Floor( from.x / GridSize ), cy = (int)MathF.Floor( from.y / GridSize );
		for ( int x = cx - 1; x <= cx + 1; x++ )
			for ( int y = cy - 1; y <= cy + 1; y++ )
			{
				if ( !_grid.TryGetValue( Key( x, y ), out var list ) ) continue;
				foreach ( int i in list )
				{
					if ( i == skip || (uint)i >= (uint)count ) continue;
					float d = (_gridPoints[i] - from).WithZ( 0f ).LengthSquared;
					if ( d < best ) { best = d; nearest = _gridPoints[i]; }
				}
			}
		return best == float.MaxValue ? best : MathF.Sqrt( best );
	}

	/// <summary>
	/// A street point near <paramref name="from"/> that is as far from <paramref name="threat"/> as
	/// can be: the way to run. Straight away from the threat if there is no street to hand.
	/// </summary>
	public static Vector3 EscapePoint( Vector3 from, Vector3 threat )
	{
		var away = (from - threat).WithZ( 0f );
		away = away.LengthSquared > 1f ? away.Normal : Vector3.Forward;
		var best = Contain( from + away * 700f );
		if ( _gridPoints is null ) return best;
		int count = _gridPoints.Count;

		float bestScore = float.MinValue;
		int cx = (int)MathF.Floor( from.x / GridSize ), cy = (int)MathF.Floor( from.y / GridSize );
		for ( int x = cx - 1; x <= cx + 1; x++ )
			for ( int y = cy - 1; y <= cy + 1; y++ )
			{
				if ( !_grid.TryGetValue( Key( x, y ), out var list ) ) continue;
				foreach ( int i in list )
				{
					if ( (uint)i >= (uint)count ) continue;
					var to = (_gridPoints[i] - from).WithZ( 0f );
					float length = to.Length;
					if ( length < 150f ) continue;
					// Further from the lizard is better; having to run toward it first is much worse.
					float score = (_gridPoints[i] - threat).WithZ( 0f ).Length + Vector3.Dot( to / length, away ) * 500f;
					if ( score > bestScore ) { bestScore = score; best = _gridPoints[i]; }
				}
			}
		return best;
	}

	/// <summary>A random street point, for somebody with nowhere particular to be.</summary>
	public static Vector3 RandomStreet()
	{
		var points = _gridPoints ?? Streets();
		return points.Count > 0 ? points[Game.Random.Next( points.Count )] : Centre;
	}
}