Rampage/Giant/GiantRiders.cs

Component that builds and drives the crew of misfits riding the giant. Each rider is a MisfitBody held to a rig bone by a spring, reacts to weapon events, footfalls and score events, says lines through Rampage.RiderSay, can be knocked off and scooped back, and contributes a small passive bonus tied to its body plan.

using System;
using System.Collections.Generic;

/// <summary>
/// The healed misfits ride the giant. Every healed one (and, if fewer than six are healed, others
/// from the Sump to make the crew up to six) is physically on him: on the head and shoulders,
/// clinging to the arms, the back and the tail, now and then carried in a hand, and one riding
/// the root of the weapon like a mechanical bull.
///
/// Each rider is a cheap self-animating <see cref="MisfitBody"/> on a spring to a bone of the rig
/// (found the way <see cref="GraftSocket"/> finds one, with its fixed points as the fallback). The
/// spring is the secondary motion: a rider lags, swings out on a turn, bounces on a footfall, is
/// flung to arm's length by a big swing and hauls itself back. A thin arm shows it holding on.
///
/// They react to what happens: they cheer when a building falls, duck under a slam, hang on and
/// shriek through a charge, point at the place their own story happened and shout when it is
/// hit, flinch from what they fear, heckle the humans and flick climbers off the giant's ankles.
/// Their talk goes through <see cref="Rampage.RiderSay"/> (speaker and line, with their speech
/// tics), with gaps, so it is seasoning. A big enough hit to the giant knocks one off; it runs
/// along behind at his feet until it is scooped back up. Each also gives a small passive help
/// while it is riding, by its kind of body (see the static rates below).
/// </summary>
[Title( "Giant Riders" ), Category( "Rampage" ), Icon( "groups" )]
public sealed class GiantRiders : Component
{
	public static GiantRiders Current { get; private set; }

	// ---- What the riders give, for the weapon and the giant (1 with no crew) ----

	/// <summary>How much faster the mega-swing charges (a Machine aboard).</summary>
	public static float ChargeRate => Current.IsValid() ? Current._chargeRate : 1f;
	/// <summary>How much faster the slingshot draws (a Jelly aboard).</summary>
	public static float DrawRate => Current.IsValid() ? Current._drawRate : 1f;
	/// <summary>How much longer the helicopter hovers (a Gas Sac aboard).</summary>
	public static float HoverBonus => Current.IsValid() ? Current._hoverBonus : 1f;
	/// <summary>How much wider the giant's own shockwaves are (a Fungus aboard).</summary>
	public static float ShockBonus => Current.IsValid() ? Current._shockBonus : 1f;

	/// <summary>The crew is made up to this many if fewer are healed.</summary>
	[Property, Group( "Crew" )] public int CrewAtLeast { get; set; } = 6;
	/// <summary>Size of a rider's body next to its size in the Sump (it grows a little as the giant does).</summary>
	[Property, Group( "Crew" )] public float RiderScale { get; set; } = 1.5f;

	/// <summary>The spring that holds a rider to its place, and how quickly its swinging dies away. Soft and under-damped: they are not glued on.</summary>
	[Property, Group( "Motion" )] public float Spring { get; set; } = 190f;
	[Property, Group( "Motion" )] public float Damping { get; set; } = 8f;
	/// <summary>Arm's length: the furthest a rider can be thrown from its place, in inches at the lizard's ordinary size.</summary>
	[Property, Group( "Motion" )] public float ArmLength { get; set; } = 5.5f;
	/// <summary>How hard a footfall bounces them, in inches a second per unit of the giant's size.</summary>
	[Property, Group( "Motion" )] public float FootBounce { get; set; } = 20f;

	/// <summary>Seconds of quiet after any ordinary line, and how long a line stays up.</summary>
	[Property, Group( "Talk" )] public float QuietSeconds { get; set; } = 4.5f;
	[Property, Group( "Talk" )] public float LineSeconds { get; set; } = 3.4f;
	/// <summary>Seconds between heckles, and between idle remarks when nothing is happening.</summary>
	[Property, Group( "Talk" )] public float HeckleEvery { get; set; } = 16f;
	[Property, Group( "Talk" )] public float IdleEvery { get; set; } = 38f;

	/// <summary>Seconds a knocked-off rider runs behind before it is scooped back up.</summary>
	[Property, Group( "Knocks" )] public float ScoopSeconds { get; set; } = 7f;
	/// <summary>Seconds between climbers being flicked off the giant's ankles (half that with a Swarm aboard).</summary>
	[Property, Group( "Knocks" )] public float FlickSeconds { get; set; } = 2.4f;

