Skip to content

Commit

Permalink
feat: re-implement music player.
Browse files Browse the repository at this point in the history
  • Loading branch information
zicklag committed Oct 15, 2023
1 parent eebddd1 commit dacd190
Show file tree
Hide file tree
Showing 7 changed files with 214 additions and 26 deletions.
18 changes: 9 additions & 9 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,8 @@ ignored = [
"getrandom", # Needed to add `js` feature
]

# # Uncomment for testing during bones development, if you clone bones adjacent to the jumpy
# # repo.
# [patch.'https://github.com/fishfolk/bones']
# bones_framework = { path = "../bones/framework_crates/bones_framework" }
# bones_bevy_renderer = { path = "../bones/framework_crates/bones_bevy_renderer" }
28 changes: 14 additions & 14 deletions assets/game.yaml
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
# music:
# title_screen: music/01 fishycuffs.ogg
# fight:
# - music/02 whalecome.ogg
# - music/03 ahoy!.ogg
# - music/04 bait the hook.ogg
# - music/05 fire in the hole.ogg
# - music/06 fishsticks.ogg
# - music/07 jolly roger.ogg
# - music/08 krill or be krilled.ogg
# - music/09 landlubber.ogg
# character_screen: music/10 fish bucket.ogg
# results_screen: music/11 thar she blows!.ogg
# credits: music/12 all hands hoay!.ogg
music:
title_screen: music/01 fishycuffs.ogg
fight:
- music/02 whalecome.ogg
- music/03 ahoy!.ogg
- music/04 bait the hook.ogg
- music/05 fire in the hole.ogg
- music/06 fishsticks.ogg
- music/07 jolly roger.ogg
- music/08 krill or be krilled.ogg
- music/09 landlubber.ogg
character_screen: music/10 fish bucket.ogg
results_screen: music/11 thar she blows!.ogg
credits: music/12 all hands hoay!.ogg


main_menu:
Expand Down
5 changes: 2 additions & 3 deletions src/core/audio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub enum AudioEvent {
}

