Story/Escort.cs

An escort NPC component from the story campaign. Walks to a formation offset behind the Envoy, snaps to ground with traces, plays boot footsteps, drives citizen animations and a swaying flashlight, and falls over when killed. Retreats to its spawn point after the envoy dies unless the player's disguise still holds.

using System;
using System.Linq;
using Sandbox.Citizen;

// The citizen model still runs on the old animgraph, which the engine marks obsolete.
#pragma warning disable CS0618

/// <summary>
/// One of the envoy's guards. Keeps its place in formation behind the envoy, carries a
/// flashlight, and can be killed. Moved by script the same way the envoy is: a step along the
/// ground each frame, then a downward trace. When the envoy dies the escorts freeze, then back
/// away to where they came in, still watching the lizard.
/// </summary>
[Title( "Escort" ), Category( "Story" ), Icon( "security" )]
public sealed class Escort : Component
{
	/// <summary>Who to follow. Left empty, the first envoy in the scene.</summary>
	[Property] public Envoy Leader { get; set; }

	/// <summary>Its place in the formation, in the envoy's frame (x forward, y left), in inches.</summary>
	[Property] public Vector3 FormationOffset { get; set; } = new( -70f, 60f, 0f );

	/// <summary>Top speed; a little faster than the envoy so it can catch up.</summary>
	[Property] public float WalkSpeed { get; set; } = 110f;

	/// <summary>Speed while backing away after the envoy has died.</summary>
	[Property] public float RetreatSpeed { get; set; } = 55f;

	/// <summary>Seconds it stands frozen after the envoy dies, before backing away.</summary>
	[Property] public float RetreatDelay { get; set; } = 1.2f;

	/// <summary>How long the fall takes when it is killed.</summary>
	[Property] public float FallSeconds { get; set; } = 0.4f;

	/// <summary>Distance walked between boot sounds, in inches.</summary>
	[Property] public float StrideLength { get; set; } = 38f;

	[Property] public string BootsSound { get; set; } = "sounds/opening/boots.sound";

	[Property, Group( "Flashlight" )] public float FlashlightIntensity { get; set; } = 25f;
	[Property, Group( "Flashlight" )] public Color FlashlightColor { get; set; } = new( 1f, 0.96f, 0.86f );
	/// <summary>Full outer cone angle, in degrees.</summary>
	[Property, Group( "Flashlight" )] public float FlashlightCone { get; set; } = 28f;
	[Property, Group( "Flashlight" )] public float FlashlightRange { get; set; } = 1800f;
	[Property, Group( "Flashlight" )] public float FlashlightFog { get; set; } = 2.5f;
	/// <summary>Where the flashlight is held, relative to the feet.</summary>
	[Property, Group( "Flashlight" )] public Vector3 FlashlightOffset { get; set; } = new( 18f, -9f, 58f );
	/// <summary>How far the hand wanders, in degrees.</summary>
	[Property, Group( "Flashlight" )] public float SwayDegrees { get; set; } = 2.5f;

	public bool IsDead { get; private set; }
	public bool IsMoving { get; private set; }

	Health _health;
	SkinnedModelRenderer _renderer;
	CitizenAnimationHelper _anim;
	GameObject _player;
	SpotLight _flashlight;

	Vector3 _home;          // where it came in; it backs away to here
	float _sinceStride;     // inches walked since the last boot sound
	float _swayPhase;
	bool _leaderDied;
	TimeSince _sinceLeaderDied;
	TimeSince _sinceDeath;
	Rotation _deathFrom;
	Rotation _deathTo;

	protected override void OnStart()
	{
		_health = Components.Get<Health>();
		_renderer = Components.Get<SkinnedModelRenderer>( FindMode.EverythingInSelfAndDescendants );
		_anim = Components.Get<CitizenAnimationHelper>( FindMode.EverythingInSelfAndDescendants );
		if ( _health is not null ) _health.Killed += OnKilled;
		if ( _health is not null ) _health.Damaged += OnDamaged;

		CoverBlown = false; // a fresh team in a fresh scene
		_home = WorldPosition;
		_swayPhase = Game.Random.Float( 0f, 10f ); // so the team's lights don't sway in step
		_sinceStride = Game.Random.Float( 0f, StrideLength );

		if ( !Scene.IsEditor ) CreateFlashlight();
	}

	protected override void OnDestroy()
	{
		if ( _health is not null ) _health.Killed -= OnKilled;
	}

