Rampage/Game/RampageAudio.cs

Audio director for the Rampage game mode. Runs four synchronized music loops whose layers fade in by tier and pitch up as the tier rises, glides panic and siren beds by game state, and plays stingers off Rampage events (scored, tier up, shockwave) and RampageGame cues.

using System;
using System.Collections.Generic;

/// <summary>
/// The sound of the Rampage that belongs to no one module. <see cref="RampageGame"/> adds it at
/// runtime. Play mode only.
///
///   - Music: four loops of the same length cut from one tune (oompah, drums, the tune, brass).
///     All four start together and never stop, so they stay in step; each is turned up when its
///     tier is reached, and the whole band plays a little faster with every tier.
///   - Beds: the town panicking (louder the more people have just been flung) and far-off sirens
///     from a tier of your choosing.
///   - Stingers: a fanfare for every tier, each more pompous than the last; combo milestones,
///     bonuses, milestones, the results; a small arcade ding for every score worth a bigger line
///     in the feed; a slide whistle now and then for a person in flight; a boom under shockwaves.
///
/// The hits themselves (whip, slam, crash, scream) are played by the modules that cause them.
/// Every sound is in Assets/sounds/rampage/, made by tools/make_rampage_sounds.py. A sound that
/// is missing is simply not heard.
/// </summary>
[Title( "Rampage Audio" ), Category( "Rampage" ), Icon( "graphic_eq" )]
public sealed class RampageAudio : Component
{
	[Property, Range( 0f, 2f )] public float MasterVolume { get; set; } = 1f;

	// ---- Music ----------------------------------------------------------------------------------
	[Property, Group( "Music" ), Range( 0f, 2f )] public float MusicVolume { get; set; } = 0.5f;
	/// <summary>The tier at which each of the four layers comes in.</summary>
	[Property, Group( "Music" )] public int[] LayerTiers { get; set; } = { 0, 1, 2, 4 };
	/// <summary>How much faster (and higher) the band plays per tier, and the most it ever does.</summary>
	[Property, Group( "Music" )] public Vector2 SpeedUp { get; set; } = new( 0.02f, 0.14f );
	/// <summary>Seconds a layer takes to come in.</summary>
	[Property, Group( "Music" )] public float LayerFadeSeconds { get; set; } = 1.5f;
	/// <summary>Music is turned down to this under the results.</summary>
	[Property, Group( "Music" ), Range( 0f, 1f )] public float ResultsDuck { get; set; } = 0.45f;

	// ---- Beds -----------------------------------------------------------------------------------
	[Property, Group( "Beds" ), Range( 0f, 2f )] public float PanicVolume { get; set; } = 0.55f;
	[Property, Group( "Beds" ), Range( 0f, 2f )] public float SirenVolume { get; set; } = 0.22f;
	[Property, Group( "Beds" )] public int SirensFromTier { get; set; } = 2;

	// ---- Stingers -------------------------------------------------------------------------------
	[Property, Group( "Stingers" ), Range( 0f, 2f )] public float StingerVolume { get; set; } = 0.85f;
	/// <summary>The arcade ding on a score. 0 for none.</summary>
	[Property, Group( "Stingers" ), Range( 0f, 2f )] public float DingVolume { get; set; } = 0.35f;
	/// <summary>Scores under this many points make no ding.</summary>
	[Property, Group( "Stingers" )] public float DingFromPoints { get; set; } = 60f;
	/// <summary>The slide whistle for a person in flight. 0 for none.</summary>
	[Property, Group( "Stingers" ), Range( 0f, 2f )] public float WhistleVolume { get; set; } = 0.3f;
	/// <summary>Least seconds between two slide whistles.</summary>
	[Property, Group( "Stingers" )] public float WhistleGap { get; set; } = 1.6f;
	/// <summary>The boom under a shockwave, on top of whatever the weapon plays. 0 for none.</summary>
	[Property, Group( "Stingers" ), Range( 0f, 2f )] public float ShockVolume { get; set; } = 0.6f;

	/// <summary>A looping sound with no position whose volume glides to a target.</summary>
	sealed class Loop
	{
		public readonly string Name;
		public float Level, Target;
		public SoundHandle Handle;
		public Loop( string name ) { Name = name; }
		public bool Playing => Handle is not null && Handle.IsValid() && !Handle.IsStopped;

