refactor audio events, add notification popup message on alien chat

This commit is contained in:
yuni 2024-03-19 03:18:16 +01:00
parent f6b067533c
commit 9f6d12145f
3 changed files with 118 additions and 86 deletions

View file

@ -98,7 +98,7 @@ pub fn handle_input(
query: Query<(&Talker, &Transform)>, query: Query<(&Talker, &Transform)>,
player: Query<&Transform, With<actor::Player>>, player: Query<&Transform, With<actor::Player>>,
mut ew_conv: EventWriter<StartConversationEvent>, mut ew_conv: EventWriter<StartConversationEvent>,
mut ew_click: EventWriter<audio::AudioClickEvent>, mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
) )
{ {
if keyboard_input.just_pressed(settings.key_interact) { if keyboard_input.just_pressed(settings.key_interact) {
@ -107,7 +107,7 @@ pub fn handle_input(
for (talker, transform) in &query { for (talker, transform) in &query {
if transform.translation.distance_squared(player.translation) <= mindist { if transform.translation.distance_squared(player.translation) <= mindist {
ew_conv.send(StartConversationEvent{conv: talker.conv.clone()}); ew_conv.send(StartConversationEvent{conv: talker.conv.clone()});
ew_click.send(audio::AudioClickEvent()); ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::IncomingChatMessage));
break; break;
} }
} }
@ -120,7 +120,7 @@ pub fn handle_conversations(
mut log: ResMut<hud::Log>, mut log: ResMut<hud::Log>,
) { ) {
for my_event in er_conv.read() { for my_event in er_conv.read() {
log.add(my_event.conv.clone()); log.chat(my_event.conv.clone(), "Alien".to_string());
break; break;
} }
} }

View file

@ -4,6 +4,7 @@ use crate::settings;
const ASSET_CLICK: &str = "sounds/click-button-140881-crop.ogg"; const ASSET_CLICK: &str = "sounds/click-button-140881-crop.ogg";
const ASSET_SWITCH: &str = "sounds/typosonic-typing-192811-crop.ogg"; const ASSET_SWITCH: &str = "sounds/typosonic-typing-192811-crop.ogg";
const ASSET_INCOMING_MESSAGE: &str = "tmp/multi-pop-2-188167.mp3.ogg";
const ASSET_RADIO: &str = "tmp/LP - Girls Go Wild (Official Music Video)-M7XRN0oHGIM.ogg"; const ASSET_RADIO: &str = "tmp/LP - Girls Go Wild (Official Music Video)-M7XRN0oHGIM.ogg";
const ASSET_BGM: &str = "tmp/FTL - Faster Than Light (2012) OST - 12 - Void (Explore)-edQw2yYXQJM.ogg"; const ASSET_BGM: &str = "tmp/FTL - Faster Than Light (2012) OST - 12 - Void (Explore)-edQw2yYXQJM.ogg";
@ -14,41 +15,27 @@ impl Plugin for AudioPlugin {
app.add_systems(Update, toggle_bgm); app.add_systems(Update, toggle_bgm);
app.add_systems(PostUpdate, play_sfx); app.add_systems(PostUpdate, play_sfx);
app.add_systems(PostUpdate, update_music); app.add_systems(PostUpdate, update_music);
app.add_event::<AudioClickEvent>(); app.add_event::<PlaySfxEvent>();
app.add_event::<AudioSwitchEvent>();
app.add_event::<ToggleMusicEvent>(); app.add_event::<ToggleMusicEvent>();
} }
} }
#[derive(Event)] pub enum Sfx {
pub struct AudioClickEvent(); IncomingChatMessage,
Click,
Switch,
}
#[derive(Event)] #[derive(Event)] pub struct PlaySfxEvent(pub Sfx);
pub struct AudioSwitchEvent(); #[derive(Event)] pub struct ToggleMusicEvent();
#[derive(Component)] pub struct ComponentBGM;
#[derive(Event)] #[derive(Component)] pub struct ComponentRadio;
pub struct ToggleMusicEvent(); #[derive(Component)] pub struct ComponentThrusterSound;
#[derive(Component)] struct SoundBGM(Handle<AudioSource>);
#[derive(Component)] #[derive(Component)] pub struct SoundRadio(Handle<AudioSource>);
pub struct ComponentBGM; #[derive(Resource)] pub struct SoundClick(Handle<AudioSource>);
#[derive(Resource)] pub struct SoundSwitch(Handle<AudioSource>);
#[derive(Component)] #[derive(Resource)] pub struct SoundIncomingMessage(Handle<AudioSource>);
pub struct ComponentRadio;
#[derive(Component)]
pub struct ComponentThrusterSound;
#[derive(Component)]
struct SoundBGM(Handle<AudioSource>);
#[derive(Component)]
pub struct SoundRadio(Handle<AudioSource>);
#[derive(Resource)]
pub struct SoundClick(Handle<AudioSource>);
#[derive(Resource)]
pub struct SoundSwitch(Handle<AudioSource>);
pub fn setup( pub fn setup(
mut commands: Commands, mut commands: Commands,
@ -98,22 +85,23 @@ pub fn setup(
)); ));
commands.insert_resource(SoundClick(asset_server.load(ASSET_CLICK))); commands.insert_resource(SoundClick(asset_server.load(ASSET_CLICK)));
commands.insert_resource(SoundSwitch(asset_server.load(ASSET_SWITCH))); commands.insert_resource(SoundSwitch(asset_server.load(ASSET_SWITCH)));
commands.insert_resource(SoundIncomingMessage(asset_server.load(ASSET_INCOMING_MESSAGE)));
} }
pub fn toggle_bgm( pub fn toggle_bgm(
keyboard_input: Res<ButtonInput<KeyCode>>, keyboard_input: Res<ButtonInput<KeyCode>>,
mut evwriter_toggle: EventWriter<ToggleMusicEvent>, mut evwriter_toggle: EventWriter<ToggleMusicEvent>,
mut evwriter_click: EventWriter<AudioClickEvent>, mut evwriter_sfx: EventWriter<PlaySfxEvent>,
mut settings: ResMut<settings::Settings>, mut settings: ResMut<settings::Settings>,
) { ) {
if keyboard_input.just_pressed(KeyCode::KeyT) { if keyboard_input.just_pressed(KeyCode::KeyT) {
settings.mute_music ^= true; settings.mute_music ^= true;
evwriter_click.send(AudioClickEvent()); evwriter_sfx.send(PlaySfxEvent(Sfx::Click));
evwriter_toggle.send(ToggleMusicEvent()); evwriter_toggle.send(ToggleMusicEvent());
} }
if keyboard_input.just_pressed(KeyCode::KeyM) { if keyboard_input.just_pressed(KeyCode::KeyM) {
settings.mute_sfx ^= true; settings.mute_sfx ^= true;
evwriter_click.send(AudioClickEvent()); evwriter_sfx.send(PlaySfxEvent(Sfx::Click));
evwriter_toggle.send(ToggleMusicEvent()); evwriter_toggle.send(ToggleMusicEvent());
} }
} }
@ -121,28 +109,23 @@ pub fn toggle_bgm(
pub fn play_sfx( pub fn play_sfx(
mut commands: Commands, mut commands: Commands,
settings: Res<settings::Settings>, settings: Res<settings::Settings>,
mut events_click: EventReader<AudioClickEvent>, mut events_sfx: EventReader<PlaySfxEvent>,
mut events_switch: EventReader<AudioSwitchEvent>,
sound_click: Res<SoundClick>, sound_click: Res<SoundClick>,
sound_switch: Res<SoundSwitch>, sound_switch: Res<SoundSwitch>,
sound_incoming_message: Res<SoundIncomingMessage>,
) { ) {
if !events_click.is_empty() { if settings.mute_sfx && !events_sfx.is_empty() {
events_click.clear(); events_sfx.clear();
if !settings.mute_sfx {
commands.spawn(AudioBundle {
source: sound_click.0.clone(),
settings: PlaybackSettings::DESPAWN,
});
}
} }
if !events_switch.is_empty() { for sfx in events_sfx.read() {
events_switch.clear(); commands.spawn(AudioBundle {
if !settings.mute_sfx { source: match sfx.0 {
commands.spawn(AudioBundle { Sfx::Switch => sound_switch.0.clone(),
source: sound_switch.0.clone(), Sfx::Click => sound_click.0.clone(),
settings: PlaybackSettings::DESPAWN, Sfx::IncomingChatMessage => sound_incoming_message.0.clone(),
}); },
} settings: PlaybackSettings::DESPAWN,
});
} }
} }

View file

@ -15,7 +15,10 @@ impl Plugin for HudPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_systems(Startup, setup); app.add_systems(Startup, setup);
app.add_systems(Update, (update, handle_input)); app.add_systems(Update, (update, handle_input));
app.insert_resource(Log { logs: VecDeque::with_capacity(LOG_MAX) }); app.insert_resource(Log {
logs: VecDeque::with_capacity(LOG_MAX),
needs_rerendering: true,
});
app.insert_resource(FPSUpdateTimer( app.insert_resource(FPSUpdateTimer(
Timer::from_seconds(HUD_REFRESH_TIME, TimerMode::Repeating))); Timer::from_seconds(HUD_REFRESH_TIME, TimerMode::Repeating)));
} }
@ -27,26 +30,53 @@ impl Plugin for HudPlugin {
#[derive(Resource)] #[derive(Resource)]
struct FPSUpdateTimer(Timer); struct FPSUpdateTimer(Timer);
pub enum LogLevel {
Warning,
//Error,
Info,
//Debug,
Chat,
//Ping,
}
struct Message { struct Message {
text: String, text: String,
sender: String,
level: LogLevel,
time: u64, time: u64,
} }
#[derive(Resource)] #[derive(Resource)]
pub struct Log { pub struct Log {
logs: VecDeque<Message>, logs: VecDeque<Message>,
needs_rerendering: bool,
} }
impl Log { impl Log {
pub fn add(&mut self, message: String) { pub fn info(&mut self, message: String) {
self.add(message, "System".to_string(), LogLevel::Info);
}
pub fn chat(&mut self, message: String, sender: String) {
self.add(message, sender, LogLevel::Chat);
}
pub fn warning(&mut self, message: String) {
self.add(message, "WARNING".to_string(), LogLevel::Warning);
}
pub fn add(&mut self, message: String, sender: String, level: LogLevel) {
if self.logs.len() == LOG_MAX { if self.logs.len() == LOG_MAX {
self.logs.pop_front(); self.logs.pop_front();
} }
if let Ok(epoch) = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) { if let Ok(epoch) = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
self.logs.push_back(Message { self.logs.push_back(Message {
text: message, text: message,
sender: sender,
level: level,
time: epoch.as_secs(), time: epoch.as_secs(),
}); });
self.needs_rerendering = true;
} }
} }
@ -67,8 +97,9 @@ fn setup(
asset_server: Res<AssetServer>, asset_server: Res<AssetServer>,
mut log: ResMut<Log>, mut log: ResMut<Log>,
) { ) {
log.add("Customer wake-up registered.".to_string()); log.info("Customer wake-up registered.".to_string());
log.add("Systems reactivated.".to_string()); log.info("Systems reactivated.".to_string());
log.warning("Oxygen Low".to_string());
let visibility = if settings.hud_active { let visibility = if settings.hud_active {
Visibility::Inherited Visibility::Inherited
} else { } else {
@ -194,26 +225,28 @@ fn setup(
)); ));
// Add Chat Box // Add Chat Box
// let bundle_chatbox = TextBundle::from_sections([ let bundle_chatbox = TextBundle::from_sections([
// TextSection::new( TextSection::new(
// "Hello :D", "Hello World!\nThis Is Cool, right?",
// TextStyle { TextStyle {
// font: asset_server.load(FONT), font: asset_server.load(FONT),
// font_size: settings.font_size_hud, font_size: settings.font_size_hud,
// color: Color::GRAY, color: Color::GRAY,
// ..default() ..default()
// } }
// ), ),
// ]).with_style(Style { ]).with_style(Style {
// position_type: PositionType::Absolute, position_type: PositionType::Absolute,
// bottom: Val::VMin(40.0), top: Val::VMin(2.0),
// left: Val::VMin(30.0), right: Val::VMin(6.0),
// ..default() //bottom: Val::VMin(40.0),
// }); //left: Val::VMin(30.0),
// commands.spawn(( ..default()
// bundle_chatbox, }).with_text_justify(JustifyText::Right);
// ChatText, commands.spawn((
// )); bundle_chatbox,
ChatText,
));
} }
fn update( fn update(
@ -223,10 +256,12 @@ fn update(
player: Query<(&actor::Suit, &actor::LifeForm), With<actor::Player>>, player: Query<(&actor::Suit, &actor::LifeForm), With<actor::Player>>,
mut timer: ResMut<FPSUpdateTimer>, mut timer: ResMut<FPSUpdateTimer>,
mut query: Query<&mut Text, With<GaugesText>>, mut query: Query<&mut Text, With<GaugesText>>,
mut query_chat: Query<&mut Text, (With<ChatText>, Without<GaugesText>)>,
query_all_actors: Query<&actor::Actor>, query_all_actors: Query<&actor::Actor>,
settings: Res<settings::Settings>,
) { ) {
// TODO only when hud is actually on // TODO only when hud is actually on
if timer.0.tick(time.delta()).just_finished() { if timer.0.tick(time.delta()).just_finished() || log.needs_rerendering {
let player = player.get_single(); let player = player.get_single();
if player.is_ok() { if player.is_ok() {
let (suit, lifeform) = player.unwrap(); let (suit, lifeform) = player.unwrap();
@ -248,10 +283,23 @@ fn update(
text.sections[9].value = format!("{all_actors:.0}"); text.sections[9].value = format!("{all_actors:.0}");
} }
} }
for mut text in &mut query {
let logs_vec: Vec<&str> = log.logs.iter().map(|s| s.text.as_str()).collect(); if let Ok(mut chat) = query_chat.get_single_mut() {
text.sections[11].value = logs_vec.join("\n"); let logfilter = if settings.hud_active {
|_msg: &&Message| { true }
} else {
|msg: &&Message| { match msg.level {
LogLevel::Chat => true,
LogLevel::Warning => true,
_ => false
}}
};
let logs_vec: Vec<String> = log.logs.iter()
.filter(logfilter)
.map(|s| format!("{}: {}", s.sender, s.text)).collect();
chat.sections[0].value = logs_vec.join("\n");
} }
log.needs_rerendering = false;
log.remove_old(); log.remove_old();
} }
} }
@ -261,11 +309,11 @@ fn handle_input(
mut settings: ResMut<settings::Settings>, mut settings: ResMut<settings::Settings>,
mut query: Query<&mut Visibility, With<GaugesText>>, mut query: Query<&mut Visibility, With<GaugesText>>,
mut query_bloomsettings: Query<&mut BloomSettings>, mut query_bloomsettings: Query<&mut BloomSettings>,
mut evwriter: EventWriter<audio::AudioSwitchEvent>, mut evwriter_sfx: EventWriter<audio::PlaySfxEvent>,
mut evwriter_togglemusic: EventWriter<audio::ToggleMusicEvent>, mut evwriter_togglemusic: EventWriter<audio::ToggleMusicEvent>,
) { ) {
if keyboard_input.just_pressed(settings.key_togglehud) { if keyboard_input.just_pressed(settings.key_togglehud) {
for mut vis in &mut query { if let Ok(mut vis) = query.get_single_mut() {
if let Ok(mut bloomsettings) = query_bloomsettings.get_single_mut() { if let Ok(mut bloomsettings) = query_bloomsettings.get_single_mut() {
if *vis == Visibility::Inherited { if *vis == Visibility::Inherited {
*vis = Visibility::Hidden; *vis = Visibility::Hidden;
@ -274,9 +322,10 @@ fn handle_input(
} else { } else {
*vis = Visibility::Inherited; *vis = Visibility::Inherited;
settings.hud_active = true; settings.hud_active = true;
bloomsettings.composite_mode = BloomCompositeMode::Additive; bloomsettings.composite_mode = BloomCompositeMode::EnergyConserving;
//bloomsettings.composite_mode = BloomCompositeMode::Additive;
} }
evwriter.send(audio::AudioSwitchEvent()); evwriter_sfx.send(audio::PlaySfxEvent(audio::Sfx::Switch));
evwriter_togglemusic.send(audio::ToggleMusicEvent()); evwriter_togglemusic.send(audio::ToggleMusicEvent());
} }
} }