Rampage/Humans/RampagePopulace.StandIns.cs

The stand-in half of RampagePopulace: per-frame steering, neighbour lookup through a hash grid, fear spreading between nearby people, squad and role behaviour (hiders, reporters, filmers, children, brave hunters), stampede and dive-out-of-the-way logic, plus a cheap non-physics toss arc with wall traces, bounces and chained knockbacks.

using System;
using System.Collections.Generic;

// The near crowd: stand-ins that stroll, film, flock, panic and stampede, and the cheap way of
// flying for the ones there is no physics body to spare for.
public sealed partial class RampagePopulace
{
	// Neighbour lookup for the stand-ins: a hash grid rebuilt every frame, as linked lists.
	const float GridSize = 90f;
	readonly Dictionary<long, int> _grid = new();
	int[] _gridNext = Array.Empty<int>();

	/// <summary>People stay within this of the middle of a street, where the streets can be followed.</summary>
	const float LaneHalfWidth = 240f;


	static long GridKey( int x, int y ) => ((long)x << 32) ^ (uint)y;

	/// <summary>
	/// The moving crowd, by the stadium's rules (<see cref="CrowdSpawner"/>) with a town's worth of
	/// character on top. Nobody is scripted: each stand-in steers by a few local rules. They keep
	/// clear of each other; fear spreads from person to person, so a scare ripples down a street
	/// faster than anyone can see the lizard; frightened people run with whoever is running beside
	/// them and keep to the street, which makes stampedes; people in the path of a charge dive out
	/// of it; the brave come round the side; and some just stand there filming.
	/// </summary>
	void UpdateStandIns( Vector3 lizard, Vector3 lizardVelocity, float now, float dt )
	{
		// Real bodies are made round where the lizard is about to be, not where it was.
		var ahead = lizard + lizardVelocity * 0.45f;
		int spawned = 0;
		float physics2 = PhysicsRadius * PhysicsRadius, cull2 = CullRadius * CullRadius;
		float half2 = HalfRateDistance * HalfRateDistance, quarter2 = half2 * 4f;
		float trim2 = MathF.Max( TrimDistance, HalfRateDistance + 100f );
		trim2 *= trim2;
		int nearCap = _strained ? Math.Min( SpawnPerFrame, 1 ) : SpawnPerFrame;

		float lizardSpeed = lizardVelocity.Length;
		var lizardHeading = lizardSpeed > 1f ? lizardVelocity / lizardSpeed : Vector3.Zero;
		bool charging = lizardSpeed > ChargeSpeed;
		bool lanes = PopulaceMap.StreetsAreLanes;
		int fleeing = 0;


		// Who is next to whom.
		_grid.Clear();
		for ( int n = 0; n < _awake.Count; n++ )
		{
			int i = _awake[n];
			if ( _agents[i].Level != Level.StandIn ) continue;
			long key = GridKey( (int)MathF.Floor( _agents[i].Position.x / GridSize ), (int)MathF.Floor( _agents[i].Position.y / GridSize ) );
			_gridNext[i] = _grid.TryGetValue( key, out int first ) ? first : -1;
			_grid[key] = i;
		}

		for ( int n = _awake.Count - 1; n >= 0; n-- )
		{
			if ( n >= _awake.Count ) continue;
			int i = _awake[n];
			ref var a = ref _agents[i];
			if ( a.Level != Level.StandIn ) continue;   // in the air: see UpdateTossed

			var role = HumanRoles.All[a.Role];
			var to = (lizard - a.Position).WithZ( 0f );
			float distance2 = to.LengthSquared;

			// Left far behind with no block to belong to: home.
			if ( a.Stray && distance2 > cull2 ) { SendHome( i ); continue; }

			// On top of the lizard: time to be real.
			bool child = role.Manner == HumanManner.Child;
			if ( !child && !a.Stranded && spawned < nearCap && _real.Count < MaxRealNearby
				&& (ahead - a.Position).WithZ( 0f ).LengthSquared < physics2 )
			{
				Promote( i );
				spawned++;
				continue;
			}

			bool hunting = a.Brave && !a.Cowed;
			if ( a.Panic > 0.5f && !hunting ) fleeing++;

			// Far from the lizard a stand-in thinks and moves every other frame, further still every
			// fourth, taking a longer step. Nobody can tell at that distance.
			float step = dt;
			if ( distance2 > quarter2 )
			{
				if ( ((i + _frame) & 3) != 0 ) continue;
				step = dt * 4f;
			}
			else if ( distance2 > half2 )
			{
				if ( ((i + _frame) & 1) != 0 ) continue;
				step = dt * 2f;
			}

			float distance = MathF.Sqrt( distance2 );
			var toward = distance > 1f ? to / distance : Vector3.Forward;

			// Now and then: the ground underfoot, the way back to the street, somewhere to hide.
			if ( ((i + _frame) & 7) == 0 )
			{
				if ( !a.Stranded ) a.Position.z = PopulaceMap.GroundAt( a.Position );
				a.Lane = Vector3.Zero;
				if ( lanes )
				{
					float off = PopulaceMap.NearestStreet( a.Position, out var street );
					if ( off > LaneHalfWidth && off < 4000f )
						a.Lane = (street - a.Position).WithZ( 0f ).Normal * MathF.Min( (off - LaneHalfWidth) / 250f, 1.5f );
				}
				if ( role.Manner == HumanManner.Hider && a.Panic > 0.25f && !a.HasCover ) FindCover( ref a, lizard );
				if ( a.Panic < 0.1f ) a.HasCover = false;

				// Its hat and whatever it carries are only drawn when there is somebody near enough to see them.
				if ( a.StandIn is { } dressed )
				{
					bool trimmed = dressed.Trimmed ? distance2 > half2 : distance2 > trim2;
					if ( trimmed != dressed.Trimmed ) Trim( ref a, role, trimmed );
				}
			}

			// Stuck on a roof: nothing to do but jump up and down and hope.
			if ( a.Stranded )
			{
				Place( ref a, role, MathF.Abs( MathF.Sin( now * 7f + a.Phase ) ) * 12f, false, false, now );
				continue;
			}

			// ---- The neighbours: keep apart, and feel what they feel.
			var apart = Vector3.Zero;
			var flow = Vector3.Zero;
			float fear = 0f;
			int near = 0;
			int cx = (int)MathF.Floor( a.Position.x / GridSize ), cy = (int)MathF.Floor( a.Position.y / GridSize );
			for ( int gx = cx - 1; gx <= cx + 1; gx++ )
				for ( int gy = cy - 1; gy <= cy + 1; gy++ )
				{
					if ( !_grid.TryGetValue( GridKey( gx, gy ), out int j ) ) continue;
					for ( ; j >= 0; j = _gridNext[j] )
					{
						if ( j == i ) continue;
						var away = (a.Position - _agents[j].Position).WithZ( 0f );
						float gap2 = away.LengthSquared;
						if ( gap2 > GridSize * GridSize || gap2 < 0.01f ) continue;
						float gap = MathF.Sqrt( gap2 );
						apart += away / gap * (1f - gap / GridSize);
						flow += _agents[j].Velocity;
						fear += _agents[j].Panic;
						near++;
					}
				}

			// ---- Fear: from the lizard itself, worse if it is bearing down, from somebody being
			// clubbed nearby, and caught from the people alongside.
			float scare = ScareAt( distance );
			float bearing = Vector3.Dot( -toward, lizardHeading );          // 1 = it is coming straight at me
			if ( charging && bearing > 0.75f && distance < 1500f ) scare = 1f;
			if ( _scares.Count > 0 && InScare( a.Position ) ) scare = 1f;
			if ( near > 0 ) scare = MathF.Max( scare, fear / near * 0.93f );
			scare *= a.Cowed ? 1f : role.Nerves;
			a.Panic += (scare - a.Panic) * MathF.Min( step * (scare > a.Panic ? 5f : 0.22f), 1f );

			// ---- What it wants.
			Vector3 wish;
			float speed;
			bool faceLizard = false, crouch = false;
			float walk = WalkSpeed * a.Pace * role.Speed;
			float hop;

			var squad = a.Squad >= 0 && a.Squad < _squads.Count ? _squads[a.Squad] : null;
			if ( squad is not null && squad.Broken ) { a.Squad = -1; squad = null; }

			if ( squad is not null )
			{
				// In formation: its place in the line, and nothing else.
				var place = (SlotPoint( squad, a.Slot ) - a.Position).WithZ( 0f );
				float left = place.Length;
				wish = left > 1f ? place / left : Vector3.Zero;
				speed = left > 14f ? MathF.Min( walk * 1.5f, left * 3f ) : 0f;
				faceLizard = !squad.Parade && speed <= 0f;
				hop = role.Plays ? MathF.Abs( MathF.Sin( now * 6.3f ) ) * 5f : 2f;
				apart *= 0.2f;
			}
			else if ( child )
			{
				// Waves at the big lizard. Is never hit.
				wish = Vector3.Zero;
				speed = 0f;
				faceLizard = true;
				hop = MathF.Abs( MathF.Sin( now * 5f + a.Phase ) ) * 5f;
				apart = Vector3.Zero;
			}
			else if ( hunting )
			{
				// Hunts where the lizard is going to be, and comes round the side rather than queueing.
				var aim = lizard + lizardVelocity * MathF.Min( distance / 400f, 1.4f ) * 0.5f;
				var toAim = (aim - a.Position).WithZ( 0f );
				wish = toAim.LengthSquared > 1f ? toAim.Normal : toward;
				if ( distance < 800f )
				{
					float round = ((i & 1) == 0 ? 1f : -1f) * 0.45f;
					wish += new Vector3( -toward.y, toward.x, 0f ) * round;
				}
				// No room to be real yet: circles at the edge of the scrum until there is.
				speed = distance > PhysicsRadius * 0.85f ? walk * (1f + 0.3f * a.Panic) : 0f;
				if ( speed <= 0f ) { wish = new Vector3( -toward.y, toward.x, 0f ) * ((i & 1) == 0 ? 1f : -1f); speed = walk * 0.6f; }
				hop = MathF.Abs( MathF.Sin( now * (7f + a.Pace * 2f) + a.Phase ) ) * 8f;
			}
			else if ( role.Manner == HumanManner.Reporter && !a.Cowed )
			{
				// Runs TOWARD it, and stops as close as the insurance allows.
				wish = toward;
				speed = distance > 420f ? walk * 1.5f : 0f;
				faceLizard = speed <= 0f;
				hop = MathF.Abs( MathF.Sin( now * 8f + a.Phase ) ) * (speed > 0f ? 7f : 2f);
			}
			else if ( role.Manner == HumanManner.Filmer && a.Hits == 0 && a.Panic < 0.85f && distance < 1500f && distance > 230f )
			{
				// Films it. Keeps filming.
				wish = Vector3.Zero;
				speed = 0f;
				faceLizard = true;
				hop = 1.5f;
			}
			else if ( a.Panic > 0.25f )
			{
				if ( a.HasCover )
				{
					// Behind the car, and down.
					var hide = (a.Cover - a.Position).WithZ( 0f );
					float left = hide.Length;
					wish = left > 1f ? hide / left : Vector3.Zero;
					speed = left > 24f ? walk * 1.8f : 0f;
					crouch = speed <= 0f;
					faceLizard = crouch;
					hop = crouch ? 0f : 8f;
					if ( distance < 170f ) a.HasCover = false;   // found: run for it
				}
				else
				{
					// Runs from it, with whoever is running alongside, down the street: a stampede.
					wish = -toward;
					if ( near > 0 && flow.LengthSquared > 100f ) wish += flow.Normal * 0.9f;
					wish += a.Lane * 0.9f;
					speed = walk * (0.7f + 1.5f * a.Panic);
					hop = MathF.Abs( MathF.Sin( now * (6f + 3f * a.Panic + a.Pace * 2f) + a.Phase ) ) * (4f + 11f * a.Panic);
				}
			}
			else
			{
				// Nothing wrong yet: about its business, along the street, never far from where it started.
				float heading = MathF.Sin( now * 0.23f + a.Phase ) * 5f + a.Phase;
				wish = new Vector3( MathF.Cos( heading ), MathF.Sin( heading ), 0f ) + a.Lane;
				var home = (a.Home - a.Position).WithZ( 0f );
				if ( a.Cell >= 0 && home.LengthSquared > 500f * 500f ) wish += home.Normal * 0.8f;
				bool jogging = role.Manner == HumanManner.Jogger;
				speed = walk * (jogging ? 1.2f : 0.4f);
				hop = MathF.Abs( MathF.Sin( now * (jogging ? 9f : 4.5f) + a.Phase ) ) * (jogging ? 6f : 2.5f);
			}

			// In the path of a charge: dive out of it, to whichever side is nearer. The crowd parts.
			if ( charging && !hunting && !child && squad is null && distance < 800f && bearing > 0.5f )
			{
				float across = -to.x * -lizardHeading.y + -to.y * lizardHeading.x;   // side of the lizard's line
				if ( MathF.Abs( across ) < 180f )
				{
					var sideways = new Vector3( -lizardHeading.y, lizardHeading.x, 0f ) * (across >= 0f ? 1f : -1f);
					wish = sideways * 1.6f + wish * 0.3f;
					speed = MathF.Max( speed, WalkSpeed * 2.4f );
					crouch = false;
				}
			}

			wish += apart * 1.7f;
			float length = wish.Length;
			if ( length > 1f ) wish /= length;
			if ( speed <= 0f && apart.LengthSquared > 0.04f && !crouch ) speed = WalkSpeed * 0.4f;   // still shuffles apart

			a.Velocity = Vector3.Lerp( a.Velocity, (wish * speed).WithZ( 0f ), MathF.Min( step * 4.5f, 1f ) );
			Walk( ref a, step );

			// Faces the way it goes; somebody standing its ground faces the lizard.
			float moving = a.Velocity.Length;
			if ( moving > 25f || faceLizard )
			{
				float face = moving > 25f ? MathF.Atan2( a.Velocity.y, a.Velocity.x ) : MathF.Atan2( toward.y, toward.x );
				float turn = (face - a.Yaw) % (MathF.PI * 2f);
				if ( turn > MathF.PI ) turn -= MathF.PI * 2f;
				if ( turn < -MathF.PI ) turn += MathF.PI * 2f;
				a.Yaw += turn * MathF.Min( step * 9f, 1f );
			}

			Place( ref a, role, hop, crouch, child, now );
		}

		_fleeing = fleeing;
	}

