Rampage/Humans/RampagePopulace.cs

Settings and per-frame driver for the town crowd in the Rampage package. Holds the tunables (density, wake/sleep radii, stand-in and physics-body caps, fear, slapstick, police response), builds the town over several frames within a millisecond budget, then each frame runs the cell wake/sleep pass, stand-ins, tossed flyers, real physics bodies and hit processing, and publishes HUD counters (Population, Fleeing, Airborne, Grabbers, PlayerHeld). Also handles scare events and hotload recovery by scrapping and rebuilding.

using System;
using System.Collections.Generic;

/// <summary>
/// The humans of the surface: a town full of people for the lizard to give their comeuppance to.
/// Thousands of them, paid for the way the stadium pays for its crowd (<see cref="CrowdSpawner"/>),
/// in levels by distance from the lizard:
///
///  1. Far: each block's people are baked into a few meshes. No objects, no thinking.
///  2. Near: the block wakes and each person is a cheap stand-in that strolls, films, flocks,
///     panics and stampedes by a few local rules.
///  3. Right round the lizard: a stand-in is swapped for a real <see cref="CrowdPerson"/>, the
///     stadium's own physics body, to be clubbed, bowled over and grabbed by. A few dozen at most.
///
/// Everybody in every level can be hit (<see cref="IRampageTarget"/>), and a hit is slapstick,
/// never worse: a big arc, a long tumble, stars round the head, and off they stagger.
/// Split over several files: this one holds the settings and the frame; Build makes the town,
/// StandIns moves the near crowd, Bodies runs the real ones, Hits does the clubbing, and
/// Response sends the police, the army and the marching band.
/// </summary>
[Title( "Rampage Populace" ), Category( "Rampage" ), Icon( "groups" )]
public sealed partial class RampagePopulace : Component
{
	// ---- For the HUD ---------------------------------------------------------------------------------
	/// <summary>Everybody in town, in every level.</summary>
	public static int Population { get; private set; }
	/// <summary>People near the lizard who are running away right now.</summary>
	public static int Fleeing { get; private set; }
	/// <summary>People in the air right now.</summary>
	public static int Airborne { get; private set; }
	/// <summary>People with a hand on the lizard.</summary>
	public static int Grabbers { get; private set; }
	/// <summary>True while anybody has hold of the lizard.</summary>
	public static bool PlayerHeld { get; private set; }
	/// <summary>True while a pile has the lizard pinned to the spot.</summary>
	public static bool PlayerPinned { get; private set; }
	/// <summary>0 to 1: how close the indignity reflex is to throwing everybody off.</summary>
	public static float ReflexCharge { get; private set; }
	/// <summary>How hard the lizard is thrashing against a grip, against what it takes (0 to 1 and over).</summary>
	public static float Struggle { get; private set; }
	/// <summary>Real physics bodies in existence, and stand-ins awake.</summary>
	public static int RealBodies { get; private set; }
	public static int AwakeStandIns { get; private set; }
	/// <summary>Raised when the indignity reflex goes off (where), for the weapon to thrash along.</summary>
	public static event Action<Vector3> IndignityReflex;

	public static RampagePopulace Current { get; private set; }
	/// <summary>True once everybody has been placed and the far crowd baked (it is done over the first frames, behind the intro).</summary>
	public static bool Built { get; private set; }
	/// <summary>How long that took (real seconds), and the longest frame while it was going on (milliseconds).</summary>
	public static float BuiltIn { get; private set; }
	public static float BuildWorstMs { get; private set; }

	// ---- Numbers ---------------------------------------------------------------------------------------
	/// <summary>People per 1,000 by 1,000 inches of town.</summary>
	[Property, Group( "Numbers" )] public float Density { get; set; } = 11f;
	[Property, Group( "Numbers" )] public int MinPopulation { get; set; } = 1500;
	[Property, Group( "Numbers" )] public int MaxPopulation { get; set; } = 9000;
	/// <summary>How far from the middle of a street people stand.</summary>
	[Property, Group( "Numbers" )] public float StreetSpread { get; set; } = 150f;
	/// <summary>Chance that an ordinary person is brave or stupid enough to go for the lizard.</summary>
	[Property, Group( "Numbers" ), Range( 0f, 1f )] public float BraveChance { get; set; } = 0.07f;

