Sump/Hub/HubSurface.cs

Post-game hub component for the Sump project. Once Rampage.Unlocked is set and the player is in the hub, it builds a glowing ladder of light at Sump.HubSpawn, shows a one-time card, replaces the objective, has healed misfits speak a line about the surface, and on Use fades out and loads Rampage.ScenePath.

using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// The way back UP, for the post-game. Add it to the Sump's root object (the bootstrap's); it
/// does nothing until <see cref="Rampage.Unlocked"/> (the finale done and everybody healed) and
/// only ever in the hub. Then:
///
///   - a ladder of light stands at <see cref="Sump.HubSpawn"/>, going up the shaft the player
///     first fell down, with a pulse climbing its rungs;
///   - the first time, a card says the post-game is open (remembered in the save);
///   - the objective reads "Go back up. Give them what they gave us.";
///   - the healed misfits each say a line about what is up there, one every little while;
///   - at the ladder, E fades out and loads <see cref="Rampage.ScenePath"/>.
///
/// It is built from the Sump's own primitives, is not saved, and is hidden again whenever the
/// Sump leaves the hub.
/// </summary>
[Title( "Hub Surface (way up)" ), Category( "Sump" ), Icon( "north" )]
public sealed class HubSurface : Component
{
	/// <summary>For testing: the way up is there whatever the save says, and the card shows every time.</summary>
	[Property] public bool AlwaysUnlocked { get; set; }

	/// <summary>Where the ladder stands, from the hub's spawn point.</summary>
	[Property, Group( "Ladder" )] public Vector3 Offset { get; set; }
	[Property, Group( "Ladder" )] public float Height { get; set; } = 900f;
	[Property, Group( "Ladder" )] public float Width { get; set; } = 34f;
	[Property, Group( "Ladder" )] public float RungGap { get; set; } = 30f;
	[Property, Group( "Ladder" )] public Color Glow { get; set; } = new( 1f, 0.82f, 0.4f );
	/// <summary>How fast the pulse climbs, in rungs per second.</summary>
	[Property, Group( "Ladder" )] public float PulseSpeed { get; set; } = 14f;
	/// <summary>How near the player must be to climb.</summary>
	[Property, Group( "Ladder" )] public float UseRadius { get; set; } = 110f;
	/// <summary>Seconds of fade before the surface loads.</summary>
	[Property, Group( "Ladder" )] public float ClimbSeconds { get; set; } = 1.4f;

	[Property, Group( "Words" )] public float CardSeconds { get; set; } = 7f;
	/// <summary>Seconds between two misfits speaking of the surface: shortest and longest.</summary>
	[Property, Group( "Words" )] public Vector2 LineGap { get; set; } = new( 9f, 16f );

	public const string Prompt = "E  climb back up to the surface";
	public const string Objective = "Go back up. Give them what they gave us.";
	const string CardTitle = "POST-GAME UNLOCKED: THE RAMPAGE";
	const string CardLine = "The way back up is open.\nThey are still up there. They have learned nothing.";
	const string SeenNote = "rampage_unlock_seen";

	/// <summary>What a healed misfit says about the surface, two lines for each way first contact went.</summary>
	static readonly Dictionary<FirstContact, string[]> Lines = new()
	{
		[FirstContact.ShotOnFarm] = new[]
		{
			"There is a farm up there, and a man on a porch. Say hello to his porch for me.",
			"They shot first. I only wanted to ask about the cows. Ask them about the cows. Loudly.",
		},
		[FirstContact.Dissected] = new[]
		{
			"They kept my pieces on a tray, with labels. Go and unlabel something of theirs.",
			"They have a table up there with straps on it. I would like it to be a much flatter table.",
		},
		[FirstContact.WorshippedThenSold] = new[]
		{
			"They put a price on me. Go up and show them what things cost.",
			"They built me a temple and then a gift shop. Start with the gift shop.",
		},
		[FirstContact.BecameMeme] = new[]
		{
			"They laughed for a whole summer. Be the last thing they ever film.",
			"Make them watch. They were always so good at watching.",
		},
		[FirstContact.AdoptedThenForgotten] = new[]
		{
			"They left me in a box in the attic. Mind the attic. No. Do not mind the attic.",
			"Somebody up there forgot me. Help them remember. From a height.",
		},
	};

	GameObject _root;
	readonly List<ModelRenderer> _rungs = new();
	PointLight _light;
	Vector3 _at;

