Rampage/Humans/RampagePopulace.Bodies.cs

Part of RampagePopulace, the simulated crowd around the lizard. It promotes stand-ins into real stadium CrowdPerson bodies when they get close, launches them with a physics hit, handles flight, getting stuck in trees, knocking others over, dazed star-spinning, and turns them back into stand-ins once they are far away or lost.

using System;
using System.Collections.Generic;

// The crowd right on top of the lizard: real physics bodies (the stadium's CrowdPerson), what
// each is told to do, and everything that happens to one between being hit and staggering off.
public sealed partial class RampagePopulace
{
	/// <summary>One real body and how its flight is going.</summary>
	sealed class RealBody
	{
		public int Agent;
		public CrowdPerson Person;
		public Rigidbody Rb;
		public GameObject Prop, Stars;

		public bool Flying;             // hit and not yet landed
		public bool HasPending;         // hit before its body existed: thrown as soon as it does
		public Vector3 Pending;
		public bool StuckOnce;          // has already had its moment in a tree
		public bool Saluted;
		public float LaunchedAt, StuckUntil, DazeUntil, SaluteUntil, StillFor, LastSpeed;
		public float NextThink, NextStroll;
		public int Knocks;              // how many people it has bowled over this flight
		public CrowdState LastState = CrowdState.Standing;
	}

	readonly List<RealBody> _real = new();
	int _flying;
	float _nextToot, _nextWhistle;

	/// <summary>A stand-in becomes a real person: the stadium's body, dressed for its part.</summary>
	RealBody Promote( int i )
	{
		ref var a = ref _agents[i];
		var role = HumanRoles.All[a.Role];
		var at = a.Position;
		ReturnStandIn( ref a );
		RemoveAwake( i );

		var go = new GameObject( _root, true, role.Name );
		go.Flags |= GameObjectFlags.NotSaved;
		go.WorldPosition = at + Vector3.Up;
		go.WorldRotation = Rotation.FromYaw( a.Yaw * 180f / MathF.PI );
		float size = role.Scale * (role.Burly ? 1.1f : 1f);
		if ( MathF.Abs( size - 1f ) > 0.01f ) go.WorldScale = size;

		var person = go.Components.Create<CrowdPerson>();
		person.Host = _grips;
		person.IsGuard = role.Guard;
		person.GrabberChance = a.Brave && !a.Cowed ? 1f : 0f;
		person.GrabWindup = 0.55f;
		person.GrabRange = MathF.Max( 50f, RampageGiant.ScaleNow * 14f );   // a giant's ankle is a long way round
		person.RunSpeed = 140f * role.Speed;
		person.LeaveThroughExit = false;
		person.DownTimeScale = 1f;                      // how long they lie there is decided here
		person.PatronHealth = person.GuardHealth = 1000000f;    // nobody dies
		person.ShirtTint = role.Shirt ?? Palette[a.Colour % Palette.Length];
		person.TrouserTint = role.Trousers;
		person.CoatTint = role.Coat;
		if ( !role.Guard ) { person.HatTint = role.Hat; person.WideHat = role.WideHat; }   // a guard has its own cap
		person.Passive = true;                          // until it is told otherwise (see Direct)

		var body = new RealBody { Agent = i, Person = person, NextThink = 0f };
		if ( role.Prop is not null && (!role.Shield || a.Shielded) )
			body.Prop = PopulaceFx.Block( go, "Prop", role.Prop.Position, role.Prop.Size, role.Prop.Tint, role.Prop.Ball );

		a.Body = body;
		a.Level = Level.Real;
		a.Velocity = Vector3.Zero;
		a.Crouched = a.HasCover = false;
		_real.Add( body );
		return body;
	}

	/// <summary>A real body left behind turns back into a stand-in.</summary>
	void Demote( RealBody body )
	{
		ref var a = ref _agents[body.Agent];
		if ( body.Stars is not null ) { PopulaceFx.ReturnStars( body.Stars ); body.Stars = null; }

		if ( body.Person.IsValid() )
		{
			a.Position = body.Person.WorldPosition;
			a.Yaw = body.Person.WorldRotation.Yaw() * MathF.PI / 180f;
			body.Person.GameObject.Destroy();
		}
		a.Body = null;
		a.Velocity = Vector3.Zero;
		a.Stranded = a.Position.z > PopulaceMap.GroundAt( a.Position ) + 90f;
		if ( !a.Stranded ) a.Position.z = PopulaceMap.GroundAt( a.Position );
		a.Stray = a.Cell < 0 || !_cells[a.Cell].Awake;
		a.Crouched = false;
		a.Level = Level.StandIn;
		a.StandIn = TakeStandIn( in a );
		a.AwakeSlot = _awake.Count;
		_awake.Add( body.Agent );
	}