	// ---- Loading ---------------------------------------------------------------------------------------
	/// <summary>The town is cut into square blocks this big; a block wakes and sleeps as a whole.</summary>
	[Property, Group( "Loading" )] public float CellSize { get; set; } = 1600f;
	/// <summary>A block wakes (its people become stand-ins) when the lizard is this close to it.</summary>
	[Property, Group( "Loading" )] public float WakeRadius { get; set; } = 3400f;
	/// <summary>A block goes back to sleep, everybody home again, when the lizard is this far from it.</summary>
	[Property, Group( "Loading" )] public float SleepRadius { get; set; } = 4600f;
	/// <summary>Somebody with no block awake to belong to is sent home when left this far behind.</summary>
	[Property, Group( "Loading" )] public float CullRadius { get; set; } = 5200f;
	/// <summary>Never more moving stand-ins than this at once (a block hit from afar may go a little over).</summary>
	[Property, Group( "Loading" )] public int MaxAwake { get; set; } = 650;
	/// <summary>A stand-in this close to where the lizard is heading becomes a real physics body.</summary>
	[Property, Group( "Loading" )] public float PhysicsRadius { get; set; } = 700f;
	/// <summary>A physics body this far from the lizard, on its feet, turns back into a stand-in.</summary>
	[Property, Group( "Loading" )] public float DemoteRadius { get; set; } = 1400f;
	/// <summary>Never more real physics bodies than this at once.</summary>
	[Property, Group( "Loading" )] public int MaxReal { get; set; } = 70;
	/// <summary>Of those, how many may be made just for standing near the lizard. The rest are kept for people who get hit.</summary>
	[Property, Group( "Loading" )] public int MaxRealNearby { get; set; } = 44;
	/// <summary>Never more real bodies in the air than this. A stand-in hit beyond it is thrown the cheap way.</summary>
	[Property, Group( "Loading" )] public int MaxAirborne { get; set; } = 40;
	/// <summary>Never more stand-ins flying the cheap way than this. Beyond it people are only shoved.</summary>
	[Property, Group( "Loading" )] public int MaxTossed { get; set; } = 90;
	/// <summary>
	/// Most physics bodies made in one frame for standing near, and for being hit (anybody hit past
	/// that is thrown the cheap way). Halved after a slow frame, so a crowd never stalls the game.
	/// </summary>
	[Property, Group( "Loading" )] public int SpawnPerFrame { get; set; } = 2;
	[Property, Group( "Loading" )] public int HitSpawnPerFrame { get; set; } = 4;
	/// <summary>Milliseconds a frame spent placing the town's people at the start, behind the intro's black.</summary>
	[Property, Group( "Loading" )] public float BuildBudgetMs { get; set; } = 4f;
	/// <summary>Stand-ins made ahead of time at the start, so that a block waking makes nothing new.</summary>
	[Property, Group( "Loading" )] public int PrewarmStandIns { get; set; } = 420;
	/// <summary>Further off than this a stand-in is drawn without its hat and prop (they come back nearer than <see cref="HalfRateDistance"/>).</summary>
	[Property, Group( "Loading" )] public float TrimDistance { get; set; } = 2600f;
	/// <summary>Stand-ins further off than this think every other frame; twice as far, every fourth.</summary>
	[Property, Group( "Loading" )] public float HalfRateDistance { get; set; } = 1900f;

	// ---- Movement and fear -----------------------------------------------------------------------------
	/// <summary>Walking speed of a stand-in with somewhere to be.</summary>
	[Property, Group( "Movement" )] public float WalkSpeed { get; set; } = 150f;
	/// <summary>The lizard moving faster than this is a charge: people in its path dive aside.</summary>
	[Property, Group( "Movement" )] public float ChargeSpeed { get; set; } = 1000f;
	/// <summary>How near the lizard has to be to frighten people who have seen nothing happen yet.</summary>
	[Property, Group( "Fear" )] public float ScareRadius { get; set; } = 1500f;
	/// <summary>How much further the fright reaches once the town is fully alarmed.</summary>
	[Property, Group( "Fear" )] public float AlarmRadius { get; set; } = 2400f;
	/// <summary>Everybody this near somebody being hit is frightened at once.</summary>
	[Property, Group( "Fear" )] public float HitScareRadius { get; set; } = 1400f;
	/// <summary>Seconds the town takes to calm down after the last hit.</summary>
	[Property, Group( "Fear" )] public float AlarmSeconds { get; set; } = 25f;

