Sump/Presentation/SumpAudio.cs

The audio layer for the Sump game. Owns looping ambience beds per place and per flashback genre with crossfades, plays random drip one-shots in the hub, synthesises speaker voices as pitched blip runs when Sump.Said fires, rings in the ears as Calm drops, and schedules stingers and a heal chime on mode changes. Sound loading and playback all go through Sump.Sfx.

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

/// <summary>
/// The sound of the Sump that belongs to no one module: the beds under everything, the voices,
/// and the stingers. <see cref="SumpPresentation"/> adds it at runtime. Play mode only.
///
///   - Beds: one looping ambience per place, crossfaded as <see cref="Sump.Mode"/> and the
///     flashback's genre change: wind in the arrival, the cavern's drone (with stray drips) in the
///     hub, a bed per flashback genre, and in the finale a deep bed plus the planet's heartbeat,
///     which follows <see cref="SumpFinale.HeartPulse"/>.
///   - Panic: ears ringing as <see cref="Sump.Calm"/> runs out, and the beds ducking under it.
///     (The heartbeat and the breathing are the trauma module's; this only adds to them.)
///   - Voices: every spoken line (<see cref="Sump.Said"/>) is read out as a run of short pitched
///     blips, the pitch and the blip taken from the speaker, so each misfit has its own voice.
///     Narration with no speaker is silent.
///   - Stingers on mode changes and when a misfit is healed.
///
/// Every sound is in Assets/sounds/sump/, made by tools/make_sump_sounds.py. A sound that is
/// missing is simply not heard.
/// </summary>
[Title( "Sump Audio" ), Category( "Sump" ), Icon( "graphic_eq" )]
public sealed class SumpAudio : Component
{
	// ---- Beds -----------------------------------------------------------------------------------
	[Property, Group( "Beds" ), Range( 0f, 2f )] public float MasterVolume { get; set; } = 1f;
	[Property, Group( "Beds" ), Range( 0f, 2f )] public float CavernVolume { get; set; } = 0.55f;
	[Property, Group( "Beds" ), Range( 0f, 2f )] public float WindVolume { get; set; } = 0.5f;
	[Property, Group( "Beds" ), Range( 0f, 2f )] public float FarmVolume { get; set; } = 0.5f;
	[Property, Group( "Beds" ), Range( 0f, 2f )] public float LabVolume { get; set; } = 0.4f;
	[Property, Group( "Beds" ), Range( 0f, 2f )] public float StudioVolume { get; set; } = 0.45f;
	[Property, Group( "Beds" ), Range( 0f, 2f )] public float FinaleVolume { get; set; } = 0.7f;
	/// <summary>
	/// The swell under the planet's heartbeat, between beats and on the beat. The finale plays the
	/// beat itself ("heart_beat"); this bed has no beat of its own and only follows the real pulse.
	/// </summary>
	[Property, Group( "Beds" )] public Vector2 HeartVolume { get; set; } = new( 0.04f, 0.9f );
	/// <summary>Seconds a bed takes to come in or go out.</summary>
	[Property, Group( "Beds" )] public float CrossfadeSeconds { get; set; } = 2.5f;
	/// <summary>How much of the cavern's bed is still heard during the arrival's fall.</summary>
	[Property, Group( "Beds" ), Range( 0f, 1f )] public float CavernInArrival { get; set; } = 0.3f;
	/// <summary>Beds are turned down to this while the player has the radio's headphones on.</summary>
	[Property, Group( "Beds" ), Range( 0f, 1f )] public float RadioDuck { get; set; } = 0.35f;
	/// <summary>Beds are turned down to this under a black screen.</summary>
	[Property, Group( "Beds" ), Range( 0f, 1f )] public float FadeDuck { get; set; } = 0.5f;

	/// <summary>Seconds between stray drips in the hub: shortest and longest gap.</summary>
	[Property, Group( "Drips" )] public Vector2 DripGap { get; set; } = new( 1.8f, 7f );
	/// <summary>How far from the player a drip falls: nearest and furthest.</summary>
	[Property, Group( "Drips" )] public Vector2 DripDistance { get; set; } = new( 250f, 1300f );
	[Property, Group( "Drips" ), Range( 0f, 2f )] public float DripVolume { get; set; } = 0.6f;

	// ---- Panic ----------------------------------------------------------------------------------
	/// <summary>Calm under which the ears start to ring.</summary>
	[Property, Group( "Panic" ), Range( 0f, 1f )] public float RingFrom { get; set; } = 0.55f;
	[Property, Group( "Panic" ), Range( 0f, 2f )] public float RingVolume { get; set; } = 0.5f;
	/// <summary>Beds are turned down to this at no calm at all.</summary>
	[Property, Group( "Panic" ), Range( 0f, 1f )] public float PanicDuck { get; set; } = 0.35f;