fn play_sounds(
audio: Res<AudioManager>,
mut audio: ResMut<AudioManager>,
mut audio_events: ResMut<AudioEvents>,
assets: Res<AssetServer>,
) {
Expand All @@ -56,10 +56,9 @@ fn play_sounds(
sound_source,
volume,
} => {
if let Err(e) = audio.borrow_mut().play(
if let Err(e) = audio.play(
assets
.get(sound_source)
.0
.with_settings(StaticSoundSettings::default().volume(volume)),
) {
warn!("Error playing sound: {e}");
Expand Down
13 changes: 13 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use bones_framework::prelude::*;

pub mod core;
pub mod input;
pub mod music;
pub mod sessions;
pub mod settings;
pub mod ui;
Expand Down Expand Up @@ -46,6 +47,17 @@ pub struct GameMeta {
pub localization: Handle<LocalizationAsset>,
pub theme: ui::UiTheme,
pub main_menu: ui::main_menu::MainMenuMeta,
pub music: GameMusic,
}

#[derive(HasSchema, Clone, Debug, Default)]
#[repr(C)]
pub struct GameMusic {
pub title_screen: Handle<AudioSource>,
pub fight: SVec<Handle<AudioSource>>,
pub character_screen: Handle<AudioSource>,
pub results_screen: Handle<AudioSource>,
pub credits: Handle<AudioSource>,
}

fn main() {
Expand All @@ -64,6 +76,7 @@ fn main() {
game
// Install game plugins
.install_plugin(DefaultGamePlugin)
.install_plugin(music::game_plugin)
.install_plugin(settings::game_plugin)
.install_plugin(input::game_plugin)
.install_plugin(core::game_plugin)
Expand Down
170 changes: 170 additions & 0 deletions src/music.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
use bones_framework::prelude::kira::{
sound::{
static_sound::{StaticSoundHandle, StaticSoundSettings},
PlaybackState, Region,
},
tween::Tween,
};

use crate::{prelude::*, ui::main_menu::MenuPage};

pub fn game_plugin(game: &mut Game) {
let session = game.sessions.create(SessionNames::MUSIC_PLAYER);

// Music player doesn't do any rendering
session.visible = false;
session.stages.add_system_to_stage(First, music_system);
}

/// The music playback state.
#[derive(HasSchema, Default)]
#[schema(no_clone)]
pub enum MusicState {
/// Music is not playing.
#[default]
None,
/// Playing the main menu music.
MainMenu(StaticSoundHandle),
/// Playing the character select music.
CharacterSelect(StaticSoundHandle),
/// Playing the credits music.
Credits(StaticSoundHandle),
/// Playing the fight music.
Fight {
/// The handle to the audio instance.
instance: StaticSoundHandle,
/// The index of the song in the shuffled playlist.
idx: usize,
},
}

impl MusicState {
/// Get the current audio instance, if one is contained.
fn current_instance(&mut self) -> Option<&mut StaticSoundHandle> {
match self {
MusicState::None => None,
MusicState::MainMenu(i) => Some(i),
MusicState::CharacterSelect(i) => Some(i),
MusicState::Credits(i) => Some(i),
MusicState::Fight { instance, .. } => Some(instance),
}
}
}

/// Bevy resource containing the in-game music playlist shuffled.
#[derive(HasSchema, Deref, DerefMut, Clone, Default)]
#[repr(C)]
pub struct ShuffledPlaylist(pub SVec<Handle<AudioSource>>);

/// The amount of time to spend fading the music in and out.
const MUSIC_FADE_DURATION: Duration = Duration::from_millis(500);

const MUSIC_VOLUME: f64 = 0.1;

/// System that plays music according to the game mode.
fn music_system(
meta: Root<GameMeta>,
mut audio: ResMut<AudioManager>,
mut shuffled_fight_music: ResMutInit<ShuffledPlaylist>,
mut music_state: ResMutInit<MusicState>,
ctx: Res<EguiCtx>,
sessions: Res<Sessions>,
assets: Res<AssetServer>,
) {
if shuffled_fight_music.is_empty() {
let mut songs = meta.music.fight.clone();
THREAD_RNG.with(|rng| rng.shuffle(&mut songs));
**shuffled_fight_music = songs;
}

let tween = Tween {
start_time: kira::StartTime::Immediate,
duration: MUSIC_FADE_DURATION,
easing: kira::tween::Easing::Linear,
};
let play_settings = StaticSoundSettings::default()
.volume(MUSIC_VOLUME)
.fade_in_tween(tween);

// If we are in a game
if sessions.get(SessionNames::GAME).is_some() {
if let MusicState::Fight { instance, idx } = &mut *music_state {
if let PlaybackState::Stopped = instance.state() {
*idx += 1;
*idx %= shuffled_fight_music.len();

*instance = audio
.play(
assets
.get(shuffled_fight_music[*idx])
.0
.with_settings(play_settings),
)
.unwrap();
}
} else {
if let Some(instance) = music_state.current_instance() {
instance.stop(tween).unwrap();
}

if let Some(song) = shuffled_fight_music.get(0) {
*music_state = MusicState::Fight {
instance: audio
.play(assets.get(*song).with_settings(play_settings))
.unwrap(),
idx: 0,
};
}
}

// If we are on a menu page
} else if sessions.get(SessionNames::MAIN_MENU).is_some() {
let menu_page = ctx.get_state::<MenuPage>();
match menu_page {
MenuPage::PlayerSelect | MenuPage::MapSelect { .. } | MenuPage::NetworkGame => {
if !matches!(*music_state, MusicState::CharacterSelect(..)) {
if let Some(instance) = music_state.current_instance() {
instance.stop(tween).unwrap();
}
*music_state = MusicState::CharacterSelect(
audio
.play(
assets
.get(meta.music.character_screen)
.with_settings(play_settings.loop_region(Region::default())),
)
.unwrap(),
);
}
}
MenuPage::Home | MenuPage::Settings => {
if !matches!(*music_state, MusicState::MainMenu(..)) {
if let Some(instance) = music_state.current_instance() {
instance.stop(tween).unwrap();
}
*music_state = MusicState::MainMenu(
audio
.play(
assets
.get(meta.music.title_screen)
.with_settings(play_settings),
)
.unwrap(),
);
}
}
MenuPage::Credits => {
if !matches!(*music_state, MusicState::Credits(..)) {
if let Some(instance) = music_state.current_instance() {
instance.stop(tween).unwrap();
}
*music_state = MusicState::Credits(
audio
.play(assets.get(meta.music.credits).with_settings(play_settings))
.unwrap(),
);
}
}
}
}
}
1 change: 1 addition & 0 deletions src/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ impl SessionNames {
pub const GAME: &str = "game";
pub const MAIN_MENU: &str = "main_menu";
pub const PAUSE_MENU: &str = "pause_menu";
pub const MUSIC_PLAYER: &str = "music_player";
}

pub trait SessionExt {
Expand Down

0 comments on commit dacd190

Please sign in to comment.