Rampage/Humans/PopulaceGrips.cs

Crowd host for the town map in Rampage. Keeps the lizard's grab anchors on its limbs, runs the grip strain, buck, mouse shake and pin/leash rules, and fires the indignity reflex that throws everyone off after a few seconds pinned. Implements ICrowdHost so CrowdPerson bodies can ask for ground height, exit routes and wander points.

using System;
using System.Collections.Generic;

/// <summary>
/// The crowd's host on the surface: what <see cref="StadiumGame"/> is to the stadium and
/// <see cref="FlashbackCrowd"/> to a memory. The town's real bodies are the stadium crowd
/// (<see cref="CrowdPerson"/>) and find this through <see cref="ICrowdHost"/>. It keeps the grips
/// on the lizard's limbs and the stadium's shake-free rules, number for number. The one
/// difference: being pinned is never the end. Leave the lizard under a pile for a few seconds and
/// the weapon thrashes of its own accord and throws everybody off in a ring: the indignity reflex.
/// Made by <see cref="RampagePopulace"/>, on the same object.
/// </summary>
[Title( "Populace Grips" ), Category( "Rampage" ), Icon( "pan_tool" )]
public sealed class PopulaceGrips : 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; } = 3400f;
	/// <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 lizard is pinned to the spot.</summary>
	[Property, Group( "Grips" )] public int PinGrips { get; set; } = 3;
	/// <summary>How much each grip slows the lizard: speed is divided by 1 + this per grip.</summary>
	[Property, Group( "Grips" )] public float SlowPerGrip { get; set; } = 0.25f;
	/// <summary>Seconds after the last grip breaks during which nobody can grab.</summary>
	[Property, Group( "Grips" )] public float FreeSeconds { get; set; } = 2f;
	/// <summary>After one hand lands, nobody else gets a grip for this long.</summary>
	[Property, Group( "Grips" )] public float GrabBeatSeconds { get; set; } = 0.9f;

	// ---- The indignity reflex ---------------------------------------------------------------------
	/// <summary>Seconds pinned before the weapon takes matters into its own hands.</summary>
	[Property, Group( "Indignity Reflex" )] public float ReflexAfter { get; set; } = 3.5f;
	/// <summary>Seconds before the reflex can go off again.</summary>
	[Property, Group( "Indignity Reflex" )] public float ReflexCooldown { get; set; } = 9f;
	/// <summary>Seconds after the reflex during which nobody can grab.</summary>
	[Property, Group( "Indignity Reflex" )] public float ReflexGrace { get; set; } = 3.5f;

	public ReptileController Player { get; set; }

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

	readonly List<Grip> _grips = new();
	GameObject[] _anchors;
	TimeSince _sinceFree = 100f;
	TimeSince _sinceGrab = 10f;
	TimeSince _sinceReflex = 100f;
	float _graceUntil;
	Vector3 _pinPosition;
	Vector3 _lastVelocity;
	float _buck;
	int _slowedBy = -1;
	/// <summary>A hand this far from the lizard is not holding anything: the grip is dropped. (The giant is wider: <see cref="RampageGiant"/> raises it.)</summary>
	[Property, Group( "Grips" )] public float GripReach { get; set; } = 220f;

	/// <summary>
	/// One of the people hanging on is picked off (the giant's riders do it): the grip is broken as
	/// if shaken free, and where that person was is given back so they can be flicked away.
	/// </summary>
	public bool FlickOne( out Vector3 where )
	{
		where = default;
		if ( _grips.Count == 0 ) return false;
		var grip = _grips[_grips.Count - 1];
		_grips.RemoveAt( _grips.Count - 1 );
		if ( grip.Holder.IsValid() )
		{
			where = grip.Holder.WorldPosition;
			GripBroken?.Invoke( grip.Holder );
		}
		else if ( Player.IsValid() ) where = Player.WorldPosition;
		if ( _grips.Count == 0 ) _sinceFree = 0;
		return true;
	}

	// Where the hands hold on if the limbs cannot be found (the body's 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 lizard has been pinned without a break, in seconds.</summary>
	public float PinnedSeconds { get; private set; }
	/// <summary>0 to 1: how close the indignity reflex is to going off.</summary>
	public float ReflexCharge => Pinned ? Math.Clamp( PinnedSeconds / MathF.Max( ReflexAfter, 0.1f ), 0f, 1f ) : 0f;
	public float ShakeForce { get; private set; }
	public float ForceNeeded => BreakForce * (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 reflex goes off, with where the lizard is. The populace does the throwing.</summary>
	public event Action<Vector3> Reflex;

	// ---- ICrowdHost: the town as the crowd asks for it ------------------------------------------
	public CrowdPhase CrowdPhase => Rampage.Running ? CrowdPhase.Chasing : CrowdPhase.Over;
	public float ShiftProgress => 1f;
	public Vector3 Focus => PopulaceMap.Centre;
	public float GroundHeight( Vector3 point ) => PopulaceMap.GroundAt( point );
	public bool InExit( Vector3 point ) => false;   // nobody leaves town: they come back for more

	/// <summary>The way out for somebody running: the street point that takes them furthest from the lizard.</summary>
	public Vector3 ExitRoute( Vector3 from ) =>
		PopulaceMap.EscapePoint( from, Player.IsValid() ? Player.WorldPosition : PopulaceMap.Centre );

	/// <summary>Somewhere to run about to: a spot round the lizard, but not too near.</summary>
	public Vector3 WanderPoint()
	{
		var about = Player.IsValid() ? Player.WorldPosition : PopulaceMap.Centre;
		float angle = Game.Random.Float( 0f, MathF.PI * 2f );
		return PopulaceMap.Contain( about + new Vector3( MathF.Cos( angle ), MathF.Sin( angle ), 0f ) * Game.Random.Float( 900f, 1800f ) );
	}

	public Vector3 Contain( Vector3 p ) => PopulaceMap.Contain( p );

	public bool TryGrab( GameObject holder, out GameObject anchor )
	{
		anchor = null;
		if ( !Rampage.Running || !Rampage.Started || Slippery || !Player.IsValid() || !holder.IsValid() || _anchors is null ) return false;
		if ( _sinceGrab < GrabBeatSeconds ) 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];
		_sinceGrab = 0f;

		if ( _grips.Count == 1 ) PopulaceFx.Sound( "grab", Player.WorldPosition );
		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 ) _sinceFree = 0;
	}

	/// <summary>Everybody holding the lizard is thrown off at once.</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 ) _sinceFree = 0;
		FreePlayer();
	}

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

	/// <summary>Takes the lizard 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[ReptileBody.GrabbableLimbs.Length];
		for ( int i = 0; i < _anchors.Length; i++ )
		{
			var go = new GameObject( GameObject, true, "Grip Anchor " + ReptileBody.GrabbableLimbs[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 limb

			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 is hanging on.
		if ( Held && Input.Pressed( "Jump" ) ) _buck = MathF.Min( _buck + BuckForce, BuckForce * 2f );
	}

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

		// The anchors ride on the limbs (or round the body, if the limbs cannot be found).
		var at = Player.WorldPosition;
		var turn = Rotation.FromYaw( Player.WorldRotation.Angles().yaw );
		var rig = Player.Rig;
		for ( int i = 0; i < _anchors.Length; i++ )
		{
			if ( !_anchors[i].IsValid() ) continue;
			if ( rig.IsValid() && rig.TryLimbTip( ReptileBody.GrabbableLimbs[i], out var tip ) ) _anchors[i].WorldPosition = tip;
			else _anchors[i].WorldPosition = at + turn * AnchorOffsets[i % AnchorOffsets.Length];
		}

		// The force of the thrashing, as in the stadium: only the player's own doing counts.
		var velocity = Player.Velocity;
		bool steering = Input.AnalogMove.Length > 0.1f && !Player.InputLocked;
		float thrash = steering ? MathF.Min( (velocity - _lastVelocity).Length / dt, BreakForce * 0.6f ) : 0f;
		float force = thrash + 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 ( !Rampage.Running )
		{
			if ( _grips.Count > 0 ) ReleaseAll();
			PinnedSeconds = 0f;
			return;
		}

		// Holders that are gone let go, and so does anybody who has been knocked clear of the lizard
		// with the grip still on the books: nothing can hold it from across the street.
		for ( int i = _grips.Count - 1; i >= 0; i-- )
		{
			var holder = _grips[i].Holder;
			if ( holder.IsValid() && (holder.WorldPosition - at).LengthSquared < GripReach * GripReach ) continue;
			_grips.RemoveAt( i );
			if ( holder.IsValid() ) GripBroken?.Invoke( holder );
			if ( _grips.Count == 0 ) _sinceFree = 0;
		}

		// One grip at a time takes the strain; 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 ) _sinceFree = 0;
			}
		}

		// Dragging people about is slow, and a pile holds the lizard to the spot. For a while.
		if ( _slowedBy != _grips.Count )
		{
			_slowedBy = _grips.Count;
			Player.SetSpeedFactor( "grips", 1f / (1f + SlowPerGrip * _grips.Count) );
		}
		Player.Leash = Pinned ? _pinPosition : null;
		Player.ClearView = Held;
		PinnedSeconds = Pinned ? PinnedSeconds + dt : MathF.Max( PinnedSeconds - dt * 2f, 0f );

		if ( Pinned && PinnedSeconds >= ReflexAfter && _sinceReflex >= ReflexCooldown ) IndignityReflex();
	}

	/// <summary>
	/// Enough. The weapon thrashes on its own, everyone with a hand on the lizard is flung off, and
	/// nobody can take hold again for a moment.
	/// </summary>
	void IndignityReflex()
	{
		_sinceReflex = 0f;
		var at = Player.WorldPosition;
		ReleaseAll();
		Grace( ReflexGrace );
		Player.Kick( Vector3.Up * 14f );
		Reflex?.Invoke( at );
	}

	void FreePlayer()
	{
		_slowedBy = -1;
		if ( !Player.IsValid() ) return;
		Player.Leash = null;
		Player.SetSpeedFactor( "grips", 1f );
		Player.ClearView = false;
	}

	/// <summary>Switched off with hands still on the lizard: they all let go, and it is free.</summary>
	protected override void OnDisabled()
	{
		if ( _grips.Count > 0 ) ReleaseAll();
		else FreePlayer();
	}

	protected override void OnDestroy()
	{
		if ( ReferenceEquals( CrowdHosts.Fallback, this ) ) CrowdHosts.Fallback = null;
		_grips.Clear();
		FreePlayer();
	}
}