	/// <summary>Takes a step, sliding along whatever cannot be walked through.</summary>
	static void Walk( ref Agent a, float step )
	{
		var move = a.Velocity * step;
		if ( move.LengthSquared < 0.0001f ) return;

		var next = a.Position + move;
		if ( PopulaceMap.CanWalk( next ) ) { a.Position = next; return; }

		var alongX = a.Position + new Vector3( move.x, 0f, 0f );
		var alongY = a.Position + new Vector3( 0f, move.y, 0f );
		if ( MathF.Abs( move.x ) > 0.01f && PopulaceMap.CanWalk( alongX ) ) { a.Position = alongX; a.Velocity.y = 0f; }
		else if ( MathF.Abs( move.y ) > 0.01f && PopulaceMap.CanWalk( alongY ) ) { a.Position = alongY; a.Velocity.x = 0f; }
		else a.Velocity = -a.Velocity * 0.5f;       // a dead end: back the way it came
	}

	/// <summary>Puts the stand-in where its person is.</summary>
	void Place( ref Agent a, HumanRole role, float hop, bool crouch, bool wave, float now )
	{
		var s = a.StandIn;
		if ( s is null || !s.Go.IsValid() ) return;

		s.Go.WorldPosition = a.Position + Vector3.Up * hop;
		var turn = Rotation.FromYaw( a.Yaw * 180f / MathF.PI );
		s.Go.WorldRotation = wave ? turn * Rotation.FromRoll( MathF.Sin( now * 6f + a.Phase ) * 12f ) : turn;

		if ( crouch == a.Crouched ) return;
		a.Crouched = crouch;
		float size = role.Scale * (role.Burly || role.Guard ? 1.1f : 1f);
		s.Go.WorldScale = crouch ? new Vector3( size, size, size * 0.55f ) : new Vector3( size );
	}