	void UpdateBodies( Vector3 lizard, float now, float dt )
	{
		float demote2 = DemoteRadius * DemoteRadius;
		int flying = 0;

		for ( int n = _real.Count - 1; n >= 0; n-- )
		{
			var body = _real[n];
			ref var a = ref _agents[body.Agent];
			bool remove = false;

			if ( !body.Person.IsValid() )
			{
				// Fell out of the world, or was cleared away by something else: home, quietly.
				LostBody( body );
				remove = true;
			}
			else
			{
				var person = body.Person;
				body.Rb ??= person.Components.Get<Rigidbody>();
				a.Position = person.WorldPosition;
				var role = HumanRoles.All[a.Role];

				if ( body.Rb.IsValid() )
				{
					if ( body.HasPending ) { body.HasPending = false; Launch( body, body.Pending, now ); }

					if ( body.Flying ) { flying++; Fly( body, ref a, role, now, dt ); }
					else Ground( body, ref a, role, lizard, now );

					body.LastState = person.State;
					body.LastSpeed = body.Rb.Velocity.Length;

					// Left behind and on its feet: a stand-in again.
					if ( !body.Flying && body.DazeUntil <= 0f && person.State == CrowdState.Standing
						&& (lizard - a.Position).WithZ( 0f ).LengthSquared > demote2 )
					{
						Demote( body );
						remove = true;
					}
				}
			}

			if ( !remove ) continue;
			_real[n] = _real[^1];
			_real.RemoveAt( _real.Count - 1 );
		}

		_flying = flying;
		if ( flying > 0 || _tossedFlying > 0 ) _airborneUntil = now + 1.5f;
	}

	/// <summary>Somebody going down within this of the lizard is its doing.</summary>
	const float SkittleRange = 260f;
	float _airborneUntil;

	void LostBody( RealBody body )
	{
		ref var a = ref _agents[body.Agent];
		if ( body.Stars is not null ) { PopulaceFx.ReturnStars( body.Stars ); body.Stars = null; }
		a.Body = null;
		a.Position = a.Cell >= 0 ? a.Home : PopulaceMap.Contain( a.Position );
		a.Position.z = PopulaceMap.GroundAt( a.Position );
		a.Level = Level.StandIn;
		a.Stray = true;
		a.Stranded = a.Crouched = false;
		a.StandIn = TakeStandIn( in a );
		a.AwakeSlot = _awake.Count;
		_awake.Add( body.Agent );
	}

	// ---- Being hit ------------------------------------------------------------------------------------

	/// <summary>
	/// Off the ground: bowled with the hit, spinning, in a long floaty arc. They stay down, flailing,
	/// until they have landed and seen their stars.
	/// </summary>
	void Launch( RealBody body, Vector3 velocity, float now )
	{
		var person = body.Person;
		if ( !person.IsValid() || !body.Rb.IsValid() ) return;

		if ( body.Stars is not null ) { PopulaceFx.ReturnStars( body.Stars ); body.Stars = null; }
		body.DazeUntil = 0f;
		body.StuckUntil = 0f;

		if ( body.Flying )
		{
			// Already in the air: the hit just adds to it. Juggling is allowed.
			body.Rb.MotionEnabled = true;
			body.Rb.Velocity += velocity * 0.7f;
			body.Rb.AngularVelocity += Vector3.Random * Spin * 0.5f;
			person.DownFor( 30f );
			return;
		}

		person.Bowl( velocity, now );
		person.DownFor( 30f );
		body.Rb.AngularVelocity += Vector3.Random * Spin;
		body.Rb.GravityScale = FlightGravity;
		body.Flying = true;
		body.LaunchedAt = now;
		body.StuckOnce = false;
		body.StillFor = 0f;
		body.Knocks = 0;
		body.LastSpeed = velocity.Length;
	}