	/// <summary>One of the crew.</summary>
	public sealed class Rider
	{
		public MisfitProfile Profile;
		public string Name = "";
		public string Passive = "";
		public GameObject Object, Arm;
		public MisfitBody Body;
		public int Slot;
		public Vector3 Position, Velocity, LastAnchor;
		public bool Placed;
		/// <summary>Knocked off and running behind until this time.</summary>
		public bool Fallen;
		public float FallenUntil, FreeUntil;
		public float CheerUntil, DuckUntil, PointUntil, HandUntil, NextHand, NextFear, NextPoint;
		public Vector3 PointAt;
		/// <summary>The landmark its own story happened at (an index into the town's list), or -1; and whether that has been dealt with.</summary>
		public int Landmark = -1;
		public bool LandmarkDone;
		public float Height = 40f;
	}

	/// <summary>Where on the giant a rider sits: a bone, an offset in the giant's own frame (inches at the lizard's ordinary size), and the bone of the hand it is sometimes carried in.</summary>
	static readonly (string Bone, Vector3 Offset, string Hand)[] Slots =
	{
		("weapon", new( 0f, 0f, 2.5f ), null),            // the mechanical bull
		("head", new( 0f, 0f, 6f ), null),
		("arm_upper_l", new( 0f, 1.5f, 4f ), null),       // the shoulders
		("arm_upper_r", new( 0f, -1.5f, 4f ), null),
		("spine_2", new( -4f, 0f, 6f ), null),            // between the shoulder blades
		("tail_1", new( 0f, 0f, 4f ), null),
		("arm_lower_l", new( 0f, 3f, 0f ), "hand_l"),     // clinging to the arms
		("arm_lower_r", new( 0f, -3f, 0f ), "hand_r"),
		("tail_3", new( 0f, 0f, 3.5f ), null),
		("spine_0", new( -5f, 0f, 5f ), null),            // the back spines
	};

	/// <summary>How many times somebody has been knocked off this run.</summary>
	public int Falls { get; private set; }

	readonly List<Rider> _crew = new();
	public IReadOnlyList<Rider> Crew => _crew;
	/// <summary>How many of the crew are on the giant right now (not running behind).</summary>
	public int Riding { get; private set; }

	ReptileController _player;
	GameObject _root;
	bool _built, _listening;
	DongWeapon _weaponHeard;
	RampageGiant _giantHeard;

	float _chargeRate = 1f, _drawRate = 1f, _hoverBonus = 1f, _shockBonus = 1f;
	bool _lookout, _spotter, _pest;
	bool _fatCalled, _chopperCalled;
	float _nextThink, _nextHeckle, _nextIdle, _nextFlick, _nextSpot, _loudAt = -100f, _flashAt = -100f, _airSince;
	float _hangOn;     // 0 to 1: a charge is on, everybody is holding tight and shaking

	protected override void OnStart()
	{
		if ( Scene.IsEditor ) return;
		Current = this;
	}

	protected override void OnEnabled()
	{
		if ( Scene.IsEditor || _listening ) return;
		Rampage.Scored += OnScored;
		Rampage.TierUp += OnTierUp;
		Rampage.Shockwave += OnShockwave;
		_listening = true;
	}

	protected override void OnDisabled()
	{
		if ( _listening )
		{
			Rampage.Scored -= OnScored;
			Rampage.TierUp -= OnTierUp;
			Rampage.Shockwave -= OnShockwave;
			_listening = false;
		}
		Scrap();
	}

	protected override void OnDestroy()
	{
		Scrap();
		if ( Current == this ) Current = null;
	}

	/// <summary>The bodies are cleared away (their primitives go back to the misfits' pool).</summary>
	void Scrap()
	{
		if ( _root.IsValid() ) _root.Destroy();
		_root = null;
		_crew.Clear();
		_built = false;
		Riding = 0;
		_chargeRate = _drawRate = _hoverBonus = _shockBonus = 1f;
	}

	// ---- The crew ---------------------------------------------------------------------------------