	// ---- Voices ---------------------------------------------------------------------------------
	[Property, Group( "Voices" )] public bool VoiceBlips { get; set; } = true;
	[Property, Group( "Voices" ), Range( 0f, 2f )] public float BlipVolume { get; set; } = 0.55f;
	/// <summary>Letters of a line per blip.</summary>
	[Property, Group( "Voices" )] public float LettersPerBlip { get; set; } = 5f;
	/// <summary>Fewest and most blips for one line.</summary>
	[Property, Group( "Voices" )] public Vector2 BlipCount { get; set; } = new( 3f, 14f );
	/// <summary>Seconds between blips: shortest and longest (each speaker has its own pace between them).</summary>
	[Property, Group( "Voices" )] public Vector2 BlipGap { get; set; } = new( 0.055f, 0.1f );
	/// <summary>Lowest and highest voice a misfit can have, as playback pitch.</summary>
	[Property, Group( "Voices" )] public Vector2 MisfitPitch { get; set; } = new( 0.7f, 1.7f );
	/// <summary>Lowest and highest voice of anybody else (humans, the intercom, the Sump itself).</summary>
	[Property, Group( "Voices" )] public Vector2 OtherPitch { get; set; } = new( 0.5f, 0.85f );
	/// <summary>How far each blip strays from the speaker's pitch, as a fraction.</summary>
	[Property, Group( "Voices" ), Range( 0f, 0.5f )] public float BlipSing { get; set; } = 0.12f;

	// ---- Stingers -------------------------------------------------------------------------------
	[Property, Group( "Stingers" ), Range( 0f, 2f )] public float StingerVolume { get; set; } = 0.8f;
	/// <summary>Seconds after a misfit is healed that the chime plays (the flashback's own return sound goes first).</summary>
	[Property, Group( "Stingers" )] public float HealChimeDelay { get; set; } = 1.6f;

	const string Folder = "sounds/sump/";

	/// <summary>A looping sound with no position whose volume glides to a target. Silent, and soon gives up, if the sound is missing.</summary>
	sealed class Bed
	{
		public readonly string Name;
		public float Level;      // 0..1, where the crossfade is
		public float Target;     // 0..1, where it is going
		public float Volume;     // what full level means, from the properties
		public float Pitch = 1f;
		SoundHandle _handle;
		float _nextTry;
		int _fails;

		public Bed( string name ) { Name = name; }

		public void Update( float step, float master )
		{
			Level = Level < Target ? MathF.Min( Level + step, Target ) : MathF.Max( Level - step, Target );
			float volume = Level * Volume * master;
			try
			{
				if ( volume <= 0.002f )
				{
					if ( Target <= 0f ) Stop();
					else if ( Playing ) _handle.Volume = 0f;
					return;
				}

				if ( !Playing && _fails < 3 && RealTime.Now >= _nextTry )
				{
					_nextTry = RealTime.Now + 1.5f;
					_handle = Sound.Play( Folder + Name + ".sound" );
					if ( !Playing ) { _fails++; _handle = null; }
				}
				if ( !Playing ) return;
				_handle.Volume = volume;
				_handle.Pitch = Pitch;
			}
			catch ( Exception ) { _fails = 99; _handle = null; }
		}

		bool Playing => _handle is not null && _handle.IsValid() && !_handle.IsStopped;

		public void Stop( float fade = 0.4f )
		{
			try { if ( Playing ) _handle.Stop( fade ); }
			catch ( Exception ) { }
			_handle = null;
		}
	}

	readonly Bed _cavern = new( "amb_cavern_loop" );
	readonly Bed _wind = new( "amb_wind_loop" );
	readonly Bed _farm = new( "amb_farm_loop" );
	readonly Bed _lab = new( "amb_lab_loop" );
	readonly Bed _studio = new( "amb_studio_loop" );
	readonly Bed _finale = new( "amb_finale_loop" );
	readonly Bed _heart = new( "finale_heart_loop" );
	readonly Bed _ring = new( "panic_ring_loop" );
	Bed[] _beds;

	SumpMode _mode;
	bool _modeKnown;
	bool _listening;
	TimeUntil _nextDrip;
	float _healChimeAt = -1f;
	float _stingAt = -1f;
	string _stingName;

	// The line being read out.
	int _blipsLeft;
	float _nextBlipAt;
	float _blipPitch = 1f, _blipGap = 0.07f;
	int _blipSound = 1;
	uint _blipState;

