Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Display energy & num selected in HUD #520

Merged
merged 9 commits into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ de_terrain = { path = "crates/terrain", version = "0.1.0-dev" }
de_uom = { path = "crates/uom", version = "0.1.0-dev" }

# Other
ab_glyph = "0.2.21"
ahash = "0.7.6"
anyhow = "1.0"
approx = "0.5.1"
Expand Down
1 change: 1 addition & 0 deletions crates/controller/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ de_combat.workspace = true
de_conf.workspace = true
de_construction.workspace = true
de_core.workspace = true
de_energy.workspace = true
de_gui.workspace = true
de_index.workspace = true
de_map.workspace = true
Expand Down
165 changes: 146 additions & 19 deletions crates/controller/src/hud/details.rs
Original file line number Diff line number Diff line change
@@ -1,37 +1,164 @@
use bevy::prelude::*;
use de_core::baseset::GameSet;
use de_core::{cleanup::DespawnOnGameExit, gamestate::GameState};
use de_energy::Battery;
use de_gui::{BodyTextCommands, BodyTextOps, GuiCommands, OuterStyle};

use super::{interaction::InteractionBlocker, HUD_COLOR};
use crate::selection::Selected;

const PREFIXES: [&str; 5] = ["", "k", "M", "G", "T"];

pub(crate) struct DetailsPlugin;

impl Plugin for DetailsPlugin {
fn build(&self, app: &mut App) {
app.add_system(spawn_details.in_schedule(OnEnter(GameState::Playing)));
app.add_system(setup.in_schedule(OnEnter(GameState::Playing)))
JackCrumpLeys marked this conversation as resolved.
Show resolved Hide resolved
.add_system(
update
.in_base_set(GameSet::PostUpdate)
.run_if(in_state(GameState::Playing)),
)
.add_system(clean_up.in_schedule(OnExit(GameState::Playing)));
}
}

fn spawn_details(mut commands: Commands) {
commands.spawn((
NodeBundle {
style: Style {
#[derive(Resource)]
struct DetailsText(Entity);

fn setup(mut commands: GuiCommands) {
let node = commands
.spawn((
NodeBundle {
style: Style {
size: Size {
width: Val::Percent(20.),
height: Val::Percent(30.),
},
position_type: PositionType::Absolute,
position: UiRect::new(
Val::Percent(0.),
Val::Percent(20.),
Val::Percent(70.),
Val::Percent(100.),
),
..default()
},
background_color: HUD_COLOR.into(),
..default()
},
DespawnOnGameExit,
InteractionBlocker,
))
.id();
let details_text = commands
.spawn_body_text(
OuterStyle {
size: Size {
width: Val::Percent(20.),
height: Val::Percent(30.),
},
position_type: PositionType::Absolute,
position: UiRect::new(
Val::Percent(0.),
Val::Percent(20.),
Val::Percent(70.),
Val::Percent(100.),
),
..default()
margin: UiRect::all(Val::Percent(5.)),
},
background_color: HUD_COLOR.into(),
..default()
},
DespawnOnGameExit,
InteractionBlocker,
));
"",
)
.id();
commands.entity(node).add_child(details_text);

commands.insert_resource(DetailsText(details_text));
}

fn format_units(value: f64, units: &str) -> String {
JackCrumpLeys marked this conversation as resolved.
Show resolved Hide resolved
let mut value = value;
let mut i = 0;

while value >= 1000.0 && i < PREFIXES.len() - 1 {
value /= 1000.0;
i += 1;
}

format!("{}{}{}", most_significant(value), PREFIXES[i], units)
}

fn most_significant(value: f64) -> f64 {
if value == 0.0 {
0.0
} else {
let d = 3 - value.abs().log10().ceil() as i32;
let p = 10f64.powi(d);
(value * p).round() / p
}
}

fn update(
ui: Res<DetailsText>,
selected: Query<Entity, With<Selected>>,
battery: Query<&Battery>,
mut text_ops: BodyTextOps,
) {
let mut battery_total = 0.;
let mut battery_max = 0.;
let mut selected_count = 0;

for entity in selected.iter() {
if let Ok(battery) = battery.get(entity) {
selected_count += 1;

battery_total += battery.energy();
battery_max += battery.capacity();
}
}

if battery_max == 0. {
text_ops
.set_text(ui.0, "")
.expect("Failed to set text of details");
return;
JackCrumpLeys marked this conversation as resolved.
Show resolved Hide resolved
}

let text = format!(
JackCrumpLeys marked this conversation as resolved.
Show resolved Hide resolved
"Battery: {} / {} ({:.1}%)\nSelected {}",
format_units(battery_total, "J"),
format_units(battery_max, "J"),
battery_total * 100. / battery_max,
selected_count,
);

text_ops
.set_text(ui.0, text)
.expect("Failed to set text of details");
}

fn clean_up(mut commands: Commands) {
// remove DetailsText
commands.remove_resource::<DetailsText>()
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_format_units() {
assert_eq!(format_units(-1.0, "J"), "-1J");
assert_eq!(format_units(0.0, "J"), "0J");
assert_eq!(format_units(1.0, "J"), "1J");
assert_eq!(format_units(10.0, "J"), "10J");
assert_eq!(format_units(100.0, "J"), "100J");
assert_eq!(format_units(673.0, "J"), "673J");
assert_eq!(format_units(1000.0, "J"), "1kJ");
assert_eq!(format_units(10000.0, "J"), "10kJ");
assert_eq!(format_units(100000.0, "J"), "100kJ");
assert_eq!(format_units(590385.0, "J"), "590kJ");
assert_eq!(format_units(1000000.0, "J"), "1MJ");
assert_eq!(format_units(10000000.0, "J"), "10MJ");
assert_eq!(format_units(100000000.0, "J"), "100MJ");
assert_eq!(format_units(339484857.0, "J"), "339MJ");
assert_eq!(format_units(1000000000.0, "J"), "1GJ");
assert_eq!(format_units(10000000000.0, "J"), "10GJ");
assert_eq!(format_units(100000000000.0, "J"), "100GJ");
assert_eq!(format_units(1000000000000.0, "J"), "1TJ");
assert_eq!(format_units(10000000000000.0, "J"), "10TJ");
assert_eq!(format_units(100000000000000.0, "J"), "100TJ");
}
}
80 changes: 80 additions & 0 deletions crates/gui/src/body_text.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
use bevy::{
ecs::system::{EntityCommands, SystemParam},
prelude::*,
};

use crate::{GuiCommands, OuterStyle};

/// marker component for UI `BasicText`
#[derive(Component)]
struct BodyText;

pub trait BodyTextCommands<'w, 's> {
fn spawn_body_text<'a>(
&'a mut self,
size: OuterStyle,
caption: impl Into<String>,
) -> EntityCommands<'w, 's, 'a>;
}

impl<'w, 's> BodyTextCommands<'w, 's> for GuiCommands<'w, 's> {
fn spawn_body_text<'a>(
&'a mut self,
style: OuterStyle,
caption: impl Into<String>,
) -> EntityCommands<'w, 's, 'a> {
let text_style = self.text_props().body_text_style();

let mut commands = self.spawn((
NodeBundle {
style: Style {
justify_content: JustifyContent::FlexStart,
align_items: AlignItems::FlexStart,
size: style.size,
margin: style.margin,
..default()
},
..default()
},
BodyText,
));

commands.with_children(|builder| {
builder.spawn(TextBundle::from_section(caption, text_style));
});

commands
Indy2222 marked this conversation as resolved.
Show resolved Hide resolved
}
}

