Sump/Finale/SumpFinale.cs

The controller for the Sump's endgame. On Sump.FinaleRequested it locks the player, hides the hub, builds three descending layers at runtime (FinaleThroat, FinaleDeep, FinaleHeart) with fades, title cards and a procession, runs each layer's updates with exception guards, drives the shared heartbeat pulse, keeps the player inside the layer bounds, handles being sent back to a checkpoint, and on an answer or turn-back tears everything down, restores the player's floor/leash/speed/zoom state and returns to the hub.

using System;

/// <summary>
/// The lore and the finale of the Sump.
///
/// THE LORE (SumpFinale.Lore.cs): none of the misfits' orders ever arrived, and neither did the
/// lizard's. Earth is alive. It eats signals, and humans are its immune system: they do not hate
/// strangers, they go to what does not belong the way a hand goes to a splinter. The radio room
/// gives this out in fragments that decode a little more with every frequency opened.
///
/// THE FINALE (this file and the three layers): on <see cref="Sump.FinaleRequested"/> the player
/// leads every healed misfit down to the planet's heart to answer the question it has been asking.
/// Built at runtime far below the hub, at <see cref="Sump.FinaleOrigin"/>, one layer at a time:
///   1. <see cref="FinaleThroat"/>  the tunnel down; valves that only open for the whole procession.
///   2. <see cref="FinaleDeep"/>    chambers of cells; get through by belonging, not by running.
///   3. <see cref="FinaleHeart"/>   the question, the Sump's answers, and the player's.
/// This component is the frame they all hang in: the fades and cards between layers, the
/// procession (<see cref="FinaleProcession"/>), the heartbeat, keeping the player inside the
/// place, being put back after a pinning, turning back early, the ending, and putting back
/// everything it changed on the player. Nothing in here is a game over.
/// The bootstrap adds this to the Sump object.
/// </summary>
[Title( "Sump Finale" ), Category( "Sump" ), Icon( "favorite" )]
public sealed partial class SumpFinale : Component
{
	public static SumpFinale Current { get; private set; }

	/// <summary>Name of this module's speed factor on the controller.</summary>
	public const string SpeedName = "finale";

	// ---- Tuning ---------------------------------------------------------------------------------
	/// <summary>Seconds the fades to and from black take.</summary>
	[Property, Group( "Timing" )] public float FadeSeconds { get; set; } = 1.2f;
	/// <summary>Seconds a layer's title card stays up.</summary>
	[Property, Group( "Timing" )] public float CardSeconds { get; set; } = 5.5f;
	/// <summary>Seconds the closing card stays up before the way back is offered.</summary>
	[Property, Group( "Timing" )] public float ClosingSeconds { get; set; } = 10f;
	/// <summary>How far below the last one each layer is built, in inches.</summary>
	[Property, Group( "Timing" )] public float LayerDrop { get; set; } = 9000f;

	/// <summary>Hold this to turn back to the Sump, unfinished. "Reload" is R.</summary>
	[Property, Group( "Rules" )] public string LeaveAction { get; set; } = "Reload";
	[Property, Group( "Rules" )] public float LeaveHoldSeconds { get; set; } = 1.5f;

	/// <summary>Seconds between heartbeats in the throat, the deep layers and the heart.</summary>
	[Property, Group( "Heartbeat" )] public float ThroatBeat { get; set; } = 6f;
	[Property, Group( "Heartbeat" )] public float DeepBeat { get; set; } = 5f;
	[Property, Group( "Heartbeat" )] public float HeartBeat { get; set; } = 4.2f;
	/// <summary>How strongly the beat is felt in each layer, 0 to 1.</summary>
	[Property, Group( "Heartbeat" )] public Vector3 BeatStrength { get; set; } = new( 0.35f, 0.65f, 1f );

	/// <summary>For testing: skips the layer being played (in the heart, straight to an ending). Clears itself.</summary>
	[Property, Group( "Testing" )] public bool DebugSkipLayer { get; set; }
	/// <summary>For testing: a key that does the same. "Slot0" is the 0 key. Empty for none.</summary>
	[Property, Group( "Testing" )] public string DebugSkipAction { get; set; } = "";   // off in the shipped game; set to an input action to skip layers while testing