	// ---- Slapstick -------------------------------------------------------------------------------------
	/// <summary>Nobody leaves the ground slower or faster than this, whatever hit them.</summary>
	[Property, Group( "Slapstick" )] public float MinLaunch { get; set; } = 520f;
	[Property, Group( "Slapstick" )] public float MaxLaunch { get; set; } = 5200f;
	/// <summary>Every launch goes up at least this much of its speed along the ground: the cartoon arc.</summary>
	[Property, Group( "Slapstick" )] public float ArcLift { get; set; } = 0.6f;
	/// <summary>Gravity on somebody in flight, against the usual 1. Lower hangs longer.</summary>
	[Property, Group( "Slapstick" ), Range( 0.2f, 1.5f )] public float FlightGravity { get; set; } = 0.7f;
	/// <summary>How hard they spin.</summary>
	[Property, Group( "Slapstick" )] public float Spin { get; set; } = 13f;
	/// <summary>Chance that somebody who hits something high up sticks there for a moment.</summary>
	[Property, Group( "Slapstick" ), Range( 0f, 1f )] public float StickChance { get; set; } = 0.35f;
	/// <summary>Seconds lying dazed with stars before getting up.</summary>
	[Property, Group( "Slapstick" )] public float DazeSeconds { get; set; } = 3f;
	/// <summary>How many people one flying person can bowl over, and how many times that can be passed on.</summary>
	[Property, Group( "Slapstick" )] public int ChainKnocks { get; set; } = 3;
	[Property, Group( "Slapstick" )] public int ChainDepth { get; set; } = 2;
	/// <summary>How much of its speed a flying person passes on to whoever it lands on.</summary>
	[Property, Group( "Slapstick" ), Range( 0f, 1f )] public float ChainKeep { get; set; } = 0.55f;
	/// <summary>Cheap flyers bounce off walls and land on roofs (a ray each per frame). Off: they only know the ground.</summary>
	[Property, Group( "Slapstick" )] public bool TossedHitWalls { get; set; } = true;
	/// <summary>Seconds after a hit during which the same person cannot be hit again (one swing, one hit).</summary>
	[Property, Group( "Slapstick" )] public float RehitSeconds { get; set; } = 0.3f;

	// ---- The response ----------------------------------------------------------------------------------
	/// <summary>Seconds between waves of whatever the town can send at this tier.</summary>
	[Property, Group( "Response" )] public float RespondEvery { get; set; } = 16f;
	/// <summary>Never more of the authorities about than this.</summary>
	[Property, Group( "Response" )] public int MaxResponders { get; set; } = 110;
	/// <summary>How far from the lizard a wave arrives.</summary>
	[Property, Group( "Response" )] public float ArriveDistance { get; set; } = 2100f;
	/// <summary>Put the Fat Guy somewhere in town.</summary>
	[Property, Group( "Response" )] public bool SpawnFatGuy { get; set; } = true;

	// ---- What it made ----------------------------------------------------------------------------------
	[Property, ReadOnly, Group( "Spawned" )] public int Townsfolk { get; private set; }
	[Property, ReadOnly, Group( "Spawned" )] public int Awake => _awake.Count;
	[Property, ReadOnly, Group( "Spawned" )] public int Physical => _real.Count;
	[Property, ReadOnly, Group( "Spawned" )] public int Tossed => _tossed.Count;
	[Property, ReadOnly, Group( "Spawned" )] public int Responders { get; private set; }

	public PopulaceGrips Grips => _grips;
	public RampageFatGuy TheFatGuy { get; private set; }

	PopulaceGrips _grips;
	GameObject _root;
	bool _built, _buildBegun, _strained;
	IEnumerator<bool> _building;
	float _buildBegan;
	Sandbox.Diagnostics.FastTimer _clock;   // the engine timer: the sandbox does not allow System.Diagnostics.Stopwatch
	int _frame;
	float _alarm;           // 0 calm, 1 the whole town knows
	float _nextCells, _nextStampede, _nextScream;
	int _fleeing;