	protected override void OnEnabled()
	{
		if ( Scene.IsEditor ) return;
		_beds = new[] { _cavern, _wind, _farm, _lab, _studio, _finale, _heart, _ring };
		Sump.Said += OnSaid;
		SumpState.MisfitHealed += OnHealed;
		_listening = true;
		_nextDrip = 3f;
	}

	protected override void OnDisabled()
	{
		if ( _listening )
		{
			Sump.Said -= OnSaid;
			SumpState.MisfitHealed -= OnHealed;
			_listening = false;
		}
		if ( _beds is not null )
			foreach ( var bed in _beds ) bed.Stop( 0.2f );
	}

	protected override void OnUpdate()
	{
		if ( Scene.IsEditor || _beds is null ) return;

		var mode = Sump.Mode;
		if ( !_modeKnown ) { _mode = mode; _modeKnown = true; }
		else if ( mode != _mode ) { OnModeChanged( _mode, mode ); _mode = mode; }

		UpdateBeds( mode );
		UpdateDrips( mode );
		UpdateBlips();
		UpdateStingers();
	}

	// ---- Beds -----------------------------------------------------------------------------------

	void UpdateBeds( SumpMode mode )
	{
		FlashbackGenre? genre = null;
		if ( mode == SumpMode.Flashback )
			genre = (FlashbackRunner.Current.IsValid() ? FlashbackRunner.Current.Profile : null)?.Genre ?? Sump.ActiveFlashback?.Genre;

		_cavern.Volume = CavernVolume;
		_wind.Volume = WindVolume;
		_farm.Volume = FarmVolume;
		_lab.Volume = LabVolume;
		_studio.Volume = StudioVolume;
		_finale.Volume = FinaleVolume;
		_ring.Volume = RingVolume;

		_cavern.Target = mode == SumpMode.Hub ? 1f : mode == SumpMode.Arrival ? CavernInArrival : 0f;
		_wind.Target = mode == SumpMode.Arrival ? 1f : 0f;
		_farm.Target = genre == FlashbackGenre.FarmHorror ? 1f : 0f;
		_lab.Target = genre == FlashbackGenre.LabEscape ? 1f : 0f;
		_studio.Target = genre == FlashbackGenre.TalkShow ? 1f : 0f;
		_finale.Target = mode == SumpMode.Finale ? 1f : mode == SumpMode.Ended ? 0.35f : 0f;
		_heart.Target = mode == SumpMode.Finale ? 1f : 0f;

		// The heart is felt as much as heard: louder and a touch higher on each beat.
		float pulse = mode == SumpMode.Finale ? SumpPresentation.HeartPulse : 0f;
		_heart.Volume = HeartVolume.x + (HeartVolume.y - HeartVolume.x) * pulse;
		_heart.Pitch = 1f + 0.04f * pulse;

		float calm = Math.Clamp( Sump.Calm, 0f, 1f );
		_ring.Target = RingFrom <= 0f ? 0f : Math.Clamp( (RingFrom - calm) / RingFrom, 0f, 1f );
		_ring.Pitch = 1f + 0.06f * _ring.Target;

		// Everything else gives way to panic, to the radio and to a black screen.
		float duck = PanicDuck + (1f - PanicDuck) * calm;
		if ( SumpHub.Radio is { PlayerListening: true } ) duck *= RadioDuck;
		duck *= 1f - (1f - FadeDuck) * Math.Clamp( Sump.Fade, 0f, 1f );

		float step = Time.Delta / MathF.Max( CrossfadeSeconds, 0.05f );
		foreach ( var bed in _beds )
			bed.Update( bed == _ring ? step * 3f : step, MasterVolume * (bed == _ring || bed == _heart ? 1f : duck) );
	}

	void UpdateDrips( SumpMode mode )
	{
		if ( mode != SumpMode.Hub || !_nextDrip || DripVolume <= 0f ) return;
		_nextDrip = Game.Random.Float( DripGap.x, MathF.Max( DripGap.y, DripGap.x ) );
		if ( !Sump.Player.IsValid() || !SumpCavern.HubVisible ) return;

		float angle = Game.Random.Float( 0f, MathF.PI * 2f );
		float distance = Game.Random.Float( DripDistance.x, MathF.Max( DripDistance.y, DripDistance.x ) );
		var at = Sump.Player.WorldPosition + new Vector3( MathF.Cos( angle ) * distance, MathF.Sin( angle ) * distance, Game.Random.Float( -20f, 60f ) );
		Play( $"amb_drip_{Game.Random.Int( 1, 3 )}", at, DripVolume * MasterVolume );
	}

	// ---- Voices ---------------------------------------------------------------------------------