	bool _cardOurs;
	float _cardUntil;
	bool _cardDone;
	float _nextLineAt = -1f;
	readonly HashSet<int> _spoken = new();
	float _leavingAt = -1f;
	bool _lockedPlayer;

	bool Open => (AlwaysUnlocked || Rampage.Unlocked) && Sump.Mode == SumpMode.Hub && SumpCavern.Ready;

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

		if ( !Open )
		{
			if ( _root.IsValid() ) _root.Enabled = false;
			DropCard();
			_nextLineAt = -1f;
			return;
		}

		EnsureBuilt();
		if ( !_root.IsValid() ) return;
		_root.Enabled = true;
		Animate();

		float now = RealTime.Now;
		if ( _leavingAt >= 0f ) { UpdateLeaving( now ); return; }

		UpdateCard( now );
		UpdateObjective();
		UpdateLines( now );
		UpdateLadder();
	}

	protected override void OnDisabled()
	{
		DropCard();
		if ( _root.IsValid() ) _root.Destroy();
		_root = null;
		_rungs.Clear();
		_light = null;
		if ( _lockedPlayer && Sump.Player.IsValid() ) Sump.Player.InputLocked = false;
		_lockedPlayer = false;
	}

	// ---- The ladder -------------------------------------------------------------------------------

	void EnsureBuilt()
	{
		if ( _root.IsValid() ) return;
		_rungs.Clear();

		_at = Sump.HubSpawn + Offset;
		_root = Sump.Spawn( "Way Up", _at, GameObject );
		float height = MathF.Max( Height, 100f );
		float half = Width * 0.5f;
		var dim = Shade( 0.7f );

		// Two rails and a run of rungs, none of them solid: it is light, and the player lands here.
		foreach ( float side in new[] { -1f, 1f } )
			AddGlowing( Sump.Box( _root, "Rail", _at + new Vector3( 0f, side * half, height * 0.5f ), new Vector3( 3f, 3f, height ), dim, false ), false );

		int count = Math.Clamp( (int)(height / MathF.Max( RungGap, 8f )), 4, 80 );
		for ( int i = 0; i < count; i++ )
			AddGlowing( Sump.Box( _root, "Rung", _at + new Vector3( 0f, 0f, (i + 0.7f) * height / count ), new Vector3( 3f, Width, 3f ), dim, false ), true );

		// A pool of it on the floor, and motes drifting up the first stretch.
		AddGlowing( Sump.Ball( _root, "Pool", _at + Vector3.Up * 1.5f, new Vector3( 70f, 70f, 1.2f ), Shade( 0.45f ) ), false );
		for ( int i = 0; i < 6; i++ )
		{
			float angle = i * 2.4f;
			AddGlowing( Sump.Ball( _root, "Mote", _at + new Vector3( MathF.Cos( angle ) * 26f, MathF.Sin( angle ) * 26f, 40f + i * 34f ), new Vector3( 3f, 3f, 3f ), Glow ), false );
		}

		var lamp = Sump.Spawn( "Way Up Light", _at + Vector3.Up * 90f, _root );
		_light = lamp.Components.Create<PointLight>();
		_light.Radius = 520f;
		_light.Shadows = false;
		_light.LightColor = Glow.WithAlpha( 1f );

		var high = Sump.Spawn( "Way Up Light High", _at + Vector3.Up * MathF.Min( height * 0.6f, 520f ), _root );
		var highLight = high.Components.Create<PointLight>();
		highLight.Radius = 420f;
		highLight.Shadows = false;
		highLight.LightColor = Shade( 0.6f );
	}

	void AddGlowing( GameObject part, bool rung )
	{
		var renderer = part.IsValid() ? part.Components.Get<ModelRenderer>() : null;
		if ( !renderer.IsValid() ) return;
		renderer.RenderType = ModelRenderer.ShadowRenderType.Off;
		if ( rung ) _rungs.Add( renderer );
	}

	Color Shade( float level ) => new Color( Glow.r * level, Glow.g * level, Glow.b * level, 1f );

	/// <summary>A pulse of brightness climbing the rungs, and the lamp breathing with it.</summary>
	void Animate()
	{
		float head = Time.Now * PulseSpeed;
		for ( int i = 0; i < _rungs.Count; i++ )
		{
			if ( !_rungs[i].IsValid() ) continue;
			// Brightest where the pulse is, with a tail below it; a new pulse every 12 rungs.
			float behind = (head - i) % 12f;
			if ( behind < 0f ) behind += 12f;
			_rungs[i].Tint = Shade( 0.55f + 1.1f * MathF.Max( 1f - behind / 5f, 0f ) );
		}
		if ( _light.IsValid() ) _light.LightColor = Shade( 0.85f + 0.15f * MathF.Sin( Time.Now * 2.1f ) );
	}

	void UpdateLadder()
	{
		var player = Sump.Player;
		if ( !player.IsValid() || player.InputLocked ) return;
		if ( (player.WorldPosition - _at).WithZ( 0f ).Length > UseRadius || MathF.Abs( player.WorldPosition.z - _at.z ) > 160f ) return;
		if ( !string.IsNullOrEmpty( Sump.Prompt ) && Sump.Prompt != Prompt ) return;      // somebody nearer wants E

		Sump.Prompt = Prompt;
		if ( !Input.Pressed( "Use" ) ) return;

		_leavingAt = RealTime.Now;
		player.InputLocked = true;
		_lockedPlayer = true;
		DropCard();
		try { Sound.Play( "sounds/rampage/climb_up.sound" ); } catch ( Exception ) { }
	}

	void UpdateLeaving( float now )
	{
		float t = (now - _leavingAt) / MathF.Max( ClimbSeconds, 0.1f );
		Sump.Fade = Math.Clamp( t, 0f, 1f );
		if ( t < 1f ) return;

		_leavingAt = -1f;
		if ( Sump.Player.IsValid() ) Sump.Player.InputLocked = false;
		_lockedPlayer = false;
		SumpCavern.CameFromSurface = true;   // the next arrival down here is the climb back down
		Game.ChangeScene( Rampage.ScenePath );
	}

	// ---- Words ------------------------------------------------------------------------------------

	/// <summary>The one-time card. It waits for the screen to be clear and nobody else's card to be up.</summary>
	void UpdateCard( float now )
	{
		if ( _cardOurs )
		{
			if ( now >= _cardUntil || Sump.CardTitle != CardTitle ) DropCard();
			return;
		}
		if ( _cardDone || !string.IsNullOrEmpty( Sump.CardTitle ) || Sump.Fade > 0.05f ) return;

		_cardDone = true;
		if ( !AlwaysUnlocked )
		{
			if ( SumpState.GetNote( SeenNote ) == "1" ) return;
			SumpState.SetNote( SeenNote, "1" );
		}
		Sump.CardTitle = CardTitle;
		Sump.CardLine = CardLine;
		_cardOurs = true;
		_cardUntil = now + CardSeconds;
		try { Sound.Play( "sounds/rampage/unlock.sound" ); } catch ( Exception ) { }
	}

	void DropCard()
	{
		if ( !_cardOurs ) return;
		_cardOurs = false;
		if ( Sump.CardTitle == CardTitle ) Sump.CardTitle = Sump.CardLine = "";
	}

	/// <summary>Takes the hub's goal over once there is nothing left to do down here but go up.</summary>
	void UpdateObjective()
	{
		string current = Sump.Objective ?? "";
		if ( current == Objective ) return;
		bool hubs = current.Length == 0 || current == "The way down is open" || current.StartsWith( "Help " ) || current.StartsWith( "Find the ones" );
		if ( hubs ) Sump.Objective = Objective;
	}

	/// <summary>Every so often one of the healed says its piece about the surface, each of them once a visit.</summary>
	void UpdateLines( float now )
	{
		if ( _nextLineAt < 0f ) { _nextLineAt = now + 5f; return; }
		if ( now < _nextLineAt || _cardOurs || Sump.Lines.Count > 0 ) return;
		_nextLineAt = now + Game.Random.Float( LineGap.x, MathF.Max( LineGap.y, LineGap.x ) );

		var healed = SumpState.Misfits.Where( m => m is not null && m.Healed ).ToList();
		if ( healed.Count == 0 && AlwaysUnlocked ) healed = SumpState.Misfits.Where( m => m is not null ).ToList();
		var who = healed.FirstOrDefault( m => !_spoken.Contains( m.Index ) );
		if ( who is null ) return;
		_spoken.Add( who.Index );

		if ( !Lines.TryGetValue( who.Contact, out var lines ) || lines.Length == 0 ) return;
		string speaker = MisfitVoice.ShortName( who );
		Sump.Say( string.IsNullOrEmpty( speaker ) ? who.Name : speaker, lines[(who.Seed & 0x7FFFFFFF) % lines.Length], 6f );
	}
}