#[derive(SystemParam)]
pub struct BodyTextOps<'w, 's> {
body_text_query: Query<'w, 's, &'static Children, With<BodyText>>,
text_query: Query<'w, 's, &'static mut Text>,
}

impl<'w, 's> BodyTextOps<'w, 's> {
/// This method changes text (e.g. caption) of UI body text.
pub fn set_text(&mut self, entity: Entity, text: impl Into<String>) -> Result<(), &str> {
let text = text.into();
let children = match self.body_text_query.get(entity) {
Ok(children) => children,
Err(e) => {
trace!("BodyText does not exist. {:?}", e);
return Err("BodyText does not exist.");
}
};
for &child in children.iter() {
if let Ok(mut text_component) = self.text_query.get_mut(child) {
if text_component.sections[0].value == text {
// avoid unnecessary update
return Ok(());
}
text_component.sections[0].value = text;
return Ok(());
}
}
trace!("BodyText does not have a child with Text component.");
Err("BodyText does not have a child with Text component.")
JackCrumpLeys marked this conversation as resolved.
Show resolved Hide resolved
}
}
3 changes: 3 additions & 0 deletions crates/gui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//! game.

use bevy::{app::PluginGroupBuilder, prelude::PluginGroup};
pub use body_text::{BodyTextCommands, BodyTextOps};
use button::ButtonPlugin;
pub use button::{ButtonCommands, ButtonOps};
pub use commands::GuiCommands;
Expand All @@ -11,11 +12,13 @@ pub use focus::SetFocusEvent;
pub use label::LabelCommands;
pub use style::OuterStyle;
use text::TextPlugin;
pub use text::TextProps;
use textbox::TextBoxPlugin;
pub use textbox::{TextBoxCommands, TextBoxQuery};
use toast::ToastPlugin;
pub use toast::{ToastEvent, ToastSet};

mod body_text;
mod button;
mod commands;
mod focus;
Expand Down
8 changes: 8 additions & 0 deletions crates/gui/src/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ impl TextProps {
}
}

pub(crate) fn body_text_style(&self) -> TextStyle {
TextStyle {
font: self.font(),
font_size: 16.0,
color: Color::rgb(0.9, 0.9, 0.9),
}
}

fn font(&self) -> Handle<Font> {
self.0.clone()
}
Expand Down