Files
isaac-port/src/music_manager.cpp
T

673 lines
23 KiB
C++

#include "music_manager.h"
#include "data.h"
#include "game.h"
#include "manager.h"
#include "room.h"
#include <cmath>
#include <cstdlib>
#include <optional>
// A stream counts as playing for this many updates after it starts, whatever its source says.
constexpr int STREAM_SETTLE_FRAMES = 10;
// While a jingle plays the music ducks toward JINGLE_DUCK_VOLUME for JINGLE_DUCK_FRAMES updates. After that it comes
// back a step at a time, or eased when the timer is JINGLE_TIMER_RESTORE.
constexpr int JINGLE_DUCK_FRAMES = 140;
constexpr float JINGLE_DUCK_VOLUME = 0.1f;
constexpr float JINGLE_DUCK_RATE = 0.08f;
constexpr float JINGLE_RESTORE_RATE = 0.04f;
constexpr float JINGLE_RESTORE_STEP = 0.033333335f;
// Tracks a jingle does not interrupt (MUSIC_BOSS_OVER_TWISTED, MUSIC_REVERSE_GENESIS).
// How the pitch slides toward its target, and how close counts as there.
constexpr float PITCH_SLIDE_RATE = 0.1f;
constexpr float PITCH_SLIDE_EPSILON = 0.001f;
// The wobble dizziness and red rooms give the pitch: three sines, by frequency and amplitude, at a speed per frame
// and a depth in octaves.
constexpr std::array<double, 3> WOBBLE_FREQUENCIES = {0.8, 1, 0.37};
constexpr std::array<float, 3> WOBBLE_AMPLITUDES = {0.4f, 0.2f, 0.4f};
constexpr double DIZZY_WOBBLE_SPEED = 0.05000000074505806;
constexpr float DIZZY_WOBBLE_DEPTH = 0.05f;
constexpr double RED_ROOM_WOBBLE_SPEED = 0.009999999776482582;
constexpr float RED_ROOM_WOBBLE_DEPTH = 0.002f;
constexpr int32_t ROOM_FLAG_RED_ROOM = 1 << 10;
constexpr std::string_view DOCUMENT_TAG = "#document";
// A seed effect that sets the music's pitch, and the pitch.
struct SeedPitch
{
uint32_t seedEffect;
float pitch;
};
// SEED_ULTRA_SLOW_MUSIC, SEED_SLOW_MUSIC, SEED_FAST_MUSIC and SEED_ULTRA_FAST_MUSIC, in the order they are checked.
constexpr std::array<SeedPitch, 4> SEED_PITCHES = {{{42, 0.15f}, {41, 0.75f}, {43, 1.25f}, {44, 2.5f}}};
// 007e1450 Loads a file to play from the start, with its loop, pitch and source volume. It starts once played.
void MusicStream::file_load(std::string_view path, SoundLoop loop, float pitch, float sourceVolume)
{
sound.assign(KAGE::Sound::manager.load_sound(path, KAGE::Sound::SOURCE_STREAM));
nextPath.clear();
frame = 0;
isActive = true;
if (!sound.source) return;
sound.source->SetLooping(loop == SOUND_LOOP);
sound.source->SetPitch(pitch);
sound.source->SetVolume(sourceVolume);
}
// Queues the file to follow the one loading, as the original's stream source queued it after an intro.
void MusicStream::file_queue(std::string_view path, SoundLoop loop)
{
if (!sound.source) return;
nextPath = path;
nextLoop = loop;
}
// Moves on to the queued file once the one before it ends, keeping its volume and pitch.
// The original's stream source joined the two seamlessly. Here the next one starts on the update after.
void MusicStream::file_follow()
{
if (nextPath.empty() || !sound.source || sound.isPaused || sound.source->IsPlaying()) return;
float sourcePitch = sound.source->pitch;
float sourceVolume = sound.source->volume;
std::string path = std::move(nextPath);
file_load(path, nextLoop, sourcePitch, sourceVolume);
sound.Play();
}
// 007e15a0 Fades the volume toward its target and gives the source that volume, times its gain and the scale. A stream
// whose source stopped lets it go. One fading to silence stops there when asked to.
void MusicStream::volume_update(float scale, SilenceMode mode)
{
file_follow();
if (frame > STREAM_SETTLE_FRAMES) isActive = sound.IsPlaying();
if (!isActive)
{
if (!sound.source || sound.isPaused) return;
log_printf(LOG_INFO, "music stopped playing\n");
sound.reset();
return;
}
frame++;
if (std::abs(volume - targetVolume) > fadeRate) volume += (targetVolume - volume) * fadeRate;
else if (volume != targetVolume)
{
volume = targetVolume;
if (targetVolume == 0 && mode == SILENCE_STOP) return sound_stop();
}
float sourceVolume = gain * volume * scale;
if (sound.source && sound.source->volume != sourceVolume) sound.source->SetVolume(sourceVolume);
}
// Sets the pitch of a loaded source.
void MusicStream::pitch_set(float value)
{
if (sound.source) sound.source->SetPitch(value);
}
// Pauses the sound, leaving the stream inactive until it resumes.
void MusicStream::sound_pause()
{
if (!sound.source) return;
sound.Pause();
isActive = false;
frame = 0;
}
// Resumes a paused sound.
void MusicStream::sound_resume()
{
if (!sound.source) return;
sound.Resume();
isActive = true;
}
// 007e1730 Stops an active stream and lets its sound go.
void MusicStream::sound_stop()
{
if (!isActive) return;
sound.Stop();
sound.reset();
nextPath.clear();
isActive = false;
frame = 0;
}
// 007df690 Sets the pitch of the main stream and the layers.
void MusicChannel::SetPitchAll(float value)
{
main.pitch_set(value);
for (MusicStream& layer : layers) layer.pitch_set(value);
}
// The pausing half of Music::Pause, for one channel.
void MusicChannel::Pause()
{
main.sound_pause();
for (MusicStream& layer : layers) layer.sound_pause();
isPlaying = main.isActive;
}
// The resuming half of Music::Resume, for one channel.
void MusicChannel::Resume()
{
main.sound_resume();
for (MusicStream& layer : layers) layer.sound_resume();
isPlaying = main.isActive;
}
// 007df5b0 Starts the main stream and the layers.
void MusicChannel::streams_start()
{
main.sound.Play();
for (MusicStream& layer : layers) layer.sound.Play();
isPlaying = main.isActive;
}
// 007df600 Stops the main stream and the layers, when playing.
void MusicChannel::streams_stop()
{
if (!isPlaying) return;
main.sound_stop();
for (MusicStream& layer : layers) layer.sound_stop();
isPlaying = false;
}
// Lets the main stream and the layers end instead of looping, as a crossfade leaves them.
void MusicChannel::loops_end()
{
if (main.sound.source) main.sound.source->SetLooping(false);
for (MusicStream& layer : layers)
if (layer.sound.source) layer.sound.source->SetLooping(false);
}
// 007df8e0 Fades the channel's volume, aims the streams at the layers that are on (the main stream away while any is,
// in LAYER_MODE_REPLACE), and updates them under the master volume. The layers stop when the main stream does, and
// the whole channel when it fades to silence and is asked to stop.
void MusicChannel::update_volume(float master, SilenceMode mode)
{
if (std::abs(volume - targetVolume) > fadeRate) volume += (targetVolume - volume) * fadeRate;
else volume = targetVolume;
if (layerMode == LAYER_MODE_REPLACE) main.targetVolume = enabledLayers.none() ? 1 : 0;
for (int i = 0; i < MUSIC_LAYER_COUNT; i++)
if (layers[i].isActive) layers[i].targetVolume = enabledLayers.test(i) ? 1 : 0;
main.volume_update(master * volume, SILENCE_KEEP);
for (MusicStream& layer : layers) layer.volume_update(master * volume, SILENCE_KEEP);
isPlaying = main.isActive;
if (!main.isActive)
for (MusicStream& layer : layers) layer.sound_stop();
if (volume <= 0 && mode == SILENCE_STOP) streams_stop();
}
// The document's root element with this tag, whether the document is that element or holds it.
static std::optional<DataNode> root_find(Data& data, std::string_view tag)
{
if (node_tag(data.root) == tag) return data.root;
if (node_tag(data.root) == DOCUMENT_TAG)
for (DataNode node : node_children(data.root))
if (node_tag(node) == tag) return node;
return std::nullopt;
}
// An element's attributes in document order, none when it has none.
static simdjson::dom::object attrs_get(DataNode node)
{
simdjson::dom::object attrs;
return node["attrs"].get(attrs) == simdjson::SUCCESS ? attrs : simdjson::dom::object();
}
// An attribute's text, NUL-terminated as atoi needs.
static std::string_view text_get(simdjson::dom::element value)
{
std::string_view text;
return value.get(text) == simdjson::SUCCESS ? text : std::string_view("");
}
// A file music.xml names, under its root, where the mods redirect it.
static std::string path_redirect(std::string_view root, std::string_view path)
{
return g_manager->modManager.TryRedirectPath(std::string(root).append(path));
}
// Whether a loop attribute says yes: "true", "True" or a number other than 0.
static bool is_text_true(std::string_view text)
{
return !text.empty() && (text == "true" || text == "True" || std::atoi(text.data()) != 0);
}
// A <layer> element's files and volume.
static MusicLayer layer_parse(DataNode node, std::string_view root)
{
MusicLayer layer;
for (auto [key, value] : attrs_get(node))
{
std::string_view text = text_get(value);
if (key == "intro") layer.introPath = path_redirect(root, text);
else if (key == "path") layer.path = path_redirect(root, text);
else if (key == "mul") layer.volume = (float)std::atof(text.data());
}
return layer;
}
// A <track>: its attributes, a first layer they may name, then its <layer> elements. Every element from the first
// <layer> on counts as a layer.
static MusicTrack track_parse(DataNode node, std::string_view root)
{
MusicTrack track;
MusicLayer attrLayer;
for (auto [key, value] : attrs_get(node))
{
std::string_view text = text_get(value);
if (key == "id") track.id = std::atoi(text.data());
else if (key == "name") track.name = text;
else if (key == "intro") track.introPath = path_redirect(root, text);
else if (key == "path") track.path = path_redirect(root, text);
else if (key == "layerintro") attrLayer.introPath = path_redirect(root, text);
else if (key == "layer") attrLayer.path = path_redirect(root, text);
else if (key == "loop") track.loop = is_text_true(text) ? SOUND_LOOP : SOUND_ONCE;
else if (key == "layermode") track.layerMode = (MusicLayerMode)(uint8_t)std::atoi(text.data());
else if (key == "mul") track.volume = (float)std::atof(text.data());
else if (key == "layermul") attrLayer.volume = (float)std::atof(text.data());
else if (key == "layerfadespeed") track.fadeRate = (float)std::atof(text.data());
}
if (!attrLayer.path.empty()) track.layers.push_back(attrLayer);
bool isLayerFound = false;
for (DataNode child : node_children(node))
{
isLayerFound = isLayerFound || node_tag(child) == "layer";
if (isLayerFound) track.layers.push_back(layer_parse(child, root));
}
return track;
}
// 007dfaf0 Loads a music.xml, its paths redirected by the mods. The game's own replaces all the tracks, each at its id,
// dropping ids past NUM_MUSIC as the original does. A mod's adds its tracks after the last id, whatever id they give.
// The original crashes without a <music> root. Here it returns after the log.
void MusicManager::LoadConfig(std::string_view path, ModEntry* mod)
{
Data data;
data_load(data, path);
if (!data.isLoaded) return;
if (!mod)
{
tracks.clear();
tracks.resize(MUSIC_TRACK_COUNT);
}
std::optional<DataNode> root = root_find(data, "music");
if (!root)
{
log_printf(LOG_ASSERT, "Could not find root node 'music' in %s\n", std::string(path).c_str());
return;
}
std::string_view rootPath = node_attr(*root, "root");
for (DataNode node : node_children(*root))
{
MusicTrack track = track_parse(node, rootPath);
if (mod)
{
track.id = (int)tracks.size();
tracks.push_back(std::move(track));
}
else if (track.id > 0 && track.id < MUSIC_TRACK_COUNT) tracks[track.id] = std::move(track);
}
}
// A pitch bent up and down around itself by three slow sines at a time, by depth octaves at most.
static float pitch_wobble(float pitch, double time, float depth)
{
float wave = 0;
for (size_t i = 0; i < WOBBLE_FREQUENCIES.size(); i++)
wave += (float)std::sin(time * WOBBLE_FREQUENCIES[i]) * WOBBLE_AMPLITUDES[i];
return std::pow(2.0f, wave * depth + std::log(pitch) / std::log(2.0f));
}
// Sets the pitch the run's music seeds give, then in a game the wobble of dizziness and of a red room. Whether any
// of them set it.
bool MusicManager::pitch_effects_apply()
{
if (!g_game) return false;
bool isChanged = false;
for (SeedPitch seedPitch : SEED_PITCHES)
if (!isChanged && g_game->seedEffects.HasSeedEffect(seedPitch.seedEffect))
{
pitch = seedPitch.pitch;
isChanged = true;
}
if (g_manager->state != MANAGER_STATE_GAME) return isChanged;
double frame = (int)g_manager->framecount;
if (g_game->dizzyIntensity > 0)
{
pitch = pitch_wobble(pitch, frame * DIZZY_WOBBLE_SPEED, g_game->dizzyIntensity * DIZZY_WOBBLE_DEPTH);
isChanged = true;
}
if (g_game->room->descriptor->flags & ROOM_FLAG_RED_ROOM)
{
pitch = pitch_wobble(pitch, frame * RED_ROOM_WOBBLE_SPEED, RED_ROOM_WOBBLE_DEPTH);
isChanged = true;
}
return isChanged;
}
// 007e17b0 Runs the music each frame. The jingle plays at the sound effect volume, squared as the original has it,
// and ducks the music while it plays. Music is silent when disabled, except in a cutscene. The channel faded out
// stops at silence. The pitch slides to its target or wherever the run's effects bend it. A queued track starts,
// fading in, once the current one has ended.
void MusicManager::Update()
{
OptionsConfig& options = g_manager->optionsConfig;
masterVolume = options.sfxVolume;
jingle.volume_update(masterVolume, SILENCE_STOP);
if (jingle.isActive && jingleTimer > 0)
{
jingleTimer--;
jingleDuck += (JINGLE_DUCK_VOLUME - jingleDuck) * JINGLE_DUCK_RATE;
}
else if (jingleTimer == JINGLE_TIMER_RESTORE) jingleDuck += (1 - jingleDuck) * JINGLE_RESTORE_RATE;
else if (std::abs(jingleDuck - 1) <= JINGLE_RESTORE_STEP) jingleDuck = 1;
else jingleDuck += jingleDuck < 1 ? JINGLE_RESTORE_STEP : -JINGLE_RESTORE_STEP;
bool isAudible = isEnabled || g_manager->state == MANAGER_STATE_CUTSCENE;
masterVolume = (isAudible ? 1.0f : 0.0f) * jingleDuck;
for (int i = 0; i < MUSIC_CHANNEL_COUNT; i++)
channels[i].update_volume(masterVolume, i != currentChannel ? SILENCE_STOP : SILENCE_KEEP);
bool isPitchChanged = pitch_effects_apply();
bool isSliding = std::abs(targetPitch - pitch) > PITCH_SLIDE_EPSILON;
if (isSliding) pitch += (targetPitch - pitch) * PITCH_SLIDE_RATE;
if (isSliding || isPitchChanged)
{
for (MusicChannel& channel : channels) channel.SetPitchAll(pitch);
jingle.pitch_set(pitch);
}
if (channels[currentChannel].isPlaying || queuedMusicId == 0) return;
float volume = isEnabled ? options.musicVolume : 0;
if (is_music_id_valid(queuedMusicId)) Fadein(queuedMusicId, volume, MUSIC_FADE_RATE);
queuedMusicId = 0;
}
// Whether music.xml has a track under the id.
bool MusicManager::is_music_id_valid(int musicId)
{
return musicId >= 0 && musicId < (int)tracks.size();
}
// 007df710 Loads a track onto a channel: its main file (or its intro, the main file queued after it) at the volume
// times the channel's, and every layer it has (each looping after its intro) at silence, the layers already started.
// Layers on the channel from before stop, and none is enabled.
void MusicManager::track_play(MusicChannel& channel, MusicTrack& track, float volume)
{
MusicStream& main = channel.main;
float mainVolume = volume * channel.volume * masterVolume;
if (track.introPath.empty()) main.file_load(track.path, track.loop, pitch, mainVolume);
else
{
main.file_load(track.introPath, SOUND_ONCE, pitch, mainVolume);
main.file_queue(track.path, track.loop);
}
channel.layerMode = track.layerMode;
main.targetVolume = 1;
main.volume = 1;
main.gain = track.volume;
main.fadeRate = track.fadeRate;
channel.enabledLayers.reset();
for (size_t i = 0; i < channel.layers.size(); i++)
{
MusicStream& stream = channel.layers[i];
stream.sound_stop();
if (i >= track.layers.size() || track.layers[i].path.empty()) continue;
MusicLayer& layer = track.layers[i];
if (layer.introPath.empty()) stream.file_load(layer.path, SOUND_LOOP, pitch, 0);
else
{
stream.file_load(layer.introPath, SOUND_ONCE, pitch, 0);
stream.file_queue(layer.path, SOUND_LOOP);
}
stream.targetVolume = 0;
stream.volume = 0;
stream.sound.Play();
stream.fadeRate = track.fadeRate;
stream.gain = layer.volume;
}
}
// 007e1d50 Plays a track from the start on the current channel at a volume, stopping both channels first.
void MusicManager::Play(int musicId, float volume)
{
if (!is_music_id_valid(musicId))
{
log_printf(LOG_ASSERT, "Music ID %d out of bounds.\n", musicId);
return;
}
MusicTrack& track = tracks[musicId];
if (track.path.empty())
{
log_printf(LOG_INFO, "[warn] no music for ID %d (%s).\n", musicId, track.name.c_str());
return;
}
for (MusicChannel& channel : channels) channel.streams_stop();
MusicChannel& channel = channels[currentChannel];
currentMusicId = musicId;
queuedMusicId = 0;
channel.targetVolume = volume;
channel.volume = volume;
track_play(channel, track, 1);
channel.streams_start();
}
// 007e1e70 Fades the current track out at a rate, letting it end instead of looping, while a track fades in on the
// other channel to the music volume. For the track already playing it only sets the target volume.
void MusicManager::Crossfade(int musicId, float fadeRate)
{
if (!is_music_id_valid(musicId))
{
log_printf(LOG_ASSERT, "Music ID %d out of bounds.\n", musicId);
return;
}
float musicVolume = g_manager->optionsConfig.musicVolume;
if (musicId == currentMusicId)
{
log_printf(LOG_INFO, "Music::Crossfade: music already playing, only adjusting target volume.\n");
channels[currentChannel].targetVolume = isEnabled ? musicVolume : 0;
return;
}
MusicTrack& track = tracks[musicId];
if (track.path.empty())
{
log_printf(LOG_INFO, "[warn] no music for ID %d (%s).\n", musicId, track.name.c_str());
return;
}
MusicChannel& previous = channels[currentChannel];
previous.targetVolume = 0;
previous.loops_end();
previous.fadeRate = fadeRate;
currentChannel = (currentChannel + 1) % MUSIC_CHANNEL_COUNT;
currentMusicId = musicId;
queuedMusicId = 0;
MusicChannel& channel = channels[currentChannel];
channel.volume = 0;
channel.targetVolume = musicVolume;
track_play(channel, track, 0);
channel.fadeRate = fadeRate;
channel.streams_start();
}
// 007e2080 Plays a track from silence, fading to a volume at a rate.
void MusicManager::Fadein(int musicId, float volume, float fadeRate)
{
if (!is_music_id_valid(musicId)) return;
Play(musicId, 0);
MusicChannel& channel = channels[currentChannel];
channel.volume = 0;
channel.targetVolume = volume;
channel.fadeRate = fadeRate;
}
// 007e2100 Fades the current track to silence at a rate, forgetting the queued one.
void MusicManager::Fadeout(float fadeRate)
{
channels[currentChannel].targetVolume = 0;
channels[currentChannel].fadeRate = fadeRate;
queuedMusicId = 0;
}
// 007e2580 Plays a track's main file once over the music as a jingle, at the music's pitch, ducking the music for a
// while. Nothing interrupts MUSIC_BOSS_OVER_TWISTED or MUSIC_REVERSE_GENESIS.
// The original's two unused arguments are dropped.
void MusicManager::PlayJingle(int musicId)
{
if (!is_music_id_valid(musicId) || currentMusicId == MUSIC_BOSS_OVER_TWISTED) return;
if (currentMusicId == MUSIC_REVERSE_GENESIS || tracks[musicId].path.empty()) return;
MusicTrack& track = tracks[musicId];
float sfxVolume = g_manager->optionsConfig.sfxVolume;
jingle.file_load(track.path, track.loop, pitch, sfxVolume * masterVolume);
jingle.targetVolume = sfxVolume;
jingle.volume = sfxVolume;
jingle.sound.Play();
jingleTimer = JINGLE_DUCK_FRAMES;
}
// 007e2480 Queues a track to fade in once the current one ends.
void MusicManager::Queue(int musicId)
{
if (is_music_id_valid(musicId)) queuedMusicId = musicId;
}
// 007e2140 Pauses the current channel.
void MusicManager::Pause()
{
channels[currentChannel].Pause();
}
// 007e21f0 Resumes the current channel.
void MusicManager::Resume()
{
channels[currentChannel].Resume();
}
// 007e2280 Turns a layer of the current track on. It fades in on later updates, or comes in at once (the main stream
// going silent at once in LAYER_MODE_REPLACE) with the channel updated right away.
void MusicManager::EnableLayer(int layerId, LayerSwitch layerSwitch)
{
if (layerId < 0 || layerId >= MUSIC_LAYER_COUNT) return;
MusicChannel& channel = channels[currentChannel];
channel.enabledLayers.set(layerId);
if (layerSwitch == LAYER_FADE) return;
if (channel.layerMode == LAYER_MODE_REPLACE)
{
channel.main.targetVolume = 0;
channel.main.volume = 0;
}
for (int i = 0; i < MUSIC_LAYER_COUNT; i++)
{
MusicStream& layer = channel.layers[i];
if (!layer.isActive) continue;
layer.targetVolume = channel.enabledLayers.test(i) ? 1 : 0;
layer.volume = layer.targetVolume;
}
channel.update_volume(masterVolume, SILENCE_KEEP);
}
// 007e2410 Turns a layer of the current track off, to fade out.
void MusicManager::DisableLayer(int layerId)
{
if (layerId >= 0 && layerId < MUSIC_LAYER_COUNT) channels[currentChannel].enabledLayers.reset(layerId);
}
// 007e2440 Whether a layer of the current track is on.
bool MusicManager::IsLayerEnabled(int layerId)
{
return layerId >= 0 && layerId < MUSIC_LAYER_COUNT && channels[currentChannel].enabledLayers.test(layerId);
}
// 007e24c0 Slides the pitch toward a target.
void MusicManager::PitchSlide(float value)
{
targetPitch = value;
}
// 007e24e0 Puts the pitch back at 1 at once, on the current channel.
void MusicManager::ResetPitch()
{
pitch = 1;
targetPitch = 1;
channels[currentChannel].SetPitchAll(1);
}
// 007e2510 Fades the current channel to a share of the music volume at a rate.
void MusicManager::VolumeSlide(float targetVolume, float fadeRate)
{
channels[currentChannel].targetVolume = targetVolume * g_manager->optionsConfig.musicVolume;
channels[currentChannel].fadeRate = fadeRate;
}
// 007e2550 Puts the current channel at the music volume at once.
void MusicManager::UpdateVolume()
{
channels[currentChannel].volume = g_manager->optionsConfig.musicVolume;
channels[currentChannel].targetVolume = g_manager->optionsConfig.musicVolume;
}
// 007e1780 The track playing.
int MusicManager::GetCurrentMusicID()
{
return currentMusicId;
}
// 007e1790 The track queued, or the one playing when none is.
int MusicManager::GetQueuedMusicID()
{
return queuedMusicId != 0 ? queuedMusicId : currentMusicId;
}
// 0085e410 Lets the music be heard.
void MusicManager::Enable()
{
isEnabled = true;
}
// 0085e420 Silences the music outside cutscenes.
void MusicManager::Disable()
{
isEnabled = false;
}
// 0085e430 Whether the music can be heard.
bool MusicManager::IsEnabled()
{
return isEnabled;
}