Files

290 lines
12 KiB
C#

using System;
using UnityEngine;
namespace BigShipTycoon
{
internal enum PassageAnnouncement { Departure, Dining, DiningSpecial, Bar, Show, Terrace, Approach }
internal sealed class PassageAudio : MonoBehaviour
{
private const int SampleRate = 22050;
private static readonly string[] Announcements =
{
"Welcome aboard. We have cleared the berth and are now under way. On behalf of the captain and crew, enjoy your voyage.",
"May I have your attention, please. We have opened an additional seating in the main dining room.",
"For a limited time, specialty dining is available at a reduced price. Please ask your dining team for details.",
"Ladies and gentlemen, happy hour has started at the bar. We look forward to seeing you there.",
"Our next performance is starting shortly. Please join us for live entertainment.",
"Join us on the pool terrace. Our crew is ready to get the next deck activity under way."
};
private AudioSource wind, engine, effects, voice;
private AudioClip step, hardStep, confirmation;
private AudioClip departureForPort, approachForPort;
private readonly AudioClip[] spoken = new AudioClip[Announcements.Length];
private readonly float[] repeatAfter = new float[(int)PassageAnnouncement.Approach + 1];
private float distanceSinceStep;
private float announcementTime, announcementGap, announcementClock;
private bool leftFoot, crossing, voicePaused, approachSent;
private PassageAnnouncement? currentAnnouncement, pendingAnnouncement;
private string nextPort;
internal PassageAnnouncement? CurrentAnnouncement => currentAnnouncement;
internal float ApproachSeconds => approachForPort != null ? approachForPort.length : 0;
internal bool ApproachSent => approachSent;
internal string Caption => currentAnnouncement switch
{
PassageAnnouncement.Departure when departureForPort != null => $"Welcome aboard. We are now under way, and our next port of call is {nextPort}.",
PassageAnnouncement.Approach => $"May I have your attention, please. We are approaching {nextPort}.",
PassageAnnouncement line => Announcements[(int)line],
_ => null
};
internal void Initialize()
{
if (FindAnyObjectByType<AudioListener>() == null)
gameObject.AddComponent<AudioListener>();
wind = Source(MakeBed("Sea wash", false));
engine = Source(MakeBed("Propulsion and ventilation", true));
effects = Source(null);
effects.volume = .72f;
step = MakeStep(false);
hardStep = MakeStep(true);
confirmation = MakeClip("Crew acknowledgement", .22f, t =>
{
float first = Pulse(t, 0, .09f) * Mathf.Sin(t * 716 * Mathf.PI * 2);
float second = Pulse(t, .074f, .14f) * Mathf.Sin(t * 958 * Mathf.PI * 2);
return (first + second * .75f) * .12f;
});
var address = new GameObject("Ship public address");
address.transform.SetParent(transform, false);
voice = address.AddComponent<AudioSource>();
voice.playOnAwake = false;
voice.spatialBlend = 0;
voice.volume = .95f;
address.AddComponent<AudioHighPassFilter>().cutoffFrequency = 165;
address.AddComponent<AudioLowPassFilter>().cutoffFrequency = 4300;
for (int i = 0; i < spoken.Length; i++)
spoken[i] = Resources.Load<AudioClip>($"Audio/PA/{(PassageAnnouncement)i}");
}
internal void Begin(int destination, bool announceDeparture = true, bool approachAnnounced = false)
{
End();
crossing = true;
approachSent = approachAnnounced;
nextPort = Market.Ports[destination].Name;
departureForPort = LoadPortClip("Departure", destination);
approachForPort = LoadPortClip("Approach", destination);
distanceSinceStep = 0;
announcementClock = announcementGap = 0;
Array.Clear(repeatAfter, 0, repeatAfter.Length);
if (!wind.isPlaying)
wind.Play();
if (!engine.isPlaying)
engine.Play();
if (announceDeparture)
Announce(PassageAnnouncement.Departure);
}
internal void End()
{
crossing = false;
voice.Stop();
voicePaused = false;
currentAnnouncement = pendingAnnouncement = null;
departureForPort = approachForPort = null;
voice.clip = null;
}
internal void Announce(PassageAnnouncement line)
{
int index = (int)line;
if (!crossing || ClipFor(line) == null || currentAnnouncement == line || pendingAnnouncement == line
|| repeatAfter[index] > announcementClock)
return;
if (currentAnnouncement.HasValue || announcementGap > 0 || voicePaused)
pendingAnnouncement = line;
else
PlayAnnouncement(line);
}
internal void AnnounceApproach()
{
if (!crossing || approachSent || approachForPort == null)
return;
approachSent = true;
pendingAnnouncement = null;
announcementGap = 0;
voice.Stop();
PlayAnnouncement(PassageAnnouncement.Approach);
}
internal static AudioClip LoadPortClip(string announcement, int destination) =>
Resources.Load<AudioClip>($"Audio/PA/{announcement}Port{destination:D2}");
private AudioClip ClipFor(PassageAnnouncement line) => line switch
{
PassageAnnouncement.Departure when departureForPort != null => departureForPort,
PassageAnnouncement.Approach => approachForPort,
_ => spoken[(int)line]
};
internal void Mix(float delta, bool active, float knots, WeatherCondition weather, bool indoors, bool engineering)
{
UpdateAnnouncements(delta, active);
float pace = Mathf.Clamp01(knots / 21);
float storm = (int)weather / 2f;
float sea = active ? (.12f + pace * .17f + storm * .14f) * (indoors ? .19f : 1) : 0;
float motor = active ? (.035f + pace * .15f) * (engineering ? 1.65f : indoors ? .60f : .72f) : 0;
if (currentAnnouncement.HasValue)
{
sea *= .54f;
motor *= .60f;
}
wind.volume = Mathf.MoveTowards(wind.volume, sea, delta * .58f);
engine.volume = Mathf.MoveTowards(engine.volume, motor, delta * .58f);
engine.pitch = .84f + pace * .32f;
if (!crossing && wind.volume == 0 && engine.volume == 0)
{
if (wind.isPlaying)
wind.Stop();
if (engine.isPlaying)
engine.Stop();
}
}
private void PlayAnnouncement(PassageAnnouncement line)
{
int index = (int)line;
currentAnnouncement = line;
voice.clip = ClipFor(line);
announcementTime = voice.clip.length;
repeatAfter[index] = announcementClock + 20f;
voice.Play();
}
private void UpdateAnnouncements(float delta, bool active)
{
if (!crossing)
return;
if (!active)
{
if (!voicePaused)
voice.Pause();
voicePaused = true;
return;
}
if (voicePaused)
{
voice.UnPause();
voicePaused = false;
}
announcementClock += delta;
if (currentAnnouncement.HasValue)
{
announcementTime -= delta;
if (announcementTime <= 0)
{
currentAnnouncement = null;
announcementGap = .44f;
}
return;
}
announcementGap = Mathf.Max(0, announcementGap - delta);
if (announcementGap == 0 && pendingAnnouncement is PassageAnnouncement next)
{
pendingAnnouncement = null;
PlayAnnouncement(next);
}
}
internal void Step(float distance, bool metal)
{
distanceSinceStep += distance;
if (distanceSinceStep < .65f)
return;
distanceSinceStep -= .65f;
leftFoot = !leftFoot;
effects.pitch = leftFoot ? .96f : 1.04f;
effects.PlayOneShot(metal ? hardStep : step, metal ? .46f : .36f);
}
internal void Confirm()
{
effects.pitch = 1;
effects.PlayOneShot(confirmation, .66f);
}
private AudioSource Source(AudioClip clip)
{
var source = gameObject.AddComponent<AudioSource>();
source.playOnAwake = false;
source.loop = clip != null;
source.clip = clip;
source.volume = 0;
source.spatialBlend = 0;
return source;
}
private static AudioClip MakeBed(string name, bool motor)
{
uint state = motor ? 5193u : 1996u;
float filtered = 0;
const float seconds = 6;
return MakeClip(name, seconds, t =>
{
filtered += (Noise(ref state) - filtered) * (motor ? .014f : .075f);
float seam = Mathf.Clamp01(Mathf.Min(t, seconds - t) * 16);
float wave = .68f + .18f * Mathf.Cos(t * Mathf.PI * 2 / seconds) + .11f * Mathf.Sin(t * Mathf.PI * 4 / seconds);
if (!motor)
return filtered * .74f * wave * seam;
float propeller = .16f * Mathf.Sin(t * 46 * Mathf.PI * 2) + .073f * Mathf.Sin(t * 92 * Mathf.PI * 2)
+ .041f * Mathf.Sin(t * 131 * Mathf.PI * 2);
return propeller * wave + filtered * .36f * seam;
});
}
private static AudioClip MakeStep(bool metal)
{
uint state = metal ? 572u : 728u;
float filtered = 0;
return MakeClip(metal ? "Steel deck footfall" : "Carpet footfall", .14f, t =>
{
float grit = Noise(ref state);
filtered += (grit - filtered) * .14f;
float impact = Mathf.Sin(t * (metal ? 123 : 94) * Mathf.PI * 2) * Pulse(t, 0, .078f) * .36f;
float scuff = (metal ? grit * .22f : filtered * .53f) * Pulse(t, .015f, .12f);
return impact + scuff;
});
}
private static AudioClip MakeClip(string name, float seconds, Func<float, float> waveform)
{
var data = new float[Mathf.CeilToInt(seconds * SampleRate)];
for (int i = 0; i < data.Length; i++)
data[i] = waveform((float)i / SampleRate);
AudioClip clip = AudioClip.Create(name, data.Length, 1, SampleRate, false);
clip.SetData(data, 0);
return clip;
}
private static float Pulse(float time, float start, float length)
{
float progress = Mathf.Clamp01((time - start) / length);
return Mathf.Min(1, progress * 20) * (1 - progress) * (1 - progress);
}
private static float Noise(ref uint state)
{
state = unchecked(state * 1664525u + 1013904223u);
return (state >> 8) * (2f / 16777215) - 1;
}
}
}