	// ---- Published for other modules (the HUD, sound, lighting) -----------------------------------
	/// <summary>True from the moment the descent is asked for until the player is back in the Sump.</summary>
	public bool Running => _stage != Stage.Idle;
	/// <summary>0 none, 1 the throat, 2 the deep layers, 3 the heart.</summary>
	public int Layer { get; private set; }
	public string LayerTitle { get; private set; } = "";
	/// <summary>The heartbeat, 0 to 1: a slow double thump, stronger the deeper the player is.</summary>
	public float HeartPulse { get; private set; }
	/// <summary>How much the player does not belong, 0 (belongs) to 1. Only means anything in the deep layers.</summary>
	public float Foreign { get; set; }
	/// <summary>0 to 1: how long the turn-back key has been held.</summary>
	public float LeaveProgress { get; private set; }
	/// <summary>The answer given this time ("here", "go", "stay"), or empty until it is given.</summary>
	public string Answer { get; private set; } = "";
	/// <summary>True while the closing card is up and the way back is being offered.</summary>
	public bool Ended => _stage == Stage.Outro;

	public ReptileController Player => _player;
	public FinaleProcession Procession => _procession;
	public FinaleLayer ActiveLayer => _layer;

	// How the descent was played; the heart reads these to see which answer fits.
	/// <summary>Times the cells let go because the player went still.</summary>
	public int Calmed { get; set; }
	/// <summary>Times the player was pinned long enough to be put back.</summary>
	public int SentBack { get; private set; }
	/// <summary>Misfits carried off, and misfits fetched back.</summary>
	public int Taken { get; set; }
	public int Freed { get; set; }
	public float StillSeconds { get; set; }
	public float RanSeconds { get; set; }
	/// <summary>Stretches the time between heartbeats (1 normal). The heart slows itself with this.</summary>
	public float BeatSlow { get; set; } = 1f;

	// ---- State ----------------------------------------------------------------------------------
	enum Stage { Idle, FadeOut, Card, Play, Outro, ReturnOut, ReturnIn }

	Stage _stage = Stage.Idle;
	float _t;                    // real seconds in this stage
	ReptileController _player;
	GameObject _root;
	FinaleSpace _space;
	FinaleLayer _layer;
	FinaleProcession _procession;
	int _next;
	string _hubObjective = "";
	Func<Vector3, float> _savedFloor;
	bool _turnedBack, _answered, _faulted;
	float _beat;

	// Being put back: a short fade to black and up again in the middle of a layer.
	bool _blinking, _blinkDone;
	float _blinkT;
	string _blinkTitle = "", _blinkLine = "";

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

	protected override void OnDestroy()
	{
		Sump.FinaleRequested -= OnRequested;
		if ( Running )
		{
			// Removed in the middle of it: everything on the player is put back, the hub with
			// its air returns, and the screen is not left black.
			TearDown();
			if ( _player.IsValid() ) { _player.InputLocked = false; _player.ForcedWish = null; }
			// (Not while the whole scene is going: there is no hub to bring back then.)
			if ( GameObject.IsValid() && (Sump.Mode == SumpMode.Finale || Sump.Mode == SumpMode.Ended) )
			{
				SumpCavern.SetHubVisible( true );
				Sump.Mode = SumpMode.Hub;
				Sump.Fade = 0f;
				Sump.CardTitle = Sump.CardLine = "";
			}
			_stage = Stage.Idle;
		}
		if ( Current == this ) Current = null;
	}

	void OnRequested()
	{
		if ( Running ) return;

		_player = Sump.Player;
		if ( !_player.IsValid() ) { Sump.Mode = SumpMode.Hub; return; }

		Answer = "";
		Calmed = SentBack = Taken = Freed = 0;
		StillSeconds = RanSeconds = 0f;
		BeatSlow = 1f;
		Foreign = 0f;
		LeaveProgress = 0f;
		_turnedBack = _answered = _faulted = _blinking = false;
		_hubObjective = Sump.Objective;
		_savedFloor = _player.FloorHeight;

		_player.InputLocked = true;
		_player.ForcedWish = null;
		Sump.Sfx( "finale_descend", _player.WorldPosition );
		_next = 1;
		Go( Stage.FadeOut );
	}

