Sump/Flashbacks/FlashbackCrowd.cs

The crowd host for a flashback arena, implementing ICrowdHost so CrowdPerson can find it. Keeps the list of grips on the player's limbs, moves grip anchor objects around the body each fixed update, turns SPACE bucks and mouse shake into strain that breaks one grip at a time, and sets the player's speed scale, leash pin and view clear from the grip count.

using System;
using System.Collections.Generic;

/// <summary>
/// The crowd's host inside a flashback: what <see cref="StadiumGame"/> is to the stadium. The
/// humans in every memory are the stadium crowd (<see cref="CrowdPerson"/>), and they find this
/// through <see cref="ICrowdHost"/>. It keeps the grips on the player's limbs and the shake-free
/// rules, which are the stadium's own, number for number: one grip at a time takes the strain,
/// every further hand makes it harder, two hands pin you to the spot.
/// One per arena, on the arena's root, so it goes when the arena goes.
/// </summary>
[Title( "Flashback Crowd" ), Category( "Sump" ), Icon( "groups" )]
public sealed class FlashbackCrowd : Component, ICrowdHost
{
	// ---- Grips (the stadium's numbers) ----------------------------------------------------------
	/// <summary>Force needed to shake off a single grip (acceleration of the body, inches per second squared).</summary>
	[Property, Group( "Grips" )] public float BreakForce { get; set; } = 5200f;
	/// <summary>How much more force each further grip adds, as a fraction of <see cref="BreakForce"/>.</summary>
	[Property, Group( "Grips" )] public float ForcePerExtraGrip { get; set; } = 0.35f;
	/// <summary>How quickly a grip gives under enough force.</summary>
	[Property, Group( "Grips" )] public float StrainRate { get; set; } = 3.2f;
	/// <summary>Force added by one press of SPACE (a buck).</summary>
	[Property, Group( "Grips" )] public float BuckForce { get; set; } = 5200f;
	/// <summary>Force added by shaking the mouse, per pixel per second.</summary>
	[Property, Group( "Grips" )] public float MouseShakeForce { get; set; } = 1.2f;
	/// <summary>With this many grips on, the player is pinned to the spot.</summary>
	[Property, Group( "Grips" )] public int PinGrips { get; set; } = 2;
	/// <summary>How much each grip slows the player: speed is divided by 1 + this per grip.</summary>
	[Property, Group( "Grips" )] public float SlowPerGrip { get; set; } = 0.45f;
	/// <summary>Seconds after the last grip breaks during which nobody can grab.</summary>
	[Property, Group( "Grips" )] public float FreeSeconds { get; set; } = 1.2f;

	/// <summary>Multiplies <see cref="BreakForce"/> for the body the player is in (slippery bodies are below 1).</summary>
	public float GripFactor { get; set; } = 1f;

	/// <summary>True while the memory is running: the humans move, patrol and grab. False: they are statues.</summary>
	public bool Live { get; set; }

	/// <summary>Set while something other than hands holds the player (straps): SPACE still bucks.</summary>
	public bool Struggling { get; set; }

	public ReptileController Player { get; set; }

	// ---- The floor the crowd stands on ----------------------------------------------------------
	public Vector3 Centre { get; set; }
	public float HalfX { get; set; } = 2000f;
	public float HalfY { get; set; } = 2000f;
	public float FloorZ { get; set; }

	// ---- State ----------------------------------------------------------------------------------
	sealed class Grip
	{
		public GameObject Holder;
		public int Limb;
		public float Strain;
	}

	readonly List<Grip> _grips = new();
	GameObject[] _anchors;
	TimeSince _sinceFree = 100f;
	float _graceUntil;
	Vector3 _pinPosition;
	Vector3 _lastVelocity;
	float _buck;

	// Where the hands find something to hold, round whatever body the player is in (its own frame).
	static readonly Vector3[] AnchorOffsets =
	{
		new( 14f, 12f, 14f ), new( 14f, -12f, 14f ), new( -12f, 12f, 12f ), new( -12f, -12f, 12f ), new( -22f, 0f, 14f ),
	};

