WIP : Timer

This commit is contained in:
beffroi 2023-06-20 19:46:25 +02:00
parent 6d61e5bb12
commit 8254e6f0e0
2 changed files with 111 additions and 57 deletions

View File

@ -16,3 +16,7 @@ opt-level = 1
# Enable high optimizations for dependencies (incl. Bevy), but not for our code: # Enable high optimizations for dependencies (incl. Bevy), but not for our code:
[profile.dev.package."*"] [profile.dev.package."*"]
opt-level = 3 opt-level = 3
[profile.release]
opt-level = 'z'
lto = "thin"

View File

@ -3,18 +3,33 @@
//! It displays the current FPS in the top left corner, as well as text that changes color //! It displays the current FPS in the top left corner, as well as text that changes color
//! in the bottom right. For text within a scene, please see the text2d example. //! in the bottom right. For text within a scene, please see the text2d example.
use std::time::Duration;
use bevy::{ use bevy::{
diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin}, diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin},
prelude::*, prelude::*,
utils::Instant,
window::WindowMode,
}; };
fn main() { fn main() {
let window_plugin = WindowPlugin {
primary_window: Some(Window {
title: "Fullscreen Test".into(),
position: WindowPosition::Centered(MonitorSelection::Index(1)),
mode: WindowMode::Fullscreen,
present_mode: bevy::window::PresentMode::AutoNoVsync,
..default()
}),
..default()
};
App::new() App::new()
.add_plugins(DefaultPlugins) .add_plugins(DefaultPlugins.set(window_plugin))
.add_plugin(FrameTimeDiagnosticsPlugin::default()) .add_plugin(FrameTimeDiagnosticsPlugin::default())
.init_resource::<ForgeTimer>()
.add_startup_system(setup) .add_startup_system(setup)
.add_system(text_update_system) .add_system(bevy::window::close_on_esc)
.add_system(text_color_system) .add_system(update_timer)
.run(); .run();
} }
@ -26,77 +41,112 @@ struct FpsText;
#[derive(Component)] #[derive(Component)]
struct ColorText; struct ColorText;
#[derive(Component)]
struct ShowTimer;
#[derive(Debug, Resource)]
struct ForgeTimer {
/// The actual ON/PAUSE timer
time_current: bevy::prelude::Time,
// time_current: TimeCurrent,
/// The target to reach
time_target: isize,
// time_target: TimeTarget,
/// The time offset, usually negative
time_offset: isize,
// /// The calculated speedup/slowdown
// time_warp: f64,
// time_offset: TimeOffset,
/// Wether it is started
started: bool,
}
impl FromWorld for ForgeTimer {
fn from_world(_world: &mut World) -> Self {
let time = Time::new(Instant::now());
time.startup();
ForgeTimer {
time_current: time,
time_target: 60 * 15 + 30,
time_offset: 60 * 14,
started: false,
}
}
}
impl ForgeTimer {
fn to_str(&mut self) -> String {
let t = self.time_current.elapsed_seconds_f64() as isize;
self.time_current.update();
let remaining = self.time_target - t;
let actual_remaining = self.time_target - self.time_offset - t;
// let scaled_remaining = remaining*
// let time_warp = (self.time_target - self.time_offset) * remaining / self.time_target;
let percent = actual_remaining * 100 / self.time_target;
// sec_to_str(remaining)
format!("{}", percent)
}
}
fn sec_to_str(time: isize) -> String {
// let time = time.as_secs();
let sign = if time < 0 { "-" } else { "" };
let s = time % 60;
let m = (time / 60) % 3600;
let h = time / 3600;
format!("{}{:02}:{:02}:{:02}", sign, h, m, s)
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// UI camera // UI camera
// let mut forge_time = bevy::prelude::Time::default();
commands.spawn(Camera2dBundle::default()); commands.spawn(Camera2dBundle::default());
// Text with one section
commands.spawn(( commands.spawn((
// Create a TextBundle that has a Text with a single section.
TextBundle::from_section(
// Accepts a `String` or any type that converts into a `String`, such as `&str`
"hello\nbevy!",
TextStyle {
font: asset_server.load("fonts/digital-7.ttf"),
font_size: 100.0,
color: Color::WHITE,
},
) // Set the alignment of the Text
.with_text_alignment(TextAlignment::Center)
// Set the style of the TextBundle itself.
.with_style(Style {
position_type: PositionType::Absolute,
position: UiRect {
bottom: Val::Px(5.0),
right: Val::Px(15.0),
..default()
},
..default()
}),
ColorText,
));
// Text with multiple sections
commands.spawn((
// Create a TextBundle that has a Text with a list of sections.
TextBundle::from_sections([ TextBundle::from_sections([
TextSection::new( TextSection::new(
"FPS: ", "REMAINING TIME: ",
TextStyle { TextStyle {
font: asset_server.load("fonts/digital-7.ttf"), font: asset_server.load("fonts/digital-7.ttf"),
font_size: 60.0, font_size: 60.,
color: Color::WHITE, color: Color::GREEN,
}, },
), ),
TextSection::from_style(TextStyle { TextSection::from_style(TextStyle {
font: asset_server.load("fonts/digital-7.ttf"), font: asset_server.load("fonts/digital-7.ttf"),
font_size: 60.0, font_size: 60.,
color: Color::GOLD, color: Color::GREEN,
}), }),
]), ])
FpsText, .with_style(Style {
position_type: PositionType::Absolute,
position: UiRect {
bottom: Val::Px(500.0),
right: Val::Px(150.0),
..default()
},
..default()
})
.with_text_alignment(TextAlignment::Center),
ShowTimer,
)); ));
} }
fn text_color_system(time: Res<Time>, mut query: Query<&mut Text, With<ColorText>>) { fn update_timer(
time: Res<Time>,
mut tmr: ResMut<ForgeTimer>,
mut query: Query<&mut Text, With<ShowTimer>>,
) {
for mut text in &mut query { for mut text in &mut query {
let seconds = time.elapsed_seconds(); text.sections[1].value = format!("{}", tmr.to_str()); //sec_to_time(time.elapsed_wrapped());
// text.sections[1].value = format!("{:?}", tmr);
// Update the color of the first and only section.
text.sections[0].style.color = Color::Rgba {
red: (1.25 * seconds).sin() / 2.0 + 0.5,
green: (0.75 * seconds).sin() / 2.0 + 0.5,
blue: (0.50 * seconds).sin() / 2.0 + 0.5,
alpha: 1.0,
};
} }
} }
fn text_update_system(diagnostics: Res<Diagnostics>, mut query: Query<&mut Text, With<FpsText>>) { // fn sec_to_time(time: Duration) -> String {
for mut text in &mut query { // let time = time.as_secs();
if let Some(fps) = diagnostics.get(FrameTimeDiagnosticsPlugin::FPS) { // let s = time % 60;
if let Some(value) = fps.smoothed() { // let m = (time / 60) % 3600;
// Update the value of the second section // let h = time / 3600;
text.sections[1].value = format!("{value:.2}"); // format!("{:02}:{:02}:{:02}", h, m, s)
} // }
}
}
}