	void CreateFlashlight()
	{
		// Use a spotlight that is already there (a prefab's), otherwise make one.
		_flashlight = Components.Get<SpotLight>( FindMode.EverythingInSelfAndDescendants );
		if ( _flashlight.IsValid() && _flashlight.GameObject != GameObject ) return;

		var go = new GameObject( GameObject, true, "Flashlight" );
		go.Flags |= GameObjectFlags.NotSaved;
		go.LocalPosition = FlashlightOffset;

		_flashlight = go.Components.Create<SpotLight>();
		_flashlight.Shadows = true;
		_flashlight.FogMode = Light.FogInfluence.Enabled;

		// A thin visible beam from the torch.
		var shaft = go.Components.Create<LightShaft>();
		shaft.MaxLength = 900f;
		shaft.Sprites = 16;
		shaft.Brightness = 0.003f;
		shaft.MaxBrightness = 0.07f;
		_flashlight.LightColor = FlashlightColor;
		_flashlight.Intensity = FlashlightIntensity;
		_flashlight.ConeOuter = FlashlightCone * 0.5f;
		_flashlight.ConeInner = FlashlightCone * 0.3f;
		_flashlight.Radius = FlashlightRange;
		_flashlight.FogStrength = FlashlightFog;
	}

	/// <summary>
	/// True once the team has seen through the lizard's disguise: one of them was attacked by
	/// something wearing the envoy. Shared by every escort in the scene.
	/// </summary>
	public static bool CoverBlown { get; private set; }

	/// <summary>What the escorts shout when the disguise fails.</summary>
	[Property] public string CoverBlownLine { get; set; } = "It's wearing him! It's wearing the envoy like a onesie! Run!";

	/// <summary>Speed they run for the breach at once the disguise fails.</summary>
	[Property] public float FleeSpeed { get; set; } = 170f;

	void OnDamaged( float amount, GameObject attacker )
	{
		// Hurt by something that looks like one of their own: the disguise is finished.
		if ( CoverBlown || FactionTag.Of( attacker ) != FactionTag.Owners ) return;
		CoverBlown = true;

		var director = StoryDirector.Get( Scene );
		director?.ShowMessage( CoverBlownLine, 5f, "ESCORT" );
		director?.Shake( 2f, 0.3f );
		StorySound.Play( "sounds/opening/voice_garble.sound", WorldPosition + Vector3.Up * 64f );
	}