	public int Grabbers => _grips.Count;
	public bool Held => _grips.Count > 0;
	public bool Pinned => _grips.Count >= PinGrips;
	/// <summary>How long the player has been pinned without a break, in seconds.</summary>
	public float PinnedSeconds { get; private set; }
	/// <summary>The force the player's thrashing is producing right now.</summary>
	public float ShakeForce { get; private set; }
	public float ForceNeeded => BreakForce * GripFactor * (1f + ForcePerExtraGrip * MathF.Max( _grips.Count - 1, 0 ));
	/// <summary>How close the grip being worked on is to breaking, 0 to 1.</summary>
	public float Struggle => _grips.Count > 0 ? _grips[0].Strain : 0f;
	public bool Slippery => _sinceFree < FreeSeconds || Time.Now < _graceUntil;

	public event Action<GameObject> GripBroken;
	/// <summary>Raised when the last grip goes.</summary>
	public event Action BrokeFree;
	/// <summary>Raised when the first hand lands.</summary>
	public event Action Grabbed;

	// ---- ICrowdHost -----------------------------------------------------------------------------
	public CrowdPhase CrowdPhase => Live ? CrowdPhase.Chasing : CrowdPhase.Waiting;
	public float ShiftProgress => 1f;
	public Vector3 Focus => Centre;
	public float GroundHeight( Vector3 point ) => FloorZ;
	public bool InExit( Vector3 point ) => false;
	public Vector3 ExitRoute( Vector3 from ) => WanderPoint();
	public Vector3 WanderPoint() => Centre + new Vector3( Game.Random.Float( -HalfX, HalfX ) * 0.8f, Game.Random.Float( -HalfY, HalfY ) * 0.8f, 0f );
	public Vector3 Contain( Vector3 p ) => new(
		Math.Clamp( p.x, Centre.x - HalfX + 60f, Centre.x + HalfX - 60f ),
		Math.Clamp( p.y, Centre.y - HalfY + 60f, Centre.y + HalfY - 60f ), p.z );

	public bool TryGrab( GameObject holder, out GameObject anchor )
	{
		anchor = null;
		if ( !Live || Slippery || !Player.IsValid() || !holder.IsValid() || _anchors is null ) return false;

		int limb = -1;
		float nearest = float.MaxValue;
		for ( int i = 0; i < _anchors.Length; i++ )
		{
			bool taken = false;
			foreach ( var grip in _grips )
			{
				if ( grip.Holder == holder ) return false; // one limb each
				if ( grip.Limb == i ) taken = true;
			}
			if ( taken || !_anchors[i].IsValid() ) continue;

			float d = (_anchors[i].WorldPosition - holder.WorldPosition).LengthSquared;
			if ( d < nearest ) { nearest = d; limb = i; }
		}
		if ( limb < 0 ) return false;

		_grips.Add( new Grip { Holder = holder, Limb = limb } );
		anchor = _anchors[limb];

		if ( _grips.Count == 1 ) Grabbed?.Invoke();
		if ( _grips.Count == PinGrips ) _pinPosition = Player.WorldPosition;
		return true;
	}

	public void ReleaseGrab( GameObject holder )
	{
		int removed = _grips.RemoveAll( g => g.Holder == holder );
		if ( removed > 0 && _grips.Count == 0 ) Loose();
	}

	void Loose()
	{
		_sinceFree = 0;
		BrokeFree?.Invoke();
	}

	/// <summary>Everybody holding the player is thrown off at once (a rewind, a scripted beat).</summary>
	public void ReleaseAll()
	{
		var holders = new List<GameObject>();
		foreach ( var grip in _grips ) holders.Add( grip.Holder );
		_grips.Clear();
		foreach ( var holder in holders )
			if ( holder.IsValid() ) GripBroken?.Invoke( holder );
		PinnedSeconds = 0f;
		if ( holders.Count > 0 ) Loose();
		if ( Player.IsValid() ) { Player.Leash = null; Player.SpeedScale = 1f; Player.ClearView = false; }
	}

	/// <summary>Nobody can grab for this many seconds.</summary>
	public void Grace( float seconds ) => _graceUntil = MathF.Max( _graceUntil, Time.Now + seconds );

