auto-hide log messages

This commit is contained in:
yuni 2024-03-18 01:02:17 +01:00
parent 0cf1c4102f
commit 03dab2bb23

View file

@ -2,10 +2,12 @@ use crate::{settings, actor};
use bevy::prelude::*;
use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
use std::collections::VecDeque;
use std::time::SystemTime;
const HUD_REFRESH_TIME: f32 = 0.5;
const FONT: &str = "tmp/fonts/NotoSansSC-Thin.ttf";
const LOG_MAX: usize = 5;
const LOG_MAX_TIME_S: u64 = 3;
pub struct HudPlugin;
impl Plugin for HudPlugin {
@ -24,9 +26,14 @@ struct GaugesText;
#[derive(Resource)]
struct FPSUpdateTimer(Timer);
struct Message {
text: String,
time: u64,
}
#[derive(Resource)]
struct Log {
logs: VecDeque<String>,
logs: VecDeque<Message>,
}
impl Log {
@ -34,7 +41,22 @@ impl Log {
if self.logs.len() == LOG_MAX {
self.logs.pop_front();
}
self.logs.push_back(message);
if let Ok(epoch) = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
self.logs.push_back(Message {
text: message,
time: epoch.as_secs(),
});
}
}
pub fn remove_old(&mut self) {
if let Some(message) = self.logs.front() {
if let Ok(epoch) = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
if epoch.as_secs() - message.time > LOG_MAX_TIME_S {
self.logs.pop_front();
}
}
}
}
}
@ -156,7 +178,7 @@ fn setup(
fn update(
diagnostics: Res<DiagnosticsStore>,
time: Res<Time>,
log: Res<Log>,
mut log: ResMut<Log>,
player: Query<(&actor::Suit, &actor::LifeForm), With<actor::Player>>,
mut timer: ResMut<FPSUpdateTimer>,
mut query: Query<&mut Text, With<GaugesText>>,
@ -182,9 +204,10 @@ fn update(
}
}
for mut text in &mut query {
let logs_vec: Vec<&str> = log.logs.iter().map(|s| s.as_str()).collect();
let logs_vec: Vec<&str> = log.logs.iter().map(|s| s.text.as_str()).collect();
text.sections[9].value = logs_vec.join("\n");
}
log.remove_old();
}
}