	/// <summary>Everybody healed, then others to make the number up; each given a place, a body and a passive.</summary>
	void Build()
	{
		_built = true;
		_crew.Clear();
		SumpState.EnsureStarted();

		var misfits = SumpState.Misfits;
		if ( misfits is null ) return;
		for ( int pass = 0; pass < 2; pass++ )
		{
			for ( int i = 0; i < misfits.Count && _crew.Count < Slots.Length; i++ )
			{
				var profile = misfits[i];
				if ( profile is null ) continue;
				// First the healed; then, if that is not a crew, whoever else there is.
				if ( pass == 0 ? !profile.Healed : (profile.Healed || _crew.Count >= CrewAtLeast) ) continue;
				_crew.Add( new Rider { Profile = profile, Slot = _crew.Count } );
			}
		}
		if ( _crew.Count == 0 ) return;

		_root = new GameObject( true, "Giant Riders" );
		_root.Flags |= GameObjectFlags.NotSaved;
		float now = Time.Now;
		for ( int i = 0; i < _crew.Count; i++ )
		{
			var rider = _crew[i];
			try
			{
				string name = MisfitVoice.ShortName( rider.Profile );
				rider.Name = string.IsNullOrWhiteSpace( name ) ? "SOMEBODY" : name.ToUpperInvariant();
				rider.Passive = RiderLines.Passive( rider.Profile.Plan );

				rider.Object = new GameObject( _root, true, "Rider " + rider.Name );
				rider.Object.Flags |= GameObjectFlags.NotSaved;
				rider.Body = MisfitBody.Create( rider.Object, rider.Profile, RiderScale );
				if ( rider.Body.IsValid() )
				{
					// The camera is a long way back from a giant: they are never "far" or asleep.
					rider.Body.FarDistance = 9000f;
					rider.Body.SleepDistance = 20000f;
					rider.Height = MathF.Max( rider.Body.Top.z - rider.Object.WorldPosition.z, 12f );
				}
				rider.Arm = PopulaceFx.Block( _root, "Rider Arm", Vector3.Zero, new Vector3( 4f ), rider.Profile.Primary );
				rider.Arm.Enabled = false;
			}
			catch ( Exception e ) { Log.Warning( $"Rider not built: {e.Message}" ); }

			rider.NextHand = now + 14f + i * 5f;
			rider.NextFear = now + 20f + i * 3f;
			rider.NextPoint = now + 8f + i * 4f;
		}
		_nextHeckle = now + 12f;
		_nextIdle = now + IdleEvery;
		_nextSpot = now + 25f;
		FindLandmarks();
		Say( Pick(), RiderLines.Start );
	}

	/// <summary>Which place in town each rider's own story happened at.</summary>
	void FindLandmarks()
	{
		var names = RampageWorld.LandmarkNames;
		for ( int r = 0; r < _crew.Count; r++ )
		{
			var rider = _crew[r];
			string want = rider.Profile.Contact switch
			{
				FirstContact.ShotOnFarm => "FARM",
				FirstContact.Dissected => "LAB",
				FirstContact.BecameMeme => "TV",
				FirstContact.WorshippedThenSold => "CHURCH",
				_ => "HOME",
			};
			rider.Landmark = -1;
			for ( int i = 0; i < names.Count; i++ )
				if ( names[i] is not null && names[i].Contains( want, StringComparison.OrdinalIgnoreCase ) ) { rider.Landmark = i; break; }
		}
	}

	/// <summary>The small helps, from whoever is riding now.</summary>
	void CountPassives()
	{
		_chargeRate = _drawRate = _hoverBonus = _shockBonus = 1f;
		_lookout = _spotter = _pest = false;
		int riding = 0;
		for ( int i = 0; i < _crew.Count; i++ )
		{
			var rider = _crew[i];
			if ( rider.Fallen ) continue;
			riding++;
			switch ( rider.Profile.Plan )
			{
				case BodyPlan.Machine: _chargeRate = 1.25f; break;
				case BodyPlan.Jelly: _drawRate = 1.3f; break;
				case BodyPlan.GasSac: _hoverBonus = 1.4f; break;
				case BodyPlan.Fungus: _shockBonus = 1.1f; break;
				case BodyPlan.CrystalLattice: _lookout = true; break;
				case BodyPlan.Insectoid: _spotter = true; break;
				case BodyPlan.Swarm: _pest = true; break;
			}
		}
		Riding = riding;
	}