	void OnSaid( string speaker, string text )
	{
		if ( !VoiceBlips || string.IsNullOrWhiteSpace( speaker ) || string.IsNullOrEmpty( text ) ) return;

		var profile = SumpUi.SumpHud.FindSpeaker( speaker );
		int seed = profile is not null ? profile.Seed : StableHash( speaker );
		float where = (MisfitGenerator.Mix( seed, 0x5EED, 1 ) & 0xFFFF) / 65535f;
		var range = profile is not null ? MisfitPitch : OtherPitch;

		_blipPitch = range.x + (range.y - range.x) * where;
		// Big ones speak lower, small ones higher.
		if ( profile is not null ) _blipPitch /= Math.Clamp( MathF.Sqrt( MathF.Max( profile.Size, 0.2f ) ), 0.7f, 1.4f );
		_blipSound = profile is not null ? 1 + (MisfitGenerator.Mix( seed, 0xB11B, 2 ) & 0x7FFF) % 3 : 1;
		_blipGap = BlipGap.x + (BlipGap.y - BlipGap.x) * ((MisfitGenerator.Mix( seed, 0x9ACE, 3 ) & 0xFFFF) / 65535f);
		// A whisperer whispers; a stutterer takes longer over it.
		if ( profile?.SpeechTic == "stutter" ) _blipGap *= 1.3f;

		_blipsLeft = (int)Math.Clamp( text.Length / MathF.Max( LettersPerBlip, 1f ), BlipCount.x, MathF.Max( BlipCount.y, BlipCount.x ) );
		_blipState = (uint)StableHash( text ) | 1u;
		_blipWhisper = profile?.SpeechTic == "whisper";
		_nextBlipAt = RealTime.Now + 0.03f;
	}

	bool _blipWhisper;

	void UpdateBlips()
	{
		if ( _blipsLeft <= 0 || RealTime.Now < _nextBlipAt ) return;
		_blipsLeft--;

		// A small fixed melody per line, from the text itself.
		_blipState ^= _blipState << 13; _blipState ^= _blipState >> 17; _blipState ^= _blipState << 5;
		float sing = ((_blipState & 0xFFFF) / 65535f) * 2f - 1f;
		bool pause = (_blipState >> 20) % 7 == 0;
		_nextBlipAt = RealTime.Now + _blipGap * (pause ? 2.4f : 1f);

		var at = Sump.Player.IsValid() ? Sump.Player.WorldPosition + Vector3.Up * 40f : WorldPosition;
		var handle = Play( $"misfit_blip_{_blipSound}", at, BlipVolume * MasterVolume * (_blipWhisper ? 0.45f : 1f) );
		try { if ( handle is not null ) handle.Pitch = MathF.Max( _blipPitch * (1f + BlipSing * sing), 0.2f ); }
		catch ( Exception ) { }
	}

	static int StableHash( string text )
	{
		unchecked
		{
			uint h = 2166136261;
			foreach ( char c in text ?? "" ) h = (h ^ c) * 16777619;
			return (int)(h & 0x7FFFFFFF);
		}
	}

	// ---- Stingers -------------------------------------------------------------------------------

	void OnModeChanged( SumpMode from, SumpMode to )
	{
		// Arrival has the cavern's own title sting and a flashback has the runner's own sounds
		// going in, so only the changes nobody else marks get one here.
		switch ( to )
		{
			case SumpMode.Hub when from == SumpMode.Flashback || from == SumpMode.Finale: Sting( "sting_hub", 1.2f ); break;
			case SumpMode.Finale: Sting( "sting_finale", 0.5f ); break;
			case SumpMode.Ended: Sting( "sting_ended", 0.3f ); break;
		}
	}

	void Sting( string name, float delay )
	{
		_stingName = name;
		_stingAt = RealTime.Now + delay;
	}

	void OnHealed( MisfitProfile profile )
	{
		_healChimeAt = RealTime.Now + MathF.Max( HealChimeDelay, 0f );
	}

	void UpdateStingers()
	{
		var at = Sump.Player.IsValid() ? Sump.Player.WorldPosition : WorldPosition;
		if ( _stingAt >= 0f && RealTime.Now >= _stingAt )
		{
			_stingAt = -1f;
			Play( _stingName, at, StingerVolume * MasterVolume );
		}
		if ( _healChimeAt >= 0f && RealTime.Now >= _healChimeAt )
		{
			_healChimeAt = -1f;
			Play( "heal_chime", at, StingerVolume * MasterVolume );
		}
	}

	/// <summary>Plays a Sump sound by short name. Null if it is missing.</summary>
	static SoundHandle Play( string name, Vector3 position, float volume )
	{
		if ( string.IsNullOrEmpty( name ) || volume <= 0f ) return null;
		try
		{
			var handle = Sump.Sfx( name, position, volume );
			return handle.IsValid() ? handle : null;
		}
		catch ( Exception ) { return null; }
	}
}