	/// <summary>Takes the player on: makes the things the hands hold on to.</summary>
	public void Adopt( ReptileController player )
	{
		Player = player;
		CrowdHosts.Fallback = this;
		if ( _anchors is not null || !player.IsValid() ) return;

		_anchors = new GameObject[AnchorOffsets.Length];
		for ( int i = 0; i < _anchors.Length; i++ )
		{
			var go = new GameObject( GameObject, true, "Grip Anchor " + i );
			go.Flags |= GameObjectFlags.NotSaved;
			go.WorldPosition = player.WorldPosition;

			var body = go.Components.Create<Rigidbody>();
			body.Gravity = false;
			body.MotionEnabled = false; // moved by hand to follow the body

			var shape = go.Components.Create<SphereCollider>();
			shape.Radius = 2f;
			shape.IsTrigger = true;

			_anchors[i] = go;
		}
	}

	protected override void OnUpdate()
	{
		// A buck: one sharp heave against whoever (or whatever) is holding on.
		if ( (Held || Struggling) && Input.Pressed( "Jump" ) ) _buck = MathF.Min( _buck + BuckForce, BuckForce * 2f );
	}

	protected override void OnFixedUpdate()
	{
		if ( !Player.IsValid() || _anchors is null ) return;
		float dt = MathF.Max( Time.Delta, 0.001f );

		// The anchors ride round the body.
		var at = Player.WorldPosition;
		var turn = Rotation.FromYaw( Player.WorldRotation.Angles().yaw );
		for ( int i = 0; i < _anchors.Length; i++ )
			if ( _anchors[i].IsValid() ) _anchors[i].WorldPosition = at + turn * AnchorOffsets[i];

		// The force of the thrashing: how violently the body changes its motion, plus the mouse
		// being shaken, plus any buck. It holds its peaks for a moment so a sharp jerk counts.
		var velocity = Player.Velocity;
		float force = (velocity - _lastVelocity).Length / dt + Input.MouseDelta.Length / dt * MouseShakeForce + _buck;
		_lastVelocity = velocity;
		_buck = MathF.Max( _buck - BuckForce * 5f * dt, 0f );
		ShakeForce = MathF.Max( force, ShakeForce * MathF.Exp( -8f * dt ) );

		if ( !Live )
		{
			if ( _grips.Count > 0 ) ReleaseAll();
			PinnedSeconds = 0f;
			return;
		}

		// Holders that are gone let go.
		for ( int i = _grips.Count - 1; i >= 0; i-- )
			if ( !_grips[i].Holder.IsValid() ) { _grips.RemoveAt( i ); if ( _grips.Count == 0 ) Loose(); }

		// One grip at a time takes the strain. Enough force for long enough and it gives; with
		// more hands on, more force is needed, so a pile has to be peeled off one by one.
		if ( _grips.Count > 0 )
		{
			var grip = _grips[0];
			float ratio = ShakeForce / MathF.Max( ForceNeeded, 1f );
			grip.Strain = ratio > 0.5f ? grip.Strain + ratio * StrainRate * dt : MathF.Max( grip.Strain - 0.5f * dt, 0f );

			if ( grip.Strain >= 1f )
			{
				_grips.RemoveAt( 0 );
				GripBroken?.Invoke( grip.Holder );
				Player.Kick( Vector3.Random * 6f );
				if ( _grips.Count == 0 ) Loose();
			}
		}

		// Dragging people about is slow, and a pile holds the player to the spot.
		Player.SpeedScale = 1f / (1f + SlowPerGrip * _grips.Count);
		Player.Leash = Pinned ? _pinPosition : null;
		Player.ClearView = Held;
		PinnedSeconds = Pinned ? PinnedSeconds + dt : MathF.Max( PinnedSeconds - dt * 2f, 0f );
	}

	protected override void OnDestroy()
	{
		if ( ReferenceEquals( CrowdHosts.Fallback, this ) ) CrowdHosts.Fallback = null;
		_grips.Clear();
		if ( Player.IsValid() ) { Player.Leash = null; Player.SpeedScale = 1f; Player.ClearView = false; }
	}
}