		public void Start()
		{
			Stop();
			Handle = Rampage.PlaySound( Name );
			if ( Playing ) Handle.Volume = 0f;
		}

		public void Set( float volume, float pitch )
		{
			if ( !Playing ) return;
			Handle.Volume = MathF.Max( volume, 0f );
			Handle.Pitch = pitch;
		}

		public void Stop( float fade = 0.3f )
		{
			if ( Playing ) Handle.Stop( fade );
			Handle = null;
		}
	}

	readonly Loop[] _music = { new( "music_0_loop" ), new( "music_1_loop" ), new( "music_2_loop" ), new( "music_3_loop" ) };
	readonly Loop _panic = new( "crowd_panic_loop" );
	readonly Loop _siren = new( "siren_loop" );
	bool _musicOn;
	int _musicStarts;
	float _nextMusicTry;
	float _nextDing, _nextWhistle;
	int _humansSeen;
	bool _listening;
	RampageGame _game;

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

	protected override void OnDisabled()
	{
		if ( _listening )
		{
			Rampage.Scored -= OnScored;
			Rampage.TierUp -= OnTierUp;
			Rampage.Shockwave -= OnShockwave;
			_listening = false;
		}
		if ( _game.IsValid() ) _game.Cue -= OnCue;
		_game = null;
		foreach ( var loop in _music ) loop.Stop();
		_panic.Stop();
		_siren.Stop();
		_musicOn = false;
	}

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

		var game = RampageGame.Current;
		if ( game != _game )
		{
			if ( _game.IsValid() ) _game.Cue -= OnCue;
			_game = game;
			if ( _game.IsValid() ) _game.Cue += OnCue;
		}
		if ( !game.IsValid() ) return;

		// No intro to wait for: strike up at once.
		if ( !_musicOn && game.Phase == RampagePhase.Rampage ) _musicOn = true;