	/// <summary>The nearest thing to hide behind, and the side of it away from the lizard.</summary>
	void FindCover( ref Agent a, Vector3 lizard )
	{
		// Asked for each time (the town keeps the list and looks it over every second or two): a list
		// of points kept in a field here would not survive a hotload.
		var cover = PopulaceMap.CoverPoints();
		if ( cover is null || cover.Count == 0 ) return;

		float best = 650f * 650f;
		var found = Vector3.Zero;
		bool any = false;
		for ( int c = 0; c < cover.Count; c++ )
		{
			float d = (cover[c] - a.Position).WithZ( 0f ).LengthSquared;
			if ( d >= best ) continue;
			best = d;
			found = cover[c];
			any = true;
		}
		if ( !any ) return;

		var behind = (found - lizard).WithZ( 0f );
		behind = behind.LengthSquared > 1f ? behind.Normal : Vector3.Forward;
		a.Cover = found + behind * 75f;
		a.HasCover = true;
	}

	// ---- Flying the cheap way -------------------------------------------------------------------------

	readonly List<int> _tossed = new();
	int _tossedFlying;
	static readonly string[] TossPassesThrough = { "crowd", "player", "fatguy", "debris", "trigger" };
	const float TossGravity = 800f;

	/// <summary>
	/// A stand-in is thrown: no physics body, just an arc, a spin, a bounce or two off whatever is
	/// in the way, and a landing. For when there are already as many real bodies as the frame can
	/// stand, so nothing the weapon touches ever just stands there.
	/// </summary>
	void Toss( int i, Vector3 velocity, int chain )
	{
		ref var a = ref _agents[i];
		if ( a.Level == Level.Tossed )
		{
			// Already up there: the hit just adds to it.
			if ( a.Dazed ) { a.Dazed = false; ClearStars( ref a ); a.Bounces = 0; }
			a.Velocity += velocity * 0.7f;
			a.Timer = Time.Now + 10f;
			return;
		}

		a.Level = Level.Tossed;
		a.Velocity = velocity;
		a.Timer = Time.Now + 10f;
		a.Bounces = 0;
		a.Chain = (byte)Math.Min( chain, 250 );
		a.Dazed = a.Stranded = a.HasCover = false;
		a.Squad = -1;
		_tossed.Add( i );
	}