	protected override void OnStart()
	{
		if ( Scene.IsEditor ) return;
		Current = this;
		Built = false;
		PopulaceFx.Reset();

		EnsureGrips();
		Rampage.Shockwave += OnShockwave;
		Rampage.TierUp += OnTierUp;
	}

	/// <summary>The grips are made in OnStart; if a hotload has lost them they are made (or found) again.</summary>
	void EnsureGrips()
	{
		if ( _grips.IsValid() ) return;
		_grips = Components.GetOrCreate<PopulaceGrips>();
		_grips.Reflex -= OnReflex;
		_grips.Reflex += OnReflex;
	}

	/// <summary>True if what was built is still all there (a hotload can leave arrays and models behind).</summary>
	bool Whole => _agents is not null && _gridNext is not null && _gridNext.Length == _agents.Length
		&& _root.IsValid() && _bodyModel is not null && _headModel is not null;

	/// <summary>
	/// Everything that was built is cleared away, so the people can be built again from nothing:
	/// used when a hotload has lost the half-finished build, or part of the finished one.
	/// </summary>
	void Scrap()
	{
		if ( _grips.IsValid() ) _grips.ReleaseAll();
		if ( _agents is not null )
			for ( int i = 0; i < _agents.Length; i++ )
				if ( _agents[i].Target is not null ) Rampage.Unregister( _agents[i].Target );
		foreach ( var cell in _cells )
			if ( cell.Lump is not null ) Rampage.Unregister( cell.Lump );
		if ( _root.IsValid() ) _root.Destroy();
		_root = null;
		TheFatGuy = null;

		_agents = Array.Empty<Agent>();
		_gridNext = Array.Empty<int>();
		_free.Clear(); _cells.Clear(); _awake.Clear(); _pool.Clear(); _meshes.Clear(); _models.Clear();
		_real.Clear(); _hits.Clear(); _squads.Clear(); _grid.Clear(); _tossed.Clear(); _scares.Clear();
		_bodyModel = _headModel = null;
		PopulaceFx.Reset();
		Townsfolk = Responders = 0;
		_flying = _tossedFlying = _fleeing = 0;
		_building = null;
		_built = false;
		Built = false;
	}

