From 2a85c5f011ad4381460d8ded00cdec6052b4f99b Mon Sep 17 00:00:00 2001 From: Harry Date: Sat, 19 Aug 2017 14:48:00 -0400 Subject: [PATCH] Implement a Fisher-Yates shuffle on background music This fixes sometimes getting repetitive background music --- apps/openmw/mwsound/soundmanagerimp.cpp | 26 ++++++++++++++++--------- apps/openmw/mwsound/soundmanagerimp.hpp | 1 + 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/apps/openmw/mwsound/soundmanagerimp.cpp b/apps/openmw/mwsound/soundmanagerimp.cpp index c6f663059..1cba2e13a 100644 --- a/apps/openmw/mwsound/soundmanagerimp.cpp +++ b/apps/openmw/mwsound/soundmanagerimp.cpp @@ -271,7 +271,6 @@ namespace MWSound return sound; } - // Gets the combined volume settings for the given sound type float SoundManager::volumeFromType(PlayType type) const { @@ -298,7 +297,6 @@ namespace MWSound return volume; } - void SoundManager::stopMusic() { if(mMusic) @@ -367,7 +365,9 @@ namespace MWSound } mMusicFiles[mCurrentPlaylist] = filelist; - + mMusicToPlay.reserve(mMusicToPlay.size() + filelist.size()); + for(int it = 0; it < filelist.size(); it++) + mMusicToPlay.push_back(it); } else filelist = mMusicFiles[mCurrentPlaylist]; @@ -375,15 +375,23 @@ namespace MWSound if(filelist.empty()) return; - int i = Misc::Rng::rollDice(filelist.size()); - - // Don't play the same music track twice in a row - if (filelist[i] == mLastPlayedMusic) + // Do a Fisher-Yates shuffle + if(mMusicFiles.size() == 0) { - i = (i+1) % filelist.size(); + mMusicToPlay.reserve(filelist.size()); + for (int it = 0; it < filelist.size(); it++) + mMusicToPlay.push_back(it); } - advanceMusic(filelist[i]); + int i = Misc::Rng::rollDice(mMusicToPlay.size()); + + // Fix last played music being the same after another shuffle + if(filelist[mMusicToPlay[i]] == mLastPlayedMusic) + i = (i+1) % mMusicToPlay.size(); + + advanceMusic(filelist[mMusicToPlay[i]]); + mMusicToPlay[i] = mMusicToPlay.back(); + mMusicToPlay.pop_back(); } bool SoundManager::isMusicPlaying() diff --git a/apps/openmw/mwsound/soundmanagerimp.hpp b/apps/openmw/mwsound/soundmanagerimp.hpp index 5d911d4be..46a03818b 100644 --- a/apps/openmw/mwsound/soundmanagerimp.hpp +++ b/apps/openmw/mwsound/soundmanagerimp.hpp @@ -49,6 +49,7 @@ namespace MWSound // Caches available music tracks by std::map > mMusicFiles; + std::vector mMusicToPlay; // The list of music files not played yet std::string mLastPlayedMusic; // The music file that was last played float mMasterVolume;