Do some cleanup

This commit is contained in:
Tobias Berger 2022-09-06 20:40:27 +02:00
parent f6ec1ba1a2
commit 329acb37f0
Signed by: toby
GPG key ID: 2D05EFAB764D6A88
10 changed files with 191 additions and 189 deletions

View file

@ -11,6 +11,7 @@ default = ["render", "debug"]
[dependencies.save] [dependencies.save]
path = "save" path = "save"
default-features = false
[dependencies.bevy] [dependencies.bevy]
version = "0.8" version = "0.8"

View file

@ -6,6 +6,7 @@ edition = "2021"
[features] [features]
debug = [] debug = []
render = ["bevy/render"] render = ["bevy/render"]
default = ["render", "debug"]
[dependencies.noise] [dependencies.noise]
version = "0.7.0" version = "0.7.0"

View file

@ -1,6 +1,7 @@
#[cfg(feature = "render")] #[cfg(feature = "render")]
use crate::TerrainCell; use crate::TerrainCell;
use crate::{World, WorldGenError}; use crate::{World, WorldGenError};
#[cfg(all(feature = "debug", feature = "render"))]
use bevy::log::debug; use bevy::log::debug;
#[cfg(feature = "render")] #[cfg(feature = "render")]
use bevy::{ use bevy::{
@ -28,14 +29,18 @@ impl WorldManager {
#[cfg(feature = "render")] #[cfg(feature = "render")]
image_handle_id: HandleId::default::<Image>(), image_handle_id: HandleId::default::<Image>(),
world: None, world: None,
#[cfg(feature = "render")]
rainfall_visible: false, rainfall_visible: false,
#[cfg(feature = "render")]
temperature_visible: false, temperature_visible: false,
#[cfg(feature = "render")]
terrain_as_contours: false, terrain_as_contours: false,
} }
} }
#[cfg(feature = "render")] #[cfg(feature = "render")]
pub fn toggle_rainfall(&mut self) { pub fn toggle_rainfall(&mut self) {
#[cfg(feature = "debug")]
if self.rainfall_visible { if self.rainfall_visible {
debug!("Turning rainfall off"); debug!("Turning rainfall off");
} else { } else {
@ -46,6 +51,7 @@ impl WorldManager {
#[cfg(feature = "render")] #[cfg(feature = "render")]
pub fn toggle_temperature(&mut self) { pub fn toggle_temperature(&mut self) {
#[cfg(feature = "debug")]
if self.temperature_visible { if self.temperature_visible {
debug!("Turning temperature off"); debug!("Turning temperature off");
} else { } else {
@ -56,6 +62,7 @@ impl WorldManager {
#[cfg(feature = "render")] #[cfg(feature = "render")]
pub fn toggle_contours(&mut self) { pub fn toggle_contours(&mut self) {
#[cfg(feature = "debug")]
if self.terrain_as_contours { if self.terrain_as_contours {
debug!("Turning terrain contours off"); debug!("Turning terrain contours off");
} else { } else {

14
src/components/markers.rs Normal file
View file

@ -0,0 +1,14 @@
#[cfg(feature = "render")]
use bevy::ecs::component::Component;
#[cfg(feature = "render")]
#[derive(Component)]
pub(crate) enum ToolbarButton {
Rainfall,
Temperature,
Contours,
}
#[cfg(feature = "render")]
#[derive(Component)]
pub(crate) struct InfoPanel;

6
src/components/mod.rs Normal file
View file

@ -0,0 +1,6 @@
pub(crate) mod markers;
pub(crate) mod third_party {
#[cfg(feature = "render")]
pub(crate) use bevy_pancam::PanCam;
}

View file

@ -32,25 +32,25 @@
#![warn(unused_results)] #![warn(unused_results)]
#![warn(variant_size_differences)] #![warn(variant_size_differences)]
mod components;
mod plugins; mod plugins;
mod resources;
use std::fmt::Display; mod ui_helpers;
use bevy::{ use bevy::{
app::App, app::App,
log::{debug, LogSettings}, log::LogSettings,
utils::tracing::Level, utils::{default, tracing::Level},
}; };
#[cfg(feature = "render")] #[cfg(feature = "render")]
use bevy::{ use bevy::{
asset::{AssetServer, Assets, Handle}, asset::{AssetServer, Assets, Handle},
core_pipeline::{ core_pipeline::{
core_2d::{Camera2d, Camera2dBundle}, core_2d::{Camera2d, Camera2dBundle},
core_3d::{Camera3d, Camera3dBundle}, core_3d::Camera3dBundle,
}, },
ecs::{ ecs::{
change_detection::ResMut, change_detection::ResMut,
component::Component,
query::{Changed, With}, query::{Changed, With},
system::{Commands, Query, Res}, system::{Commands, Query, Res},
}, },
@ -70,22 +70,33 @@ use bevy::{
text::Text, text::Text,
transform::components::{GlobalTransform, Transform}, transform::components::{GlobalTransform, Transform},
ui::{ ui::{
entity::{ButtonBundle, NodeBundle, TextBundle}, entity::{NodeBundle, TextBundle},
widget::Button, AlignSelf, FocusPolicy, Interaction, JustifyContent, PositionType, Size, Style, UiColor,
AlignItems, AlignSelf, FocusPolicy, Interaction, JustifyContent, PositionType, Size, Style, UiRect, Val,
UiColor, UiRect, Val,
}, },
utils::default,
window::{CursorIcon, WindowDescriptor, Windows}, window::{CursorIcon, WindowDescriptor, Windows},
winit::WinitSettings, winit::WinitSettings,
}; };
#[cfg(all(feature = "debug", feature = "render"))]
use bevy::{
diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin},
log::debug,
};
#[cfg(feature = "render")] #[cfg(feature = "render")]
use plugins::PanCam; use components::{
markers::{InfoPanel, ToolbarButton},
third_party::PanCam,
};
use plugins::WorldPlugins; use plugins::WorldPlugins;
#[cfg(feature = "render")]
use resources::CursorMapPosition;
use save::*; use save::*;
#[cfg(feature = "render")]
use ui_helpers::{toolbar_button, toolbar_button_text};
#[cfg(feature = "render")] #[cfg(feature = "render")]
fn refresh_world_texture(images: &mut Assets<Image>, world_manager: &WorldManager) { fn refresh_world_texture(images: &mut Assets<Image>, world_manager: &WorldManager) {
#[cfg(feature = "debug")]
debug!("refreshing world texture"); debug!("refreshing world texture");
let image_handle = images.get_handle(world_manager.image_handle_id); let image_handle = images.get_handle(world_manager.image_handle_id);
images.get_mut(&image_handle).unwrap().data = world_manager.world_color_bytes(); images.get_mut(&image_handle).unwrap().data = world_manager.world_color_bytes();
@ -94,121 +105,45 @@ fn refresh_world_texture(images: &mut Assets<Image>, world_manager: &WorldManage
} }
#[cfg(feature = "render")] #[cfg(feature = "render")]
#[derive(Component)]
struct RainfallButton;
#[cfg(feature = "render")]
#[derive(Component)]
struct TemperatureButton;
#[cfg(feature = "render")]
#[derive(Component)]
struct ContoursButton;
#[cfg(feature = "render")]
#[derive(Component)]
struct InfoPanel;
#[cfg(feature = "render")]
#[derive(Default, Debug)]
struct CursorMapPosition {
x: i32,
y: i32,
}
impl Display for CursorMapPosition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("x: {}, y: {}", self.x, self.y))
}
}
const NORMAL_BUTTON: Color = Color::rgb(0.15, 0.15, 0.15); const NORMAL_BUTTON: Color = Color::rgb(0.15, 0.15, 0.15);
#[cfg(feature = "render")]
const HOVERED_BUTTON: Color = Color::rgb(0.25, 0.25, 0.25); const HOVERED_BUTTON: Color = Color::rgb(0.25, 0.25, 0.25);
#[cfg(feature = "render")]
const PRESSED_BUTTON: Color = Color::rgb(0.35, 0.60, 0.35); const PRESSED_BUTTON: Color = Color::rgb(0.35, 0.60, 0.35);
#[cfg(feature = "render")] #[cfg(feature = "render")]
fn handle_rainfall_button( fn handle_toolbar_button(
mut interaction_query: Query< mut interaction_query: Query<
'_, '_,
'_, '_,
(&Interaction, &mut UiColor), (&Interaction, &mut UiColor, &ToolbarButton),
(Changed<Interaction>, With<RainfallButton>), Changed<Interaction>,
>, >,
mut windows: ResMut<'_, Windows>, mut windows: ResMut<'_, Windows>,
mut images: ResMut<'_, Assets<Image>>, mut images: ResMut<'_, Assets<Image>>,
mut world_manager: ResMut<'_, WorldManager>, mut world_manager: ResMut<'_, WorldManager>,
) { ) {
for (interaction, mut color) in &mut interaction_query { for (interaction, mut color, toolbar_button) in &mut interaction_query {
match *interaction { match *interaction {
Interaction::Clicked => { Interaction::Clicked => {
windows.primary_mut().set_cursor_icon(CursorIcon::Default); windows.primary_mut().set_cursor_icon(CursorIcon::Default);
*color = PRESSED_BUTTON.into(); *color = PRESSED_BUTTON.into();
match toolbar_button {
ToolbarButton::Rainfall => {
#[cfg(feature = "debug")]
debug!("Toggling rainfall"); debug!("Toggling rainfall");
world_manager.toggle_rainfall(); world_manager.toggle_rainfall();
refresh_world_texture(&mut images, &world_manager)
} }
Interaction::Hovered => { ToolbarButton::Temperature => {
windows.primary_mut().set_cursor_icon(CursorIcon::Hand); #[cfg(feature = "debug")]
*color = HOVERED_BUTTON.into();
}
Interaction::None => {
windows.primary_mut().set_cursor_icon(CursorIcon::Default);
*color = NORMAL_BUTTON.into();
}
}
}
}
#[cfg(feature = "render")]
fn handle_temperature_button(
mut interaction_query: Query<
'_,
'_,
(&Interaction, &mut UiColor),
(Changed<Interaction>, With<TemperatureButton>),
>,
mut windows: ResMut<'_, Windows>,
mut images: ResMut<'_, Assets<Image>>,
mut world_manager: ResMut<'_, WorldManager>,
) {
for (interaction, mut color) in &mut interaction_query {
match *interaction {
Interaction::Clicked => {
windows.primary_mut().set_cursor_icon(CursorIcon::Default);
*color = PRESSED_BUTTON.into();
debug!("Toggling temperature"); debug!("Toggling temperature");
world_manager.toggle_temperature(); world_manager.toggle_temperature();
refresh_world_texture(&mut images, &world_manager)
} }
Interaction::Hovered => { ToolbarButton::Contours => {
windows.primary_mut().set_cursor_icon(CursorIcon::Hand); #[cfg(feature = "debug")]
*color = HOVERED_BUTTON.into();
}
Interaction::None => {
windows.primary_mut().set_cursor_icon(CursorIcon::Default);
*color = NORMAL_BUTTON.into();
}
}
}
}
#[cfg(feature = "render")]
fn handle_contours_button(
mut interaction_query: Query<
'_,
'_,
(&Interaction, &mut UiColor),
(Changed<Interaction>, With<ContoursButton>),
>,
mut windows: ResMut<'_, Windows>,
mut images: ResMut<'_, Assets<Image>>,
mut world_manager: ResMut<'_, WorldManager>,
) {
for (interaction, mut color) in &mut interaction_query {
match *interaction {
Interaction::Clicked => {
windows.primary_mut().set_cursor_icon(CursorIcon::Default);
*color = PRESSED_BUTTON.into();
debug!("Toggling contours"); debug!("Toggling contours");
world_manager.toggle_contours(); world_manager.toggle_contours();
}
}
refresh_world_texture(&mut images, &world_manager) refresh_world_texture(&mut images, &world_manager)
} }
Interaction::Hovered => { Interaction::Hovered => {
@ -254,6 +189,7 @@ fn update_cursor_map_position(
} }
} }
#[cfg(feature = "render")]
const ROTATION_SPEED: f32 = 0.002; const ROTATION_SPEED: f32 = 0.002;
#[cfg(feature = "render")] #[cfg(feature = "render")]
fn rotate_planet(mut planet_transform: Query<'_, '_, &mut Transform, With<Handle<Mesh>>>) { fn rotate_planet(mut planet_transform: Query<'_, '_, &mut Transform, With<Handle<Mesh>>>) {
@ -262,6 +198,7 @@ fn rotate_planet(mut planet_transform: Query<'_, '_, &mut Transform, With<Handle
#[cfg(feature = "render")] #[cfg(feature = "render")]
fn update_info_panel( fn update_info_panel(
#[cfg(feature = "debug")] diagnostics: Res<'_, Diagnostics>,
cursor_position: Res<'_, CursorMapPosition>, cursor_position: Res<'_, CursorMapPosition>,
world_manager: Res<'_, WorldManager>, world_manager: Res<'_, WorldManager>,
mut text: Query<'_, '_, &mut Text, With<InfoPanel>>, mut text: Query<'_, '_, &mut Text, With<InfoPanel>>,
@ -273,10 +210,27 @@ fn update_info_panel(
&& cursor_position.y < world.height && cursor_position.y < world.height
{ {
let cell = &world.terrain[cursor_position.y as usize][cursor_position.x as usize]; let cell = &world.terrain[cursor_position.y as usize][cursor_position.x as usize];
#[cfg(feature = "debug")]
{
format!(
"FPS: {}\nMouse position: {}\nAltitude: {}\nRainfall: {}\nTemperature: {}",
match diagnostics.get_measurement(FrameTimeDiagnosticsPlugin::FPS) {
None => f64::NAN,
Some(fps) => fps.value,
},
*cursor_position,
cell.altitude,
cell.rainfall,
cell.temperature
)
}
#[cfg(not(feature = "debug"))]
{
format!( format!(
"Mouse position: {}\nAltitude: {}\nRainfall: {}\nTemperature: {}", "Mouse position: {}\nAltitude: {}\nRainfall: {}\nTemperature: {}",
*cursor_position, cell.altitude, cell.rainfall, cell.temperature *cursor_position, cell.altitude, cell.rainfall, cell.temperature
) )
}
} else { } else {
format!("Mouse position: {}\nOut of bounds", *cursor_position) format!("Mouse position: {}\nOut of bounds", *cursor_position)
}; };
@ -412,84 +366,37 @@ fn generate_graphics(
}) })
.with_children(|button_box| { .with_children(|button_box| {
_ = button_box _ = button_box
.spawn_bundle(ButtonBundle { .spawn_bundle(toolbar_button())
button: Button,
style: Style {
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
color: NORMAL_BUTTON.into(),
..default()
})
.insert(RainfallButton)
.with_children(|button| { .with_children(|button| {
_ = button.spawn_bundle(TextBundle { _ = button.spawn_bundle(toolbar_button_text(
text: bevy::text::Text::from_section( &asset_server,
"Toggle rainfall", ToolbarButton::Rainfall,
bevy::text::TextStyle { ));
font: asset_server.load("JuliaMono.ttf"), })
font_size: 20.0, .insert(ToolbarButton::Rainfall);
color: Color::WHITE,
},
),
..default()
});
});
_ = button_box _ = button_box
.spawn_bundle(ButtonBundle { .spawn_bundle(toolbar_button())
button: Button,
style: Style {
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
color: NORMAL_BUTTON.into(),
..default()
})
.insert(TemperatureButton)
.with_children(|button| { .with_children(|button| {
_ = button.spawn_bundle(TextBundle { _ = button.spawn_bundle(toolbar_button_text(
text: bevy::text::Text::from_section( &asset_server,
"Toggle temperature", ToolbarButton::Temperature,
bevy::text::TextStyle { ));
font: asset_server.load("JuliaMono.ttf"), })
font_size: 20.0, .insert(ToolbarButton::Temperature);
color: Color::WHITE,
},
),
..default()
});
});
_ = button_box _ = button_box
.spawn_bundle(ButtonBundle { .spawn_bundle(toolbar_button())
button: Button,
style: Style {
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
color: NORMAL_BUTTON.into(),
..default()
})
.insert(ContoursButton)
.with_children(|button| { .with_children(|button| {
_ = button.spawn_bundle(TextBundle { _ = button.spawn_bundle(toolbar_button_text(
text: bevy::text::Text::from_section( &asset_server,
"Toggle contours", ToolbarButton::Contours,
bevy::text::TextStyle { ));
font: asset_server.load("JuliaMono.ttf"), })
font_size: 20.0, .insert(ToolbarButton::Contours);
color: Color::WHITE,
},
),
..default()
});
});
}); });
}); });
} }
#[cfg(feature = "render")]
const WORLD_SCALE: i32 = 3; const WORLD_SCALE: i32 = 3;
fn main() -> Result<(), Box<dyn std::error::Error>> { fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut app = App::new(); let mut app = App::new();
@ -510,9 +417,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}) })
.insert_resource(CursorMapPosition::default()) .insert_resource(CursorMapPosition::default())
.add_startup_system(generate_graphics) .add_startup_system(generate_graphics)
.add_system(handle_rainfall_button) .add_system(handle_toolbar_button)
.add_system(handle_temperature_button)
.add_system(handle_contours_button)
.add_system(update_cursor_map_position) .add_system(update_cursor_map_position)
.add_system(update_info_panel) .add_system(update_info_panel)
.add_system(rotate_planet); .add_system(rotate_planet);

View file

@ -1,4 +1,2 @@
pub(crate) mod world_plugins; pub(crate) mod world_plugins;
pub(crate) use world_plugins::WorldPlugins; pub(crate) use world_plugins::WorldPlugins;
pub(crate) use bevy_pancam::PanCam;

View file

@ -40,6 +40,10 @@ impl PluginGroup for WorldPlugins {
.add(UiPlugin::default()) .add(UiPlugin::default())
.add(PbrPlugin::default()) .add(PbrPlugin::default())
.add(PanCamPlugin::default()); .add(PanCamPlugin::default());
#[cfg(feature = "debug")]
{
_ = group.add(FrameTimeDiagnosticsPlugin::default());
}
} }
#[cfg(not(feature = "render"))] #[cfg(not(feature = "render"))]
{ {

15
src/resources/mod.rs Normal file
View file

@ -0,0 +1,15 @@
#[cfg(feature = "render")]
use std::fmt::Display;
#[cfg(feature = "render")]
#[derive(Default, Debug)]
pub(crate) struct CursorMapPosition {
pub(crate) x: i32,
pub(crate) y: i32,
}
#[cfg(feature = "render")]
impl Display for CursorMapPosition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("x: {}, y: {}", self.x, self.y))
}
}

51
src/ui_helpers.rs Normal file
View file

@ -0,0 +1,51 @@
#[cfg(feature = "render")]
use bevy::{
asset::AssetServer,
ecs::system::Res,
render::color::Color,
ui::{
entity::{ButtonBundle, TextBundle},
widget::Button,
AlignItems, JustifyContent, Style,
},
utils::default,
};
#[cfg(feature = "render")]
use crate::{components::markers::ToolbarButton, NORMAL_BUTTON};
#[cfg(feature = "render")]
pub(crate) fn toolbar_button() -> ButtonBundle {
ButtonBundle {
button: Button,
style: Style {
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
color: NORMAL_BUTTON.into(),
..default()
}
}
#[cfg(feature = "render")]
pub(crate) fn toolbar_button_text(
asset_server: &Res<'_, AssetServer>,
which: ToolbarButton,
) -> TextBundle {
TextBundle {
text: bevy::text::Text::from_section(
match which {
ToolbarButton::Rainfall => "Toggle rainfall",
ToolbarButton::Temperature => "Toggle temperature",
ToolbarButton::Contours => "Toggle contours",
},
bevy::text::TextStyle {
font: asset_server.load("JuliaMono.ttf"),
font_size: 20.0,
color: Color::WHITE,
},
),
..default()
}
}