	/// <summary>In the air: sticks in trees, bowls over whoever is underneath, and comes down in the end.</summary>
	void Fly( RealBody body, ref Agent a, HumanRole role, float now, float dt )
	{
		var person = body.Person;
		var rb = body.Rb;
		var velocity = rb.Velocity;
		float speed = velocity.Length;
		float height = a.Position.z - PopulaceMap.GroundAt( a.Position );

		// Got up some other way (something reset it): no longer flying.
		if ( person.State != CrowdState.Down ) { rb.GravityScale = 1f; body.Flying = false; return; }

		if ( body.StuckUntil > 0f )
		{
			// Hanging in a tree, legs going. Then down it comes.
			if ( now < body.StuckUntil ) return;
			body.StuckUntil = 0f;
			rb.MotionEnabled = true;
			rb.Velocity = new Vector3( Game.Random.Float( -60f, 60f ), Game.Random.Float( -60f, 60f ), 40f );
			rb.AngularVelocity = Vector3.Random * 4f;
			PopulaceFx.Sound( "unstuck_pop", a.Position, 0.7f );
			return;
		}

		// Stopped dead against something well off the ground: a tree, a lamppost, the side of a
		// building. Now and then they stick there for a moment.
		if ( !body.StuckOnce && now > body.LaunchedAt + 0.15f && height > 130f && body.LastSpeed > 450f && speed < body.LastSpeed * 0.4f )
		{
			body.StuckOnce = true;
			if ( Game.Random.Float( 0f, 1f ) < StickChance )
			{
				rb.Velocity = Vector3.Zero;
				rb.AngularVelocity = Vector3.Zero;
				rb.MotionEnabled = false;
				body.StuckUntil = now + Game.Random.Float( 1.2f, 2.4f );
				PopulaceFx.Sound( "stuck_twang", a.Position );
				return;
			}
			PopulaceFx.Sound( "bounce", a.Position, 0.8f );
		}

		// Coming through the crowd at head height: whoever it lands on goes over too. Up to a point.
		if ( speed > 320f && height < 120f && body.Knocks < ChainKnocks && a.Chain < ChainDepth && now > body.LaunchedAt + 0.25f )
			body.Knocks += KnockNear( a.Position, 60f, velocity.WithZ( 0f ) * ChainKeep + Vector3.Up * 320f, a.Chain + 1, ChainKnocks - body.Knocks, body.Agent );

		if ( role.Plays ) Toot( a.Position, now );     // the band plays on

		// Down, and still: stars.
		body.StillFor = speed < 70f ? body.StillFor + dt : 0f;
		bool down = now > body.LaunchedAt + 0.4f && ((height < 40f && speed < 110f) || body.StillFor > 0.35f);
		if ( !down && now < body.LaunchedAt + 14f ) return;

		rb.GravityScale = 1f;
		body.Flying = false;
		body.DazeUntil = now + DazeSeconds * Game.Random.Float( 0.7f, 1.3f );
		person.DownFor( body.DazeUntil - now );
		body.Stars = PopulaceFx.TakeStars( _root );
		PopulaceFx.Sound( "thud_land", a.Position );
		if ( body.Stars is not null ) PopulaceFx.Sound( "stars", a.Position, 0.5f );
	}

	/// <summary>Not flying: dazed with stars, getting up and staggering off, or going about its part.</summary>
	void Ground( RealBody body, ref Agent a, HumanRole role, Vector3 lizard, float now )
	{
		var person = body.Person;

		// Went down without being hit by the weapon: somebody flying landed on it, or the lizard ran
		// it over. That counts.
		if ( person.State == CrowdState.Down && body.LastState != CrowdState.Down && body.DazeUntil <= 0f )
		{
			// It only counts when the lizard had something to do with it: it is right there, or
			// people are flying about. Somebody tripping over his own feet three streets away is
			// not a score (measured: it was, and a town falling over by itself raised the tier).
			if ( FlatDistance( lizard, a.Position ) < SkittleRange || now < _airborneUntil )
			{
				Award( ref a, role, a.Position, " (SKITTLED)" );
				if ( a.Hits < 250 ) a.Hits++;
			}
			body.DazeUntil = now + DazeSeconds * 0.6f;
			person.DownFor( body.DazeUntil - now );
			body.Stars = PopulaceFx.TakeStars( _root );
			AddScare( a.Position, HitScareRadius * 0.6f );
		}

		if ( body.DazeUntil > 0f )
		{
			if ( body.Stars is not null )
				PopulaceFx.SpinStars( body.Stars, person.WorldTransform.PointToWorld( new Vector3( 0f, 0f, 74f ) ), now );
			if ( now < body.DazeUntil || person.State == CrowdState.Down ) return;

			// Up. Dizzy. Leaving.
			if ( body.Stars is not null ) { PopulaceFx.ReturnStars( body.Stars ); body.Stars = null; }
			body.DazeUntil = 0f;
			a.Cowed = !role.Relentless;
			a.Panic = 1f;
			a.Squad = -1;
			person.Push( Vector3.Random.WithZ( 0f ) * 70f, 1.3f, now );
			body.NextThink = 0f;
		}

		if ( now < body.NextThink ) return;
		body.NextThink = now + 0.25f;
		Direct( body, ref a, role, lizard, now );
	}