	void Go( Stage stage )
	{
		_stage = stage;
		_t = 0f;
	}

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor ) return;
		UpdateLore();
		if ( _stage == Stage.Idle ) return;

		_t += RealTime.Delta;
		float dt = Time.Delta;
		UpdatePulse( dt );

		switch ( _stage )
		{
			case Stage.FadeOut:
				Hold();
				Sump.Fade = MathF.Max( Sump.Fade, Math.Clamp( _t / MathF.Max( FadeSeconds, 0.05f ), 0f, 1f ) );
				if ( _t >= FadeSeconds ) Enter( _next );
				break;

			case Stage.Card:
				// Black for a moment while the place settles, then it comes up behind the card.
				Hold();
				Tick( dt, false );
				Sump.Fade = 1f - Math.Clamp( (_t - 1.4f) / 1.6f, 0f, 1f );
				if ( _t >= CardSeconds ) BeginPlay();
				break;

			case Stage.Play: Play( dt ); break;
			case Stage.Outro: Outro( dt ); break;

			case Stage.ReturnOut:
				Hold();
				Tick( dt, false );
				Sump.Fade = MathF.Max( Sump.Fade, Math.Clamp( _t / MathF.Max( FadeSeconds, 0.05f ), 0f, 1f ) );
				if ( _t >= FadeSeconds + (_turnedBack ? 2.2f : 0.4f) ) Finish();
				break;

			case Stage.ReturnIn:
				Sump.Fade = 1f - Math.Clamp( (_t - 0.6f) / 1.4f, 0f, 1f );
				if ( _t < 2f ) break;
				Sump.Fade = 0f;
				if ( _player.IsValid() ) _player.InputLocked = false;
				Go( Stage.Idle );
				break;
		}
	}

	/// <summary>The player has no controls while the finale is between things.</summary>
	void Hold()
	{
		if ( !_player.IsValid() ) return;
		_player.InputLocked = true;
		_player.ForcedWish = null;
	}

	// ---- Going down -----------------------------------------------------------------------------

	/// <summary>The screen is black: build a layer (taking the last one away) and put everybody at its start.</summary>
	void Enter( int number )
	{
		try
		{
			if ( !_root.IsValid() )
			{
				// The first layer: the hub goes (and with it the rock that keeps the lizard in).
				SumpCavern.SetHubVisible( false );
				_root = Sump.Spawn( "Sump Finale", Sump.FinaleOrigin );
				_procession = new FinaleProcession( _root, SumpState.Healed, MisfitGenerator.Mix( SumpState.Seed, 0xF1A1 ) );
			}

			_layer?.End();
			_space?.Destroy();

			_layer = number switch
			{
				1 => new FinaleThroat(),
				2 => new FinaleDeep(),
				_ => new FinaleHeart(),
			};
			var origin = Sump.FinaleOrigin + Vector3.Down * (LayerDrop * (number - 1));
			_space = new FinaleSpace( _root, "Finale Layer " + number, origin, MisfitGenerator.Mix( SumpState.Seed, 0xF1A1, number ) );
			_layer.Finale = this;
			_layer.Space = _space;
			_layer.Build();

			// The ground is the layer's own arithmetic, so nobody falls through a seam.
			var layer = _layer;
			_procession.Floor = layer.Floor;
			_player.FloorHeight = point => layer.Floor( point ) - 8f;
			_player.Unpin();
			_player.SetCameraZoom( SpeedName, layer.CameraZoom );
			MoveTo( layer.Start, layer.StartYaw );
			_procession.Regroup( layer.Start, layer.StartYaw, true );

			Layer = number;
			LayerTitle = layer.Title;
			Foreign = 0f;
			_beat = 0f;

			Sump.CardTitle = layer.Title;
			Sump.CardLine = layer.CardLine;
			Sump.Objective = "";
			Sump.Prompt = null;
			Sump.Sfx( "finale_layer", layer.Start );
			Go( Stage.Card );
		}
		catch ( Exception e )
		{
			// Whatever went wrong, the player goes home in one piece.
			Log.Warning( $"Sump finale could not build layer {number}: {e}" );
			_faulted = true;   // nothing half-built is run on the way out
			_turnedBack = true;
			Sump.CardTitle = "THE WAY DOWN CLOSES";
			Sump.CardLine = "Not yet. It will open again.";
			Go( Stage.ReturnOut );
		}
	}

	void BeginPlay()
	{
		Sump.CardTitle = Sump.CardLine = "";
		Sump.Fade = 0f;
		_player.InputLocked = false;
		Guard( () => _layer.Begin() );
		if ( Layer == 1 && !string.IsNullOrEmpty( LeaveAction ) )
			Sump.Say( "", "R (hold)  turn back. The way down will still be there.", 6f );
		Go( Stage.Play );
	}

	// ---- Playing --------------------------------------------------------------------------------

	void Play( float dt )
	{
		// The prompt line belongs to the layer while it runs: cleared, then set again by whoever wants it.
		Sump.Prompt = null;

		// A layer that has failed once is not run again (it would fail again, every frame):
		// the way down closes and the player is taken home.
		if ( _faulted )
		{
			_turnedBack = true;
			_blinking = false;
			Sump.CardTitle = "THE WAY DOWN CLOSES";
			Sump.CardLine = "Not yet. It will open again.";
			Go( Stage.ReturnOut );
			return;
		}

		if ( _blinking )
		{
			Blink();
			Tick( dt, false );
			return;
		}

		Guard( () => _layer.Update( dt ) );
		if ( _stage != Stage.Play ) return;   // the heart has been answered

		Tick( dt, true );
		Sump.Objective = _layer.Objective;
		KeepInside();

		// Testing: straight on.
		if ( DebugSkipLayer || (!string.IsNullOrEmpty( DebugSkipAction ) && Input.Pressed( DebugSkipAction )) )
		{
			DebugSkipLayer = false;
			if ( Layer < 3 ) NextLayer();
			else EndWith( "here" );
			return;
		}

		// The way out that is always there.
		if ( !string.IsNullOrEmpty( LeaveAction ) && Input.Down( LeaveAction ) )
		{
			LeaveProgress = MathF.Min( LeaveProgress + RealTime.Delta / MathF.Max( LeaveHoldSeconds, 0.1f ), 1f );
			Sump.Prompt = "Turning back...";
			if ( LeaveProgress >= 1f ) { TurnBack(); return; }
		}
		else LeaveProgress = 0f;

		if ( _layer.Done && Layer < 3 ) NextLayer();
	}

	/// <summary>Moves the procession, the pulsing walls and the layer's lights on by a frame.</summary>
	void Tick( float dt, bool talk )
	{
		if ( _faulted || _procession is null || _space is null || _layer is null || !_player.IsValid() ) return;
		_procession.Update( dt, _player.WorldPosition );
		if ( talk ) _procession.Chatter( dt, _layer.Chatter );
		_space.Animate( Time.Now, HeartPulse, dt );
	}

	/// <summary>Collision should keep the player in; if it ever does not, this does.</summary>
	void KeepInside()
	{
		var at = _player.WorldPosition;
		var inside = _layer.Contain( at );
		if ( (inside - at).Length > 1f ) _player.Teleport( inside );
	}

	void NextLayer()
	{
		_next = Layer + 1;
		Hold();
		Sump.Prompt = null;
		Sump.Sfx( "finale_swallow", _player.WorldPosition );
		Go( Stage.FadeOut );
	}

	/// <summary>Runs a piece of a layer, so a mistake in one cannot strand the player down here.</summary>
	void Guard( Action action )
	{
		try { action(); }
		catch ( Exception e )
		{
			if ( !_faulted ) Log.Warning( $"Sump finale error ({LayerTitle}): {e}" );
			_faulted = true;
		}
	}

	// ---- Being put back -------------------------------------------------------------------------

	/// <summary>
	/// The player is carried back to the layer's last safe spot: a fade to black, a card, and up
	/// again with everybody regrouped. Used when the cells have had them pinned too long.
	/// </summary>
	public void SendBack( string title, string line )
	{
		if ( _blinking || _stage != Stage.Play ) return;
		_blinking = true;
		_blinkDone = false;
		_blinkT = 0f;
		_blinkTitle = title ?? "";
		_blinkLine = line ?? "";
		SentBack++;
		Sump.Sfx( "finale_sent_back", _player.WorldPosition );
	}

	void Blink()
	{
		_blinkT += RealTime.Delta;
		Hold();

		if ( _blinkT < 0.6f ) { Sump.Fade = MathF.Max( Sump.Fade, _blinkT / 0.6f ); return; }

		if ( !_blinkDone )
		{
			_blinkDone = true;
			Sump.Fade = 1f;
			var (feet, yaw) = _layer.Checkpoint;
			MoveTo( feet, yaw );
			_procession.Regroup( feet, yaw );
			Guard( () => _layer.SentBack() );
			Sump.CardTitle = _blinkTitle;
			Sump.CardLine = _blinkLine;
		}

		if ( _blinkT < 3.2f ) { Sump.Fade = 1f; return; }
		Sump.CardTitle = Sump.CardLine = "";
		Sump.Fade = 1f - Math.Clamp( (_blinkT - 3.2f) / 1f, 0f, 1f );
		if ( _blinkT < 4.2f ) return;

		Sump.Fade = 0f;
		_blinking = false;
		_player.InputLocked = false;
	}

	// ---- The ending -----------------------------------------------------------------------------

	/// <summary>The question has been answered ("here", "go" or "stay"): save it, show the closing card, offer the way back.</summary>
	public void EndWith( string answer )
	{
		if ( _answered || !Running ) return;
		_answered = true;
		Answer = string.IsNullOrEmpty( answer ) ? "here" : answer;

		SumpState.FinaleDone = true;
		SumpState.SetNote( AnswerKey, Answer );
		SumpState.Save();

		var (title, line) = FinaleWriting.Closing( Answer, SumpState.HealedCount );
		Sump.CardTitle = title;
		Sump.CardLine = line;
		Sump.Objective = "";
		Sump.Prompt = null;
		Sump.Mode = SumpMode.Ended;
		Sump.Sfx( "finale_end", _player.WorldPosition );

		_player.InputLocked = false;
		LeaveProgress = 0f;
		Go( Stage.Outro );
	}

	/// <summary>After the answer: the procession walks round the heart, and the player leaves when they like.</summary>
	void Outro( float dt )
	{
		Sump.Prompt = null;
		if ( !_faulted && _layer is not null )
		{
			Guard( () => _layer.Update( dt ) );
			Tick( dt, false );
			KeepInside();
		}

		if ( _t < ClosingSeconds ) return;
		Sump.CardTitle = Sump.CardLine = "";
		Sump.Prompt = "E  go back up to the Sump";
		if ( !Input.Pressed( "Use" ) ) return;

		Hold();
		Sump.Prompt = null;
		Sump.Sfx( "finale_ascend", _player.WorldPosition );
		Go( Stage.ReturnOut );
	}

	/// <summary>Leaves now, unfinished. The hatch stays open.</summary>
	public void TurnBack()
	{
		if ( _stage != Stage.Play && _stage != Stage.Card ) return;
		_turnedBack = true;
		_blinking = false;
		Sump.Prompt = null;
		Sump.CardTitle = "YOU TURN BACK";
		Sump.CardLine = "It will keep asking. It is very good at waiting.";
		Sump.Sfx( "finale_turn_back", _player.WorldPosition );
		Go( Stage.ReturnOut );
	}

	// ---- Coming back ----------------------------------------------------------------------------

	/// <summary>Out of the descent (answered, turned back or broken): everything is put back and the hub returns.</summary>
	void Finish()
	{
		Sump.Fade = 1f;
		TearDown();

		SumpCavern.SetHubVisible( true );
		if ( _player.IsValid() ) MoveTo( Sump.HubSpawn, 0f );

		Sump.CardTitle = Sump.CardLine = "";
		Sump.Prompt = null;
		Sump.Mode = SumpMode.Hub;
		Sump.Sfx( "finale_return", Sump.HubSpawn );

		if ( _answered )
		{
			Sump.Objective = "The radio has stopped hissing. Go and listen.";
			Sump.Say( "THE SUMP", "Home. The same cave. It sounds different. It smells exactly the same.", 7f );
		}
		else Sump.Objective = _hubObjective ?? "";

		Go( Stage.ReturnIn );
	}

	/// <summary>Destroys everything built and puts back everything that was changed on the player.</summary>
	void TearDown()
	{
		try { _layer?.End(); } catch ( Exception e ) { Log.Warning( $"Sump finale layer did not end cleanly: {e.Message}" ); }
		_layer = null;
		_space = null;
		_procession = null;
		if ( _root.IsValid() ) _root.Destroy();
		_root = null;
		if ( CrowdHosts.Fallback is FinaleCellHost ) CrowdHosts.Fallback = null;

		if ( _player.IsValid() )
		{
			_player.FloorHeight = _savedFloor;
			_player.ForcedWish = null;
			_player.Leash = null;
			_player.SpeedScale = 1f;
			_player.ClearView = false;
			_player.Unpin();
			_player.SetSpeedFactor( SpeedName, 1f );
			_player.SetCameraZoom( SpeedName, 1f );
		}
		_savedFloor = null;

		Layer = 0;
		LayerTitle = "";
		HeartPulse = 0f;
		Foreign = 0f;
		BeatSlow = 1f;
		LeaveProgress = 0f;
		_blinking = false;
	}

	void MoveTo( Vector3 feet, float yaw )
	{
		if ( SumpBootstrap.Current.IsValid() ) Sump.Teleport( feet, yaw );
		else _player.Teleport( feet, yaw );
	}

	// ---- The heartbeat --------------------------------------------------------------------------

	/// <summary>
	/// A slow double thump (lub, then a softer dub), 0 to 1 in <see cref="HeartPulse"/>. Everything
	/// that pulses down here follows it, and the sound and lighting module can too.
	/// </summary>
	void UpdatePulse( float dt )
	{
		if ( Layer <= 0 || _layer is null ) { HeartPulse = 0f; return; }

		float seconds = Layer == 1 ? ThroatBeat : Layer == 2 ? DeepBeat : HeartBeat;
		float strength = Layer == 1 ? BeatStrength.x : Layer == 2 ? BeatStrength.y : BeatStrength.z;

		_beat += dt / MathF.Max( seconds * MathF.Max( BeatSlow, 0.2f ), 0.5f );
		if ( _beat >= 1f )
		{
			_beat -= MathF.Floor( _beat );
			if ( _player.IsValid() && (_stage == Stage.Play || _stage == Stage.Outro) )
			{
				// Heard from the direction of the heart, however far off it is.
				var toward = (_layer.PulseFrom - _player.WorldPosition);
				var from = _player.WorldPosition + (toward.Length > 300f ? toward.Normal * 300f : toward);
				Sump.Sfx( "heart_beat", from, 0.35f + 0.65f * strength );
			}
		}

		float shape = MathF.Max( Bump( _beat, 0.08f, 0.09f ), 0.65f * Bump( _beat, 0.3f, 0.1f ) );
		HeartPulse += (strength * shape - HeartPulse) * Math.Clamp( dt * 14f, 0f, 1f );
	}

	/// <summary>A smooth bump of height 1 centred on c, w wide to either side.</summary>
	static float Bump( float p, float c, float w )
	{
		float d = MathF.Abs( p - c ) / w;
		if ( d >= 1f ) return 0f;
		float k = 1f - d * d;
		return k * k;
	}
}