	void OnKilled( GameObject attacker )
	{
		if ( IsDead ) return;
		IsDead = true;
		IsMoving = false;
		Animate( Vector3.Zero );

		// Fall onto its back: a quarter turn about its own sideways axis. The flashlight goes with it.
		_sinceDeath = 0f;
		_deathFrom = WorldRotation;
		_deathTo = Rotation.FromAxis( WorldRotation.Right, 90f ) * WorldRotation;
	}

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor ) return;

		if ( IsDead )
		{
			float t = FallSeconds <= 0f ? 1f : MathF.Min( _sinceDeath / FallSeconds, 1f );
			WorldRotation = Rotation.Slerp( _deathFrom, _deathTo, t * t ); // speeds up as it tips
			return;
		}

		if ( !_player.IsValid() )
			_player = Scene.GetAllComponents<ReptileController>().FirstOrDefault()?.GameObject;
		if ( !Leader.IsValid() && !_leaderDied )
			Leader = Scene.GetAllComponents<Envoy>().FirstOrDefault();

		if ( !_leaderDied && Leader.IsValid() && Leader.IsDead )
		{
			_leaderDied = true;
			_sinceLeaderDied = 0f;
		}

		// Where it wants to stand, and how fast it may go there.
		var target = WorldPosition;
		float speed = 0f;
		float slack; // how far off its spot it may be before it starts walking

		// Fooled: the thing walking toward them now looks like the envoy. Stop backing away.
		bool fooled = _leaderDied && !CoverBlown && FactionTag.Of( _player ) == FactionTag.Owners;

		if ( _leaderDied )
		{
			if ( _sinceLeaderDied >= RetreatDelay && !fooled )
			{
				target = _home;
				speed = CoverBlown ? FleeSpeed : RetreatSpeed;
			}
			slack = 12f;
		}
		else if ( Leader.IsValid() )
		{
			target = Leader.WorldTransform.PointToWorld( FormationOffset );
			speed = WalkSpeed;
			// While the envoy stands talking it turns to follow the lizard, which swings the
			// formation spots about; don't shuffle after every small turn.
			slack = Leader.IsMoving ? 10f : 45f;
		}
		else
		{
			slack = 12f;
		}

		// Spawned or pushed up onto a boulder: come down to the leader's level before anything else.
		if ( !_leaderDied && Leader.IsValid() && WorldPosition.z - Leader.WorldPosition.z > 30f )
		{
			target = Leader.WorldPosition;
			speed = WalkSpeed;
			slack = 0f;
		}

		var toTarget = (target - WorldPosition).WithZ( 0 );
		float distance = toTarget.Length;
		var velocity = Vector3.Zero;

		// Once walking, carry on until it is nearly on the spot.
		if ( speed > 0f && distance > (IsMoving ? 6f : slack) )
		{
			float step = MathF.Min( speed * Time.Delta, distance );
			var move = toTarget / distance * step;
			velocity = Time.Delta > 0f ? move / Time.Delta : Vector3.Zero;
			WorldPosition = SnapToGround( WorldPosition + move );

			_sinceStride += step;
			if ( _sinceStride >= StrideLength )
			{
				_sinceStride = 0f;
				StorySound.Play( BootsSound, WorldPosition );
			}
		}
		IsMoving = velocity.Length > 1f;

		// Always face the lizard (so it backs away rather than turning its back); with no lizard,
		// face the way the envoy faces.
		var look = WorldRotation.Forward.WithZ( 0 );
		if ( _player.IsValid() ) look = (_player.WorldPosition - WorldPosition).WithZ( 0 );
		else if ( Leader.IsValid() ) look = Leader.WorldRotation.Forward.WithZ( 0 );
		if ( look.Length > 0.01f )
		{
			var facing = Rotation.LookAt( look.Normal, Vector3.Up );
			WorldRotation = Rotation.Slerp( WorldRotation, facing, MathF.Min( Time.Delta * 6f, 1f ) );
		}

		SwayFlashlight();
		Animate( velocity );
	}

	/// <summary>The flashlight points where the escort faces, wandering a little with the hand.</summary>
	void SwayFlashlight()
	{
		if ( !_flashlight.IsValid() || _flashlight.GameObject == GameObject ) return;

		float t = Time.Now + _swayPhase;
		float busy = IsMoving ? 1.6f : 1f; // bobs more on the move
		float pitch = 3f + MathF.Sin( t * 1.7f * busy ) * SwayDegrees * 0.6f;
		float yaw = MathF.Sin( t * 1.1f * busy + 1.3f ) * SwayDegrees;
		_flashlight.GameObject.LocalRotation = new Angles( pitch, yaw, 0f ).ToRotation();
	}

	/// <summary>Puts a position on the ground below (or just above) it, if there is any.</summary>
	Vector3 SnapToGround( Vector3 position )
	{
		var trace = Scene.Trace.Ray( position + Vector3.Up * 50f, position + Vector3.Down * 150f )
			.IgnoreGameObjectHierarchy( GameObject );
		if ( _player.IsValid() ) trace = trace.IgnoreGameObjectHierarchy( _player );

		var tr = trace.Run();
		if ( !tr.Hit ) return position;

		// People don't walk up boulders: if the ground ahead is a big step up, sidle round it.
		if ( tr.HitPosition.z - WorldPosition.z <= 24f ) return tr.HitPosition;

		var ahead = (position - WorldPosition).WithZ( 0 );
		var side = WorldPosition + new Vector3( -ahead.y, ahead.x, 0 ) * _sidestep;
		var sideTrace = Scene.Trace.Ray( side + Vector3.Up * 50f, side + Vector3.Down * 150f )
			.IgnoreGameObjectHierarchy( GameObject );
		if ( _player.IsValid() ) sideTrace = sideTrace.IgnoreGameObjectHierarchy( _player );
		var sideHit = sideTrace.Run();
		if ( sideHit.Hit && sideHit.HitPosition.z - WorldPosition.z <= 24f ) return sideHit.HitPosition;

		_sidestep = -_sidestep; // blocked that way too: try the other side next step
		return WorldPosition;
	}

	float _sidestep = 1f;

	/// <summary>Walk or idle on the citizen animgraph. Does nothing for other models.</summary>
	void Animate( Vector3 velocity )
	{
		if ( _anim.IsValid() )
		{
			_anim.WithVelocity( velocity );
			_anim.WithWishVelocity( velocity );
			_anim.IsGrounded = true;
			return;
		}

		if ( !_renderer.IsValid() ) return;

		// No helper: set the few citizen parameters that matter. Unknown names are ignored.
		float forward = Vector3.Dot( velocity, WorldRotation.Forward );
		float left = Vector3.Dot( velocity, WorldRotation.Left );
		_renderer.Set( "b_grounded", true );
		_renderer.Set( "move_groundspeed", velocity.Length );
		_renderer.Set( "wish_groundspeed", velocity.Length );
		_renderer.Set( "move_x", forward );
		_renderer.Set( "move_y", left );
		_renderer.Set( "wish_x", forward );
		_renderer.Set( "wish_y", left );
	}
}