	/// <summary>
	/// Tells a real body what its part is just now. The stadium's person does the rest: left to
	/// itself (not passive) a grabber walks at the lizard, leaps and takes hold of a limb, and
	/// anybody else runs away. Passive, it stands or walks where it is sent.
	/// </summary>
	void Direct( RealBody body, ref Agent a, HumanRole role, Vector3 lizard, float now )
	{
		var person = body.Person;
		if ( person.State == CrowdState.Holding ) return;

		float distance = FlatDistance( lizard, a.Position );
		float scare = ScareAt( distance );
		if ( _scares.Count > 0 && InScare( a.Position ) ) scare = 1f;
		scare *= a.Cowed ? 1f : role.Nerves;
		a.Panic += (scare - a.Panic) * (scare > a.Panic ? 0.8f : 0.06f);

		bool hunting = a.Brave && !a.Cowed;
		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; }

		person.Gesture = 0;
		person.LookAt = null;

		if ( squad is not null )
		{
			// Holding the line (or marching in the parade).
			person.SetGrabber( false );
			person.Passive = true;
			person.PassiveSpeed = 170f;
			person.GoTo = SlotPoint( squad, a.Slot );
			if ( !squad.Parade ) person.LookAt = lizard;
			person.Gesture = role.Plays ? 4 : role.Salutes && distance < 700f ? 1 : 0;
			return;
		}

		if ( hunting )
		{
			// A soldier salutes first. Then the stadium's rules: walk, leap, grab.
			if ( role.Salutes && !body.Saluted && distance < 430f )
			{
				body.Saluted = true;
				body.SaluteUntil = now + 1.3f;
				PopulaceFx.Sound( "salute", a.Position, 0.7f );
			}
			if ( now < body.SaluteUntil )
			{
				person.Passive = true;
				person.GoTo = null;
				person.LookAt = lizard;
				person.Gesture = 1;
				return;
			}
			if ( role.Whistles && distance < 900f && now >= _nextWhistle )
			{
				_nextWhistle = now + Game.Random.Float( 1.4f, 2.6f );
				PopulaceFx.Sound( "police_whistle", a.Position, 0.6f, Game.Random.Float( 0.95f, 1.1f ) );
			}
			person.SetGrabber( true );
			person.Passive = false;
			return;
		}

		person.SetGrabber( false );

		if ( role.Manner == HumanManner.Reporter && !a.Cowed )
		{
			// As close as the camera needs, pointing the thing at it.
			var from = (a.Position - lizard).WithZ( 0f );
			person.Passive = true;
			person.PassiveSpeed = 210f;
			person.GoTo = distance > 430f ? lizard + (from.LengthSquared > 1f ? from.Normal : Vector3.Forward) * 380f : (Vector3?)null;
			person.LookAt = lizard;
			person.Gesture = 2;
			return;
		}

		if ( (role.Manner == HumanManner.Filmer || role.Salutes) && a.Hits == 0 && a.Panic < 0.85f && distance > 200f )
		{
			// Still filming (or, for a general out of his parade, still saluting).
			person.Passive = true;
			person.GoTo = null;
			person.LookAt = lizard;
			person.Gesture = role.Salutes ? 1 : 2;
			return;
		}

		if ( a.Panic > 0.25f || (a.Cowed && distance < 900f) )
		{
			person.Passive = false;     // runs, by the stadium's rules, toward the host's way out
			return;
		}

		// Nothing wrong yet: strolling from one bit of street to the next.
		person.Passive = true;
		person.PassiveSpeed = role.Manner == HumanManner.Jogger ? 190f : 70f;
		if ( now >= body.NextStroll || person.AtGoal )
		{
			body.NextStroll = now + Game.Random.Float( 4f, 9f );
			var about = a.Position + new Vector3( Game.Random.Float( -500f, 500f ), Game.Random.Float( -500f, 500f ), 0f );
			person.GoTo = PopulaceMap.NearestStreet( about, out var street ) < 900f ? street : PopulaceMap.Contain( about );
		}
	}

	/// <summary>A note from the band, wherever it currently is. One at a time, however many of them are in the air.</summary>
	void Toot( Vector3 at, float now )
	{
		if ( now < _nextToot ) return;
		_nextToot = now + Game.Random.Float( 0.3f, 0.55f );
		PopulaceFx.Sound( "band_toot", at, 0.8f, Game.Random.Float( 0.8f, 1.3f ) );
	}
}