	void UpdateTossed( float now, float dt )
	{
		int flying = 0;
		var player = Rampage.Player;

		for ( int n = _tossed.Count - 1; n >= 0; n-- )
		{
			int i = _tossed[n];
			ref var a = ref _agents[i];
			var s = a.StandIn;
			if ( a.Level != Level.Tossed || s is null || !s.Go.IsValid() ) { _tossed.RemoveAt( n ); continue; }
			var role = HumanRoles.All[a.Role];

			if ( a.Dazed )
			{
				// Flat on its back with stars going round, then up and off.
				if ( now < a.Timer )
				{
					if ( s.Stars is not null ) PopulaceFx.SpinStars( s.Stars, a.Position + Vector3.Up * 16f, now );
					continue;
				}

				ClearStars( ref a );
				a.Dazed = false;
				a.Level = Level.StandIn;
				a.Cowed = !role.Relentless;
				a.Panic = 1f;
				a.Velocity = Vector3.Zero;
				a.Stranded = a.Position.z > PopulaceMap.GroundAt( a.Position ) + 90f;   // came down on a roof
				a.Crouched = true;      // so Place puts its size back
				Place( ref a, role, 0f, false, false, now );
				_tossed.RemoveAt( n );
				continue;
			}

			flying++;
			a.Velocity.z -= TossGravity * FlightGravity * dt;
			var from = a.Position;
			var next = from + a.Velocity * dt;
			bool landed = false;

			// Walls, roofs, trees and lampposts: off them, or onto them.
			var normal = Vector3.Up;
			bool struck = false;
			if ( TossedHitWalls )
			{
				var lift = Vector3.Up * 30f;
				var trace = Scene.Trace.Ray( from + lift, next + lift ).WithoutTags( TossPassesThrough );
				if ( player.IsValid() ) trace = trace.IgnoreGameObjectHierarchy( player.GameObject );
				var tr = trace.Run();
				if ( tr.Hit )
				{
					struck = true;
					normal = tr.Normal;
					// Onto a floor or a roof: that is where its feet are. Off a wall: stood clear of it.
					next = normal.z > 0.6f ? tr.HitPosition : tr.HitPosition + normal * 14f - lift;
				}
			}

			float ground = PopulaceMap.GroundAt( next );
			if ( next.z <= ground && a.Velocity.z < 0f )
			{
				struck = true;
				normal = Vector3.Up;
				next.z = ground;
			}

			// Out of town is out of bounds: back in off the edge of the world.
			var kept = PopulaceMap.Contain( next );
			if ( kept.x != next.x ) a.Velocity.x = -a.Velocity.x * 0.5f;
			if ( kept.y != next.y ) a.Velocity.y = -a.Velocity.y * 0.5f;
			next = kept;

			if ( struck )
			{
				float into = -Vector3.Dot( a.Velocity, normal );
				bool floor = normal.z > 0.6f;

				// Whoever it came down on goes over too, up to a point.
				if ( floor && a.Bounces == 0 && a.Chain < ChainDepth )
					KnockNear( next, 75f, a.Velocity.WithZ( 0f ) * ChainKeep + Vector3.Up * 300f, a.Chain + 1, 2, i );

				if ( floor && (into < 260f || a.Bounces >= 2) ) landed = true;
				else if ( into > 0f )
				{
					a.Velocity = (a.Velocity + normal * into * 2f) * (floor ? 0.45f : 0.5f);
					if ( a.Bounces < 250 ) a.Bounces++;
					if ( a.Bounces > 5 ) a.Velocity = new Vector3( 0f, 0f, MathF.Min( a.Velocity.z, 0f ) );
					PopulaceFx.Sound( "bounce", next, Math.Clamp( into / 900f, 0.3f, 1f ) );
				}
			}

			a.Position = next;
			if ( now >= a.Timer ) { a.Position.z = ground; landed = true; }

			if ( landed )
			{
				a.Dazed = true;
				a.Timer = now + DazeSeconds * Game.Random.Float( 0.7f, 1.3f );
				a.Velocity = Vector3.Zero;
				s.Go.WorldPosition = a.Position + Vector3.Up * 7f;
				s.Go.WorldRotation = Rotation.FromYaw( a.Yaw * 180f / MathF.PI ) * Rotation.FromPitch( -90f );
				s.Stars = PopulaceFx.TakeStars( _root );
				PopulaceFx.Sound( "thud_land", a.Position, 0.8f );
				continue;
			}

			// Head over heels.
			var axis = new Vector3( MathF.Cos( a.Phase ), MathF.Sin( a.Phase ), 0.3f ).Normal;
			s.Go.WorldPosition = a.Position + Vector3.Up * 20f;
			s.Go.WorldRotation = Rotation.FromAxis( axis, now * Spin * 40f ) * Rotation.FromYaw( a.Yaw * 180f / MathF.PI );
			if ( role.Plays ) Toot( a.Position, now );
		}

		_tossedFlying = flying;
	}