	protected override void OnDestroy()
	{
		Rampage.Shockwave -= OnShockwave;
		Rampage.TierUp -= OnTierUp;
		if ( _grips is not null ) _grips.Reflex -= OnReflex;

		if ( _agents is not null )
			for ( int i = 0; i < _agents.Length; i++ )
				if ( _agents[i].Target is not null ) Rampage.Unregister( _agents[i].Target );
		foreach ( var cell in _cells )
			if ( cell.Lump is not null ) Rampage.Unregister( cell.Lump );

		if ( _root.IsValid() ) _root.Destroy();
		if ( Current == this )
		{
			Current = null;
			Built = false;
			Population = Fleeing = Airborne = Grabbers = RealBodies = AwakeStandIns = 0;
			PlayerHeld = PlayerPinned = false;
			ReflexCharge = Struggle = 0f;
			IndignityReflex = null;
		}
	}

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor ) return;
		EnsureGrips();

		// Built, but a hotload has taken part of it away: it is all cleared and built again,
		// rather than every frame from here on tripping over what is missing.
		if ( _built && !Whole ) Scrap();

		// Meshes made before the first frame may not draw, and the town has to be there first.
		if ( !_built )
		{
			if ( !PopulaceMap.IsReady ) return;

			// A few steps a frame, as many as fit in the budget, so the start never freezes.
			if ( _building is null )
			{
				if ( _buildBegun ) Scrap();     // begun, and the steps lost to a hotload: again from nothing
				_buildBegun = true;
				_building = BuildSteps(); _buildBegan = RealTime.Now; BuildWorstMs = 0f;
			}
			else BuildWorstMs = MathF.Max( BuildWorstMs, RealTime.Delta * 1000f );
			_clock = Sandbox.Diagnostics.FastTimer.StartNew();
			float building = RealTime.Now - _buildBegan;
			float budget = building > 8f ? 100000f : building > 3f ? BuildBudgetMs * 4f : BuildBudgetMs;
			bool more;
			while ( (more = _building.MoveNext()) && _clock.ElapsedMilliSeconds < budget ) { }
			if ( more ) return;

			_building = null;
			_built = true;
			Built = true;
			BuiltIn = RealTime.Now - _buildBegan;
		}

		var player = Rampage.Player;
		if ( !player.IsValid() ) return;
		if ( _grips.Player != player ) _grips.Adopt( player );

		float now = Time.Now;
		float dt = Time.Delta;
		_frame++;
		_scoresThisFrame = 0;
		_hitSpawns = 0;
		_strained = RealTime.Delta > 0.02f;     // the last frame was a slow one: make fewer bodies in this one
		_alarm = MathF.Max( _alarm - dt / MathF.Max( AlarmSeconds, 1f ), 0f );

		var lizard = player.WorldPosition;
		var lizardVelocity = player.Velocity.WithZ( 0f );

		ApplyHits();                    // whatever the weapon did since the last frame
		if ( now >= _nextCells ) { _nextCells = now + 0.1f; WakeAndSleepCells( lizard ); }
		UpdateResponse( lizard, now, dt );
		UpdateStandIns( lizard, lizardVelocity, now, dt );
		UpdateTossed( now, dt );
		UpdateBodies( lizard, now, dt );
		ApplyHits();                    // and whoever the flying landed on, this same frame
		FlushScores();
		ExpireScares( now );

		// The sound of a town leaving.
		if ( _fleeing > 25 && now >= _nextStampede )
		{
			_nextStampede = now + Game.Random.Float( 3.5f, 5.5f );
			PopulaceFx.Sound( "stampede", lizard, Math.Clamp( _fleeing / 120f, 0.3f, 1f ) );
		}

		// For the HUD.
		Population = Townsfolk + Responders;
		Fleeing = _fleeing;
		Airborne = _flying + _tossedFlying;
		Grabbers = _grips.Grabbers;
		PlayerHeld = _grips.Held;
		PlayerPinned = _grips.Pinned;
		ReflexCharge = _grips.ReflexCharge;
		Struggle = _grips.Held ? _grips.ShakeForce / MathF.Max( _grips.ForceNeeded, 1f ) : 0f;
		RealBodies = _real.Count;
		AwakeStandIns = _awake.Count;
	}

	// ---- Fright ----------------------------------------------------------------------------------------

	struct Scare { public Vector3 At; public float Radius, Until; }
	readonly List<Scare> _scares = new();

	/// <summary>Something frightening just happened here: everybody within the radius panics at once, for a moment.</summary>
	void AddScare( Vector3 at, float radius )
	{
		_alarm = MathF.Min( _alarm + 0.34f, 1f );

		// A few at most: a new one near an old one just refreshes it.
		for ( int i = 0; i < _scares.Count; i++ )
		{
			var s = _scares[i];
			if ( (s.At - at).WithZ( 0f ).LengthSquared > 300f * 300f ) continue;
			s.Radius = MathF.Max( s.Radius, radius );
			s.Until = Time.Now + 0.6f;
			_scares[i] = s;
			return;
		}
		if ( _scares.Count >= 5 ) _scares.RemoveAt( 0 );
		_scares.Add( new Scare { At = at, Radius = radius, Until = Time.Now + 0.6f } );

		if ( Time.Now >= _nextScream )
		{
			_nextScream = Time.Now + Game.Random.Float( 0.5f, 1.1f );
			PopulaceFx.Sound( "scream", at, 0.8f, Game.Random.Float( 0.9f, 1.15f ) );
		}
	}

	void ExpireScares( float now )
	{
		for ( int i = _scares.Count - 1; i >= 0; i-- )
			if ( now >= _scares[i].Until ) _scares.RemoveAt( i );
	}

	bool InScare( Vector3 at )
	{
		for ( int i = 0; i < _scares.Count; i++ )
		{
			var s = _scares[i];
			if ( (s.At - at).WithZ( 0f ).LengthSquared < s.Radius * s.Radius ) return true;
		}
		return false;
	}

	/// <summary>How frightening the lizard is from this far off: nearer is worse, and an alarmed town frightens from further.</summary>
	float ScareAt( float distance ) => Math.Clamp( 1f - distance / (ScareRadius + AlarmRadius * _alarm), 0f, 1f );

	static float FlatDistance( Vector3 a, Vector3 b ) => (a - b).WithZ( 0f ).Length;
}