	// ---- Every frame ------------------------------------------------------------------------------

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor ) return;
		Current = this;
		if ( !Rampage.Running ) { if ( _built ) Scrap(); return; }
		if ( !_player.IsValid() ) _player = Components.Get<ReptileController>() ?? Rampage.Player;
		if ( !_player.IsValid() ) return;

		// They climb aboard when the giant comes up out of the square.
		if ( !_built )
		{
			if ( !Rampage.Started || !RampageWorld.Ready ) return;
			Build();
		}
		// A hotload can take the bodies and leave the list: then they are all made again.
		if ( _crew.Count > 0 && !_root.IsValid() ) { Scrap(); return; }

		Listen();
		float dt = MathF.Min( Time.Delta, 0.05f );
		if ( dt <= 0f ) return;
		float now = Time.Now;
		float size = MathF.Max( RampageGiant.ScaleNow, 1f );
		var rig = _player.Rig;
		var frame = Rotation.FromYaw( _player.WorldRotation.Yaw() );
		float agitation = Math.Clamp( 0.12f + Rampage.Terror * 0.45f + Rampage.Tier * 0.07f, 0f, 1f );

		var weapon = DongWeapon.Current;
		_hangOn += ((weapon.IsValid() && weapon.Charge01 > 0.02f ? 1f : 0f) - _hangOn) * MathF.Min( dt * 6f, 1f );
		_airSince = _player.Attached ? 0f : _airSince + dt;

		for ( int i = 0; i < _crew.Count; i++ )
		{
			var rider = _crew[i];
			if ( !rider.Object.IsValid() ) continue;
			if ( rider.Fallen ) RunBehind( rider, i, dt, now, size, frame );
			else Ride( rider, rig, dt, now, size, frame );
			if ( rider.Body.IsValid() ) rider.Body.Agitation = Math.Clamp( agitation + _hangOn * 0.5f + (now < rider.DuckUntil ? 0.3f : 0f), 0f, 1f );
		}

		if ( now >= _nextThink )
		{
			_nextThink = now + 0.5f;
			Think( now, size );
		}
	}

	/// <summary>The weapon and the giant forget who was listening when they are put away: they are asked again.</summary>
	void Listen()
	{
		var weapon = DongWeapon.Current;
		if ( weapon != _weaponHeard )
		{
			_weaponHeard = weapon;
			if ( weapon.IsValid() ) { weapon.Did -= OnDid; weapon.Did += OnDid; }
		}
		var giant = RampageGiant.Current;
		if ( giant != _giantHeard )
		{
			_giantHeard = giant;
			if ( giant.IsValid() )
			{
				giant.Footfall -= OnFootfall; giant.Footfall += OnFootfall;
				giant.Landed -= OnLanded; giant.Landed += OnLanded;
			}
		}
	}

	/// <summary>Where a rider's place is in the world right now.</summary>
	Vector3 Anchor( Rider rider, LizardRig rig, float now, float size, Rotation frame )
	{
		var slot = Slots[Math.Clamp( rider.Slot, 0, Slots.Length - 1 )];
		string bone = slot.Hand is not null && now < rider.HandUntil ? slot.Hand : slot.Bone;
		var offset = frame * (slot.Offset * size);

		if ( bone == "weapon" )
		{
			if ( rig.IsValid() && rig.WeaponMode ) return rig.DongRoot + offset;
			bone = "pelvis";
		}
		if ( rig.IsValid() && rig.TryBonePosition( bone, out var at ) ) return at + offset;

		// No such bone to follow: the fixed point for it on the old body, at the giant's size.
		var basis = _player.WorldRotation;
		return _player.WorldPosition + basis * (GraftSocket.FallbackPoint( bone ) * size) + offset;
	}

	void Ride( Rider rider, LizardRig rig, float dt, float now, float size, Rotation frame )
	{
		var anchor = Anchor( rider, rig, now, size, frame );
		if ( !rider.Placed || (rider.Position - anchor).Length > size * 80f )
		{
			rider.Placed = true;
			rider.Position = anchor;
			rider.Velocity = Vector3.Zero;
			rider.LastAnchor = anchor;
		}

		// The spring. Its damping is against the place it is holding on to, not against the world,
		// so a rider keeps up with a walking giant and only lags when he starts, stops, turns or jolts.
		var carried = (anchor - rider.LastAnchor) / dt;
		rider.LastAnchor = anchor;
		float grip = 1f + _hangOn * 1.5f;      // holding tight through a charge
		rider.Velocity += ((anchor - rider.Position) * (Spring * grip) - (rider.Velocity - carried) * (Damping * grip)) * dt;
		rider.Position += rider.Velocity * dt;

		// Arm's length: flung that far and no further, and hauled back from there.
		var away = rider.Position - anchor;
		float most = ArmLength * size;
		float out_ = away.Length;
		if ( out_ > most && now >= rider.FreeUntil )
		{
			var direction = away / out_;
			rider.Position = anchor + direction * most;
			float leaving = Vector3.Dot( rider.Velocity - carried, direction );
			if ( leaving > 0f ) rider.Velocity -= direction * leaving;
			out_ = most;
		}

		// Now and then the ones on the arms are carried in a hand for a while.
		var slot = Slots[Math.Clamp( rider.Slot, 0, Slots.Length - 1 )];
		if ( slot.Hand is not null && now >= rider.NextHand )
		{
			rider.HandUntil = now + 7f;
			rider.NextHand = now + Game.Random.Float( 22f, 36f );
		}

		// Shown: bouncing when it cheers, flattened when it ducks, shaking through a charge, leaning the way it has swung.
		var shown = rider.Position;
		if ( now < rider.CheerUntil ) shown += Vector3.Up * (MathF.Abs( MathF.Sin( now * 11f + rider.Slot ) ) * size * 1.6f);
		if ( _hangOn > 0.05f ) shown += Vector3.Random * (_hangOn * size * 0.25f);

		float yaw = _player.WorldRotation.Yaw();
		if ( now < rider.PointUntil )
		{
			var to = rider.PointAt - rider.Position;
			if ( to.WithZ( 0f ).Length > 1f ) yaw = MathF.Atan2( to.y, to.x ) * (180f / MathF.PI);
		}
		var local = frame.Inverse * away;
		float lean = 40f / MathF.Max( most, 1f );
		var turn = Rotation.FromYaw( yaw ) * Rotation.From( Math.Clamp( -local.x * lean, -45f, 45f ), 0f, Math.Clamp( local.y * lean, -45f, 45f ) );

		rider.Object.WorldPosition = shown;
		rider.Object.WorldRotation = turn;
		rider.Object.WorldScale = now < rider.DuckUntil ? new Vector3( 1.15f, 1.15f, 0.55f ) : Vector3.One;
		if ( rider.Body.IsValid() ) rider.Body.MoveSpeed = 0f;
		ShowArm( rider, shown + Vector3.Up * (rider.Height * 0.5f), anchor, out_ > size * 0.6f );
	}

	/// <summary>The arm: a thin box from the rider to what it is holding on to, drawn once it has swung clear.</summary>
	static void ShowArm( Rider rider, Vector3 from, Vector3 to, bool show )
	{
		if ( !rider.Arm.IsValid() ) return;
		var span = to - from;
		float length = span.Length;
		if ( !show || length < 2f ) { rider.Arm.Enabled = false; return; }
		rider.Arm.Enabled = true;
		rider.Arm.WorldPosition = (from + to) * 0.5f;
		rider.Arm.WorldRotation = Rotation.LookAt( span / length );
		rider.Arm.WorldScale = new Vector3( length, 3f, 3f ) / 50f;
	}

	/// <summary>Knocked off: it runs along behind the giant's heels, keeping up, until it is scooped back onto its place.</summary>
	void RunBehind( Rider rider, int index, float dt, float now, float size, Rotation frame )
	{
		float radius = _player.Radius;
		var feet = _player.WorldPosition;
		var want = feet + frame * new Vector3( -radius * 2.4f, (index - _crew.Count * 0.5f) * radius * 0.45f, 0f );
		want = want.WithZ( RampageWorld.GroundHeightAt( want ) );

		// It falls to the road first, then legs it.
		var position = rider.Position;
		float ground = RampageWorld.GroundHeightAt( position );
		if ( position.z > ground + 1f )
		{
			rider.Velocity += Vector3.Down * (900f * dt);
			position += rider.Velocity * dt;
			if ( position.z <= ground ) { position = position.WithZ( ground ); rider.Velocity = Vector3.Zero; }
		}
		else
		{
			var to = (want - position).WithZ( 0f );
			float pace = MathF.Max( _player.Velocity.WithZ( 0f ).Length * 1.08f, 260f );
			float step = MathF.Min( pace * dt, to.Length );
			if ( to.Length > 1f ) position += to.Normal * step;
			position = position.WithZ( ground );
			if ( rider.Body.IsValid() ) rider.Body.MoveSpeed = step / dt;
			if ( to.Length > 4f ) rider.Object.WorldRotation = Rotation.FromYaw( MathF.Atan2( to.y, to.x ) * (180f / MathF.PI) );
		}
		rider.Position = position;
		rider.Object.WorldPosition = position;
		rider.Object.WorldScale = Vector3.One;
		if ( rider.Arm.IsValid() ) rider.Arm.Enabled = false;

		if ( now < rider.FallenUntil ) return;

		// Scooped up: thrown at its place, and the spring does the rest.
		rider.Fallen = false;
		rider.FreeUntil = now + 0.9f;
		rider.Velocity = Vector3.Up * (size * 110f) + _player.Velocity;
		rider.LastAnchor = position;
		CountPassives();
		Say( rider, RiderLines.Scooped );
	}

	// ---- What they notice -----------------------------------------------------------------------

	/// <summary>Twice a second: who points, who is frightened, who heckles, who flicks a climber off.</summary>
	void Think( float now, float size )
	{
		CountPassives();
		var at = _player.WorldPosition;
		var landmarks = RampageWorld.Landmarks;

		for ( int i = 0; i < _crew.Count; i++ )
		{
			var rider = _crew[i];
			if ( rider.Fallen ) continue;

			// The place its own story happened: pointed at when it comes into view.
			if ( rider.Landmark >= 0 && rider.Landmark < landmarks.Count && !rider.LandmarkDone && now >= rider.NextPoint
				&& (landmarks[rider.Landmark] - at).WithZ( 0f ).Length < 5200f )
			{
				rider.NextPoint = now + 45f;
				if ( Say( rider, RiderLines.Point( rider.Profile.Contact ), true ) )
				{
					rider.PointUntil = now + 3f;
					rider.PointAt = landmarks[rider.Landmark];
				}
			}

			// What it cannot bear.
			if ( now >= rider.NextFear && Frightened( rider.Profile.FearKind, now ) )
			{
				rider.NextFear = now + 55f;
				if ( rider.Body.IsValid() ) rider.Body.Flinch();
				rider.DuckUntil = now + 1.2f;
				Say( rider, RiderLines.Fear( rider.Profile.FearKind ) );
			}
		}

		// Climbers: the brave ones on the giant's ankles are picked off one at a time.
		var populace = RampagePopulace.Current;
		if ( populace.IsValid() && populace.Grips.IsValid() && populace.Grips.Grabbers > 0 && now >= _nextFlick && Riding > 0 )
		{
			_nextFlick = now + FlickSeconds * (_pest ? 0.5f : 1f);
			if ( populace.Grips.FlickOne( out var where ) ) Flick( where, size );
		}

		// The Fat Guy, called out once by whoever has the eyes for it.
		if ( _spotter && !_fatCalled && populace.IsValid() && populace.TheFatGuy.IsValid()
			&& (populace.TheFatGuy.WorldPosition - at).WithZ( 0f ).Length < 4500f )
		{
			_fatCalled = Say( WithPlan( BodyPlan.Insectoid ), RiderLines.FatGuy );
		}

		if ( !_chopperCalled && GiantFoes.ChoppersUp > 0 ) _chopperCalled = Say( Pick(), RiderLines.Chopper );

		// The lookout calls the nearest place that is still worth a visit.
		if ( _lookout && now >= _nextSpot )
		{
			_nextSpot = now + 50f;
			CallLandmark( at );
		}

		if ( now >= _nextHeckle && RampagePopulace.Fleeing > 12 )
		{
			_nextHeckle = now + HeckleEvery;
			Say( Pick(), RiderLines.Heckle );
		}
		if ( now >= _nextIdle )
		{
			_nextIdle = now + IdleEvery;
			Say( Pick(), RiderLines.Idle );
		}
	}

	bool Frightened( string kind, float now ) => kind switch
	{
		"light" => now - _flashAt < 1.5f,
		"noise" => now - _loudAt < 1.5f,
		"touch" => RampagePopulace.Grabbers > 0,
		"crowds" => RampagePopulace.Fleeing > 70 || RampagePopulace.Grabbers > 1,
		"open" => _airSince > 0.6f,
		_ => GiantFoes.ChoppersUp > 0,
	};

	/// <summary>A climber, picked off an ankle and sent on its way.</summary>
	void Flick( Vector3 where, float size )
	{
		var near = Rampage.Borrow();
		Rampage.TargetsNear( where, 50f, near );
		var away = (where - _player.WorldPosition).WithZ( 0f );
		var direction = away.Length > 1f ? away.Normal : Vector3.Random.WithZ( 0f ).Normal;
		for ( int i = 0; i < near.Count; i++ )
		{
			var target = near[i];
			if ( target is Building || target is Toppler || target.Radius > 120f ) continue;
			target.Hit( direction * 900f + Vector3.Up * 1400f, 0f, where );
		}
		Rampage.Return( near );
		Rampage.PlaySound( "rider_flick", where );
		Say( _pest ? WithPlan( BodyPlan.Swarm ) : Pick(), RiderLines.Climber );
	}

	/// <summary>"THE LAB. A LONG WAY, LEFT." from the lookout, about the nearest landmark that is not the square.</summary>
	void CallLandmark( Vector3 at )
	{
		var landmarks = RampageWorld.Landmarks;
		var names = RampageWorld.LandmarkNames;
		int best = -1;
		float nearest = float.MaxValue;
		for ( int i = 0; i < landmarks.Count && i < names.Count; i++ )
		{
			float d = (landmarks[i] - at).WithZ( 0f ).Length;
			if ( d < 900f || d >= nearest ) continue;
			nearest = d;
			best = i;
		}
		if ( best < 0 ) return;

		var to = (landmarks[best] - at).WithZ( 0f ).Normal;
		var look = Rotation.FromYaw( _player.Look.yaw );
		float ahead = Vector3.Dot( to, look.Forward ), left = Vector3.Dot( to, look.Left );
		string way = MathF.Abs( ahead ) > MathF.Abs( left ) ? (ahead > 0f ? "DEAD AHEAD" : "BEHIND US") : (left > 0f ? "TO THE LEFT" : "TO THE RIGHT");
		string far = nearest < 2500f ? "CLOSE" : nearest < 6000f ? "A FEW STREETS" : "A LONG WAY";
		Say( WithPlan( BodyPlan.CrystalLattice ), $"{names[best]}. {far}, {way}. STILL SMUG. FIX THAT." );
	}

	// ---- Things that happen to them ---------------------------------------------------------------

	void OnFootfall( Vector3 at, int foot )
	{
		float size = MathF.Max( RampageGiant.ScaleNow, 1f );
		for ( int i = 0; i < _crew.Count; i++ )
			if ( !_crew[i].Fallen ) _crew[i].Velocity += Vector3.Up * (FootBounce * size * (0.7f + 0.3f * ((i + foot) & 1)));
	}

	void OnLanded( Vector3 at, float hard )
	{
		float size = MathF.Max( RampageGiant.ScaleNow, 1f );
		float now = Time.Now;
		for ( int i = 0; i < _crew.Count; i++ )
		{
			if ( _crew[i].Fallen ) continue;
			_crew[i].Velocity += Vector3.Down * (FootBounce * size * 3f * hard);
			_crew[i].DuckUntil = now + 0.5f;
		}
	}

	/// <summary>What the weapon just did (see <see cref="DongWeapon.Did"/>).</summary>
	void OnDid( string what, float amount )
	{
		float now = Time.Now;
		float size = MathF.Max( RampageGiant.ScaleNow, 1f );
		switch ( what )
		{
			case "crack": if ( amount > 0.8f ) Say( Pick(), RiderLines.Crack ); break;
			case "slam": DuckAll( now, 0.6f ); Say( Pick(), RiderLines.Slam ); break;
			case "charge": if ( amount < 0.5f ) Say( Pick(), RiderLines.Charge ); break;
			case "mega": Jolt( size * 70f * (0.5f + amount) ); CheerAll( now, 1.6f ); Say( Pick(), RiderLines.Mega, amount > 0.8f ); break;
			case "miss": Jolt( size * 110f ); DuckAll( now, 1.2f ); Say( Pick(), RiderLines.Miss, true ); break;
			case "spin": if ( amount > 0.5f ) Say( Pick(), RiderLines.Spin ); break;
			case "spin_release": Jolt( size * 60f * amount ); Say( Pick(), RiderLines.SpinRelease ); break;
			case "flail": Say( Pick(), RiderLines.Flail ); break;
			case "flail_bounce": Jolt( size * 50f ); Say( Pick(), RiderLines.FlailBounce ); break;
			case "sling": Say( Pick(), RiderLines.Sling ); break;
			case "sling_back": Jolt( size * 45f * (0.4f + amount) ); DuckAll( now, 0.5f ); Say( Pick(), RiderLines.SlingBack ); break;
			case "clap": CheerAll( now, 1.4f ); Say( Pick(), RiderLines.Clap ); break;
			case "pound":
			case "sitdown": DuckAll( now, 0.7f ); Say( Pick(), RiderLines.Crater ); break;
			case "hook": Say( Pick(), RiderLines.Hook ); break;
			case "fling": Say( Pick(), RiderLines.Fling ); break;
			case "tear": Say( Pick(), RiderLines.Tear ); break;
		}
	}

	void OnScored( Vector3 at, float points, string label )
	{
		if ( !_built || points < 150f ) return;
		float now = Time.Now;
		var landmarks = RampageWorld.Landmarks;

		// Somebody's own landmark, hit: that one shouts, whatever else is being said.
		for ( int i = 0; i < _crew.Count; i++ )
		{
			var rider = _crew[i];
			if ( rider.Landmark < 0 || rider.Landmark >= landmarks.Count || rider.LandmarkDone ) continue;
			if ( (landmarks[rider.Landmark] - at).WithZ( 0f ).Length > 1100f ) continue;
			rider.LandmarkDone = true;
			rider.CheerUntil = now + 3f;
			Say( rider, RiderLines.Revenge( rider.Profile.Contact ), true );
			return;
		}

		// A building down: everybody cheers.
		if ( points < 300f ) return;
		CheerAll( now, 1.5f );
		Say( Pick(), RiderLines.BuildingFell );
	}

	void OnTierUp( int tier )
	{
		if ( !_built ) return;
		Jolt( MathF.Max( RampageGiant.ScaleNow, 1f ) * 40f );
		Say( Pick(), RiderLines.TierUp );
	}

	void OnShockwave( Vector3 centre, float radius, float speed )
	{
		if ( !_built || !_player.IsValid() ) return;
		if ( radius < 700f || (centre - _player.WorldPosition).Length > radius + 1500f ) return;
		_loudAt = Time.Now;
		if ( speed >= 900f ) _flashAt = Time.Now;
	}

	/// <summary>
	/// A big enough hit to the giant (a tank's shell, a helicopter's shot): one rider is knocked off
	/// and runs behind until it is scooped up. Never the last one aboard.
	/// </summary>
	public void Knock( Vector3 from )
	{
		if ( !_built || Riding <= 1 ) return;
		int start = Game.Random.Next( 0, Math.Max( _crew.Count, 1 ) );
		for ( int n = 0; n < _crew.Count; n++ )
		{
			var rider = _crew[(start + n) % _crew.Count];
			if ( rider.Fallen || !rider.Object.IsValid() ) continue;

			float now = Time.Now;
			var away = (rider.Position - from).WithZ( 0f );
			rider.Fallen = true;
			rider.FallenUntil = now + ScoopSeconds;
			rider.Velocity = (away.Length > 1f ? away.Normal : Vector3.Random.WithZ( 0f ).Normal) * 400f + Vector3.Up * 300f;
			rider.HandUntil = 0f;
			Falls++;
			CountPassives();
			Rampage.PlaySound( "rider_knocked", rider.Position );
			Say( rider, RiderLines.KnockedOff, true );
			return;
		}
	}

	/// <summary>Everybody is thrown about by this much (inches a second), each their own way.</summary>
	void Jolt( float speed )
	{
		for ( int i = 0; i < _crew.Count; i++ )
			if ( !_crew[i].Fallen ) _crew[i].Velocity += (Vector3.Random + Vector3.Up * 0.5f) * speed;
	}

	void CheerAll( float now, float seconds )
	{
		for ( int i = 0; i < _crew.Count; i++ ) _crew[i].CheerUntil = now + seconds;
	}

	void DuckAll( float now, float seconds )
	{
		for ( int i = 0; i < _crew.Count; i++ ) _crew[i].DuckUntil = now + seconds;
	}

	// ---- Talk ---------------------------------------------------------------------------------------

	/// <summary>Somebody who is riding, at random (null with nobody aboard).</summary>
	Rider Pick()
	{
		if ( _crew.Count == 0 ) return null;
		int start = Game.Random.Next( 0, _crew.Count );
		for ( int n = 0; n < _crew.Count; n++ )
		{
			var rider = _crew[(start + n) % _crew.Count];
			if ( !rider.Fallen ) return rider;
		}
		return _crew[start];
	}

	/// <summary>The rider with this kind of body, or failing that anybody.</summary>
	Rider WithPlan( BodyPlan plan )
	{
		for ( int i = 0; i < _crew.Count; i++ )
			if ( !_crew[i].Fallen && _crew[i].Profile.Plan == plan ) return _crew[i];
		return Pick();
	}

	bool Say( Rider rider, string[] lines, bool urgent = false )
	{
		if ( lines is null || lines.Length == 0 ) return false;
		return Say( rider, lines[Game.Random.Next( 0, lines.Length )], urgent );
	}

	/// <summary>One line, the way this rider says things. False if somebody else was still talking.</summary>
	bool Say( Rider rider, string line, bool urgent = false )
	{
		if ( rider is null || string.IsNullOrEmpty( line ) ) return false;
		string spoken;
		try { spoken = MisfitVoice.Speak( rider.Profile, line ); }
		catch ( Exception ) { spoken = line; }
		return Rampage.RiderSay( rider.Name, spoken, LineSeconds, QuietSeconds, urgent );
	}
}