	void ClearStars( ref Agent a )
	{
		var s = a.StandIn;
		if ( s?.Stars is null ) return;
		PopulaceFx.ReturnStars( s.Stars );
		s.Stars = null;
	}

	/// <summary>
	/// Hits the stand-ins standing within a radius of a spot (somebody flying has come down on
	/// them). Real bodies look after themselves: they are solid, and trip.
	/// </summary>
	int KnockNear( Vector3 at, float radius, Vector3 velocity, int chain, int most, int except )
	{
		int knocked = 0;
		int reach = (int)MathF.Ceiling( radius / GridSize );
		int cx = (int)MathF.Floor( at.x / GridSize ), cy = (int)MathF.Floor( at.y / GridSize );
		for ( int gx = cx - reach; gx <= cx + reach && knocked < most; gx++ )
			for ( int gy = cy - reach; gy <= cy + reach && knocked < most; gy++ )
			{
				if ( !_grid.TryGetValue( GridKey( gx, gy ), out int j ) ) continue;
				for ( ; j >= 0 && knocked < most; j = _gridNext[j] )
				{
					if ( j == except || _agents[j].Level != Level.StandIn ) continue;
					var gap = _agents[j].Position - at;
					if ( gap.WithZ( 0f ).LengthSquared > radius * radius || MathF.Abs( gap.z ) > 110f ) continue;
					if ( HitAgent( j, velocity, 0f, _agents[j].Position, chain ) ) knocked++;
				}
			}
		return knocked;
	}
}