		float dt = Math.Clamp( RealTime.Delta, 0f, 0.1f );
		UpdateMusic( game, dt );
		UpdateBeds( game, dt );
	}

	// ---- Music and beds ---------------------------------------------------------------------------

	void UpdateMusic( RampageGame game, float dt )
	{
		if ( !_musicOn || MusicVolume <= 0f ) return;

		// All four start on the same frame, and again together if any of them has stopped.
		bool allPlaying = true;
		foreach ( var loop in _music ) allPlaying &= loop.Playing;
		if ( !allPlaying )
		{
			if ( _musicStarts >= 4 || RealTime.Now < _nextMusicTry ) return;
			_musicStarts++;
			_nextMusicTry = RealTime.Now + 2f;
			foreach ( var loop in _music ) loop.Start();
		}

		int tier = Rampage.Tier;
		float pitch = 1f + MathF.Min( tier * SpeedUp.x, SpeedUp.y );
		float duck = game.ShowResults ? ResultsDuck : 1f;
		float step = dt / MathF.Max( LayerFadeSeconds, 0.05f );
		for ( int i = 0; i < _music.Length; i++ )
		{
			var loop = _music[i];
			int from = LayerTiers is not null && i < LayerTiers.Length ? LayerTiers[i] : i;
			loop.Target = tier >= from ? 1f : 0f;
			loop.Level = loop.Level < loop.Target ? MathF.Min( loop.Level + step, loop.Target ) : MathF.Max( loop.Level - step, loop.Target );
			loop.Set( loop.Level * MusicVolume * MasterVolume * duck, pitch );
		}
	}

	void UpdateBeds( RampageGame game, float dt )
	{
		bool running = game.Phase == RampagePhase.Rampage;
		Glide( _panic, running ? Math.Clamp( game.Panic, 0f, 1f ) : 0f, PanicVolume, 1f + 0.08f * game.Panic, dt * 1.5f );
		Glide( _siren, running && Rampage.Tier >= SirensFromTier ? 1f : 0f, SirenVolume, 1f, dt * 0.4f );
	}

	/// <summary>Moves a bed toward a level, starting it when it is first wanted and stopping it when it has faded out.</summary>
	void Glide( Loop loop, float target, float volume, float pitch, float step )
	{
		loop.Target = volume > 0f ? target : 0f;
		loop.Level = loop.Level < loop.Target ? MathF.Min( loop.Level + step, loop.Target ) : MathF.Max( loop.Level - step, loop.Target );
		if ( loop.Level <= 0.002f )
		{
			if ( loop.Target <= 0f && loop.Playing ) loop.Stop();
			return;
		}
		if ( !loop.Playing )
		{
			if ( RealTime.Now < _nextBedTry ) return;
			_nextBedTry = RealTime.Now + 2f;
			loop.Start();
		}
		loop.Set( loop.Level * volume * MasterVolume, pitch );
	}

	float _nextBedTry, _nextShock;

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

	void OnCue( string cue, int number )
	{
		switch ( cue )
		{
			case "title": Play( "title_sting", StingerVolume ); break;
			case "go": _musicOn = true; break;
			case "combo":
				// Each milestone a step higher than the last.
				int step = Math.Max( Array.IndexOf( RampageNews.ComboMilestones, number ), 0 );
				Play( "combo_up", StingerVolume, 1f + step * 0.09f );
				break;
			case "combo_break": Play( "combo_break", StingerVolume * 0.8f ); break;
			case "bonus": Play( "kaching", StingerVolume * 0.8f ); break;
			case "milestone": Play( "milestone", StingerVolume ); break;
			case "results": Play( "results_stamp", StingerVolume ); break;
			case "record": Play( "record", StingerVolume ); break;
			case "tick": Play( "news_tick", StingerVolume * 0.35f ); break;
		}
	}

	static readonly string[] Fanfares = { "fanfare_1", "fanfare_2", "fanfare_3", "fanfare_4", "fanfare_5", "fanfare_6" };

	void OnTierUp( int tier )
	{
		Play( Fanfares[Math.Clamp( tier, 1, 6 ) - 1], StingerVolume );
	}

	void OnScored( Vector3 at, float points, string label )
	{
		float now = RealTime.Now;
		bool human = Rampage.HumansSent != _humansSeen;
		_humansSeen = Rampage.HumansSent;

		if ( human && WhistleVolume > 0f && now >= _nextWhistle )
		{
			_nextWhistle = now + MathF.Max( WhistleGap, 0.2f );
			Play( "slide_whistle_up", WhistleVolume, Game.Random.Float( 0.9f, 1.2f ) );
		}

		if ( DingVolume > 0f && points >= DingFromPoints && now >= _nextDing )
		{
			_nextDing = now + 0.09f;
			// Bigger scores ring lower and longer; a chain rings higher as it goes.
			float size = Math.Clamp( MathF.Log10( MathF.Max( points, 10f ) ) - 1.5f, 0f, 2f );
			int combo = _game.IsValid() ? Math.Min( _game.Combo, 24 ) : 0;
			Play( size > 1.2f ? "score_big" : "score_ding", DingVolume * (0.7f + 0.3f * size), 1f + combo * 0.02f );
		}
	}

	void OnShockwave( Vector3 centre, float radius, float speed )
	{
		if ( ShockVolume <= 0f ) return;
		// One boom at a time is plenty: a cracked street sends a dozen waves in a second.
		if ( RealTime.Now < _nextShock ) return;
		_nextShock = RealTime.Now + 0.07f;
		var handle = Rampage.PlaySound( "shock_boom", centre );
		if ( handle is null ) return;
		handle.Volume = ShockVolume * MasterVolume * Math.Clamp( radius / 800f, 0.4f, 1.3f );
		handle.Pitch = Math.Clamp( 1.25f - radius / 3000f, 0.7f, 1.25f );
	}

	/// <summary>Plays a Rampage sound with no position, by short name. Null if it is missing.</summary>
	SoundHandle Play( string name, float volume, float pitch = 1f )
	{
		if ( string.IsNullOrEmpty( name ) || volume <= 0f ) return null;
		var handle = Rampage.PlaySound( name );
		if ( handle is null ) return null;
		handle.Volume = volume * MasterVolume;
		if ( pitch != 1f ) handle.Pitch = pitch;
		return handle;
	}
}