Add rustfmt config

This commit is contained in:
Tobias Berger 2022-09-19 10:54:10 +02:00
parent fb78c618e4
commit 81df0cd02f
Signed by: toby
GPG key ID: 2D05EFAB764D6A88
10 changed files with 259 additions and 207 deletions

11
planet/rustfmt.toml Normal file
View file

@ -0,0 +1,11 @@
imports_granularity = "One"
group_imports = "One"
enum_discrim_align_threshold = 15
imports_layout = "HorizontalVertical"
match_block_trailing_comma = true
newline_style = "Native"
reorder_impl_items = true
struct_field_align_threshold = 20
use_field_init_shorthand = true
use_try_shorthand = true
wrap_comments = true

View file

@ -1,9 +1,9 @@
use serde::{Deserialize, Serialize};
#[cfg(feature = "render")] #[cfg(feature = "render")]
use bevy::render::color::Color; use bevy::render::color::Color;
use {
use crate::World; crate::World,
serde::{Deserialize, Serialize},
};
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct Biome { pub struct Biome {

View file

@ -1,12 +1,13 @@
use std::{ use {
bevy::math::Vec3A,
rand::{rngs::StdRng, Rng},
std::{
error::Error, error::Error,
f32::consts::{PI, TAU}, f32::consts::{PI, TAU},
fmt::{Debug, Display}, fmt::{Debug, Display},
},
}; };
use bevy::math::Vec3A;
use rand::{rngs::StdRng, Rng};
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
pub enum CartesianError { pub enum CartesianError {
InvalidAlpha(f32), InvalidAlpha(f32),
@ -29,7 +30,7 @@ impl Display for CartesianError {
match self { match self {
CartesianError::InvalidAlpha(alpha) => { CartesianError::InvalidAlpha(alpha) => {
f.write_fmt(format_args!("Alpha value must be [0..PI], was {}", alpha)) f.write_fmt(format_args!("Alpha value must be [0..PI], was {}", alpha))
} },
} }
} }
} }

View file

@ -1,13 +1,13 @@
use std::fmt::{self, Formatter}; use {
crate::{TerrainCell, World},
use rand::{rngs::StdRng, SeedableRng}; rand::{rngs::StdRng, SeedableRng},
use serde::{ serde::{
de::{Error, MapAccess, SeqAccess, Visitor}, de::{Error, MapAccess, SeqAccess, Visitor},
Deserialize, Deserialize,
},
std::fmt::{self, Formatter},
}; };
use crate::{TerrainCell, World};
struct WorldTerrainAttributes { struct WorldTerrainAttributes {
max_altitude: f32, max_altitude: f32,
min_altitude: f32, min_altitude: f32,
@ -148,37 +148,37 @@ impl<'de> Deserialize<'de> for World {
return Err(Error::duplicate_field("width")); return Err(Error::duplicate_field("width"));
} }
width = Some(map.next_value()?); width = Some(map.next_value()?);
} },
Field::Height => { Field::Height => {
if height.is_some() { if height.is_some() {
return Err(Error::duplicate_field("height")); return Err(Error::duplicate_field("height"));
} }
height = Some(map.next_value()?); height = Some(map.next_value()?);
} },
Field::Seed => { Field::Seed => {
if seed.is_some() { if seed.is_some() {
return Err(Error::duplicate_field("seed")); return Err(Error::duplicate_field("seed"));
} }
seed = Some(map.next_value()?); seed = Some(map.next_value()?);
} },
Field::Terrain => { Field::Terrain => {
if terrain.is_some() { if terrain.is_some() {
return Err(Error::duplicate_field("terrain")); return Err(Error::duplicate_field("terrain"));
} }
terrain = Some(map.next_value()?); terrain = Some(map.next_value()?);
} },
Field::ContinentOffsets => { Field::ContinentOffsets => {
if continent_offsets.is_some() { if continent_offsets.is_some() {
return Err(Error::duplicate_field("continent_offsets")); return Err(Error::duplicate_field("continent_offsets"));
} }
continent_offsets = Some(map.next_value()?); continent_offsets = Some(map.next_value()?);
} },
Field::ContinentWidths => { Field::ContinentWidths => {
if continent_widths.is_some() { if continent_widths.is_some() {
return Err(Error::duplicate_field("continent_widths")); return Err(Error::duplicate_field("continent_widths"));
} }
continent_widths = Some(map.next_value()?); continent_widths = Some(map.next_value()?);
} },
} }
} }

View file

@ -1,18 +1,25 @@
use serde::{Deserialize, Serialize}; // TODO: Logging doesn't seem to work here? Figure out why and fix
use std::{ use {
crate::{
biome::BiomeType,
cartesian_coordinates,
mix_values,
perlin,
random_point_in_sphere,
Biome,
CartesianError,
RepeatNum,
},
bevy::{log::info, math::Vec3A, prelude::Vec2, utils::default},
rand::{rngs::StdRng, Rng, SeedableRng},
serde::{Deserialize, Serialize},
std::{
error::Error, error::Error,
f32::consts::{PI, TAU}, f32::consts::{PI, TAU},
fmt::{Debug, Display}, fmt::{Debug, Display},
},
}; };
// TODO: Logging doesn't seem to work here? Figure out why and fix
use crate::{biome::BiomeType, perlin, Biome};
use bevy::{log::info, math::Vec3A, prelude::Vec2, utils::default};
use rand::{rngs::StdRng, Rng, SeedableRng};
use crate::{cartesian_coordinates, mix_values, random_point_in_sphere, CartesianError, RepeatNum};
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum WorldGenError { pub enum WorldGenError {
CartesianError(CartesianError), CartesianError(CartesianError),
@ -75,6 +82,28 @@ pub struct TerrainCell {
} }
impl World { impl World {
const ALTITUDE_SPAN: f32 = World::MAX_ALTITUDE - World::MIN_ALTITUDE;
const CONTINENT_MAX_WIDTH_FACTOR: f32 = 7.0;
const CONTINENT_MIN_WIDTH_FACTOR: f32 = 3.0;
pub(crate) const MAX_ALTITUDE: f32 = 15000.0;
pub(crate) const MAX_RAINFALL: f32 = 7500.0;
pub(crate) const MAX_TEMPERATURE: f32 = 30.0;
pub(crate) const MIN_ALTITUDE: f32 = -15000.0;
pub(crate) const MIN_RAINFALL: f32 = 0.0;
pub(crate) const MIN_TEMPERATURE: f32 = -60.0;
const MOUNTAIN_RANGE_MIX_FACTOR: f32 = 0.075;
const MOUNTAIN_RANGE_WIDTH_FACTOR: f32 = 25.0;
const NUM_CONTINENTS: u8 = 7;
const RAINFALL_DRYNESS_FACTOR: f32 = 0.005;
const RAINFALL_DRYNESS_OFFSET: f32 = World::RAINFALL_DRYNESS_FACTOR * World::MAX_RAINFALL;
const RAINFALL_SPAN: f32 = World::MAX_RAINFALL - World::MIN_RAINFALL;
const TEMPERATURE_ALTITUDE_FACTOR: f32 = 1.0;
const TEMPERATURE_SPAN: f32 = World::MAX_TEMPERATURE - World::MIN_TEMPERATURE;
const TERRAIN_NOISE_FACTOR_1: f32 = 0.15;
const TERRAIN_NOISE_FACTOR_2: f32 = 0.15;
const TERRAIN_NOISE_FACTOR_3: f32 = 0.1;
const TERRAIN_NOISE_FACTOR_4: f32 = 2.5;
pub fn new(width: u32, height: u32, seed: u32) -> World { pub fn new(width: u32, height: u32, seed: u32) -> World {
World { World {
width, width,
@ -96,33 +125,6 @@ impl World {
} }
} }
const NUM_CONTINENTS: u8 = 7;
const CONTINENT_MIN_WIDTH_FACTOR: f32 = 3.0;
const CONTINENT_MAX_WIDTH_FACTOR: f32 = 7.0;
pub(crate) const MIN_ALTITUDE: f32 = -15000.0;
pub(crate) const MAX_ALTITUDE: f32 = 15000.0;
const ALTITUDE_SPAN: f32 = World::MAX_ALTITUDE - World::MIN_ALTITUDE;
const MOUNTAIN_RANGE_MIX_FACTOR: f32 = 0.075;
const MOUNTAIN_RANGE_WIDTH_FACTOR: f32 = 25.0;
const TERRAIN_NOISE_FACTOR_1: f32 = 0.15;
const TERRAIN_NOISE_FACTOR_2: f32 = 0.15;
const TERRAIN_NOISE_FACTOR_3: f32 = 0.1;
const TERRAIN_NOISE_FACTOR_4: f32 = 2.5;
pub(crate) const MIN_RAINFALL: f32 = 0.0;
pub(crate) const MAX_RAINFALL: f32 = 7500.0;
const RAINFALL_SPAN: f32 = World::MAX_RAINFALL - World::MIN_RAINFALL;
const RAINFALL_DRYNESS_FACTOR: f32 = 0.005;
const RAINFALL_DRYNESS_OFFSET: f32 = World::RAINFALL_DRYNESS_FACTOR * World::MAX_RAINFALL;
pub(crate) const MIN_TEMPERATURE: f32 = -60.0;
pub(crate) const MAX_TEMPERATURE: f32 = 30.0;
const TEMPERATURE_SPAN: f32 = World::MAX_TEMPERATURE - World::MIN_TEMPERATURE;
const TEMPERATURE_ALTITUDE_FACTOR: f32 = 1.0;
pub fn generate(&mut self) -> Result<(), WorldGenError> { pub fn generate(&mut self) -> Result<(), WorldGenError> {
if let Err(err) = self.generate_altitude() { if let Err(err) = self.generate_altitude() {
return Err(WorldGenError::CartesianError(err)); return Err(WorldGenError::CartesianError(err));

View file

@ -1,9 +1,7 @@
#[cfg(feature = "render")] #[cfg(feature = "render")]
use crate::TerrainCell; use crate::TerrainCell;
use crate::{Biome, World, WorldGenError};
#[cfg(all(feature = "debug", feature = "render"))] #[cfg(all(feature = "debug", feature = "render"))]
use bevy::log::debug; use bevy::log::debug;
use bevy::log::warn;
#[cfg(feature = "debug")] #[cfg(feature = "debug")]
use bevy::utils::default; use bevy::utils::default;
#[cfg(feature = "render")] #[cfg(feature = "render")]
@ -12,13 +10,17 @@ use bevy::{
render::render_resource::Extent3d, render::render_resource::Extent3d,
render::{color::Color, texture::Image}, render::{color::Color, texture::Image},
}; };
use rand::random; use {
use std::{ crate::{Biome, World, WorldGenError},
bevy::log::warn,
rand::random,
std::{
error::Error, error::Error,
fmt::Display, fmt::Display,
fs::File, fs::File,
io::{self, Read, Write}, io::{self, Read, Write},
path::Path, path::Path,
},
}; };
#[derive(Debug)] #[derive(Debug)]
@ -86,9 +88,9 @@ impl Display for SaveError {
#[derive(Debug)] #[derive(Debug)]
pub struct WorldManager { pub struct WorldManager {
world: Option<World>,
#[cfg(feature = "render")] #[cfg(feature = "render")]
pub image_handle_id: Option<HandleId>, pub image_handle_id: Option<HandleId>,
world: Option<World>,
#[cfg(feature = "render")] #[cfg(feature = "render")]
rainfall_visible: bool, rainfall_visible: bool,
#[cfg(feature = "render")] #[cfg(feature = "render")]
@ -122,14 +124,14 @@ impl WorldManager {
None => { None => {
warn!("No world to save"); warn!("No world to save");
return Err(SaveError::MissingWorld); return Err(SaveError::MissingWorld);
} },
}; };
#[cfg(feature = "debug")] #[cfg(feature = "debug")]
let serialized = match ron::ser::to_string_pretty(world, default()) { let serialized = match ron::ser::to_string_pretty(world, default()) {
Ok(serialized) => serialized, Ok(serialized) => serialized,
Err(err) => { Err(err) => {
return Err(SaveError::SerializationError(err)); return Err(SaveError::SerializationError(err));
} },
}; };
#[cfg(not(feature = "debug"))] #[cfg(not(feature = "debug"))]
@ -137,7 +139,7 @@ impl WorldManager {
Ok(serialized) => serialized, Ok(serialized) => serialized,
Err(err) => { Err(err) => {
return Err(SaveError::SerializationError(err)); return Err(SaveError::SerializationError(err));
} },
}; };
match File::create(path).unwrap().write_all(serialized.as_bytes()) { match File::create(path).unwrap().write_all(serialized.as_bytes()) {
@ -155,14 +157,14 @@ impl WorldManager {
Ok(file) => file, Ok(file) => file,
Err(err) => { Err(err) => {
return Err(LoadError::MissingSave(err)); return Err(LoadError::MissingSave(err));
} },
}; };
let mut buf = String::new(); let mut buf = String::new();
match file.read_to_string(&mut buf) { match file.read_to_string(&mut buf) {
Ok(_) => {} Ok(_) => {},
Err(err) => { Err(err) => {
return Err(LoadError::MissingSave(err)); return Err(LoadError::MissingSave(err));
} },
}; };
match ron::from_str(buf.as_str()) { match ron::from_str(buf.as_str()) {
Ok(world) => { Ok(world) => {
@ -185,7 +187,7 @@ impl WorldManager {
}); });
} }
Ok(()) Ok(())
} },
Err(err) => Err(LoadError::InvalidSave(err)), Err(err) => Err(LoadError::InvalidSave(err)),
} }
} }
@ -237,6 +239,7 @@ impl WorldManager {
pub fn get_world(&self) -> Option<&World> { pub fn get_world(&self) -> Option<&World> {
self.world.as_ref() self.world.as_ref()
} }
pub fn world(&self) -> &World { pub fn world(&self) -> &World {
assert!(self.world.is_some(), "No world."); assert!(self.world.is_some(), "No world.");
self.get_world().unwrap() self.get_world().unwrap()
@ -377,7 +380,7 @@ impl WorldManager {
.iter() .iter()
.map(|cell| self.generate_color(cell)) .map(|cell| self.generate_color(cell))
.collect() .collect()
} },
} }
} }

11
rustfmt.toml Normal file
View file

@ -0,0 +1,11 @@
imports_granularity = "One"
group_imports = "One"
enum_discrim_align_threshold = 15
imports_layout = "HorizontalVertical"
match_block_trailing_comma = true
newline_style = "Native"
reorder_impl_items = true
struct_field_align_threshold = 20
use_field_init_shorthand = true
use_try_shorthand = true
wrap_comments = true

View file

@ -37,11 +37,6 @@ mod plugins;
mod resources; mod resources;
mod ui_helpers; mod ui_helpers;
use bevy::{
app::App,
log::LogSettings,
utils::{default, tracing::Level},
};
#[cfg(all(feature = "render", feature = "planet_view"))] #[cfg(all(feature = "render", feature = "planet_view"))]
use bevy::{ use bevy::{
asset::Handle, asset::Handle,
@ -67,7 +62,11 @@ use bevy::{
camera::{Camera, RenderTarget}, camera::{Camera, RenderTarget},
color::Color, color::Color,
render_resource::{ render_resource::{
Extent3d, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, Extent3d,
TextureDescriptor,
TextureDimension,
TextureFormat,
TextureUsages,
}, },
texture::{Image, ImageSettings}, texture::{Image, ImageSettings},
}, },
@ -76,14 +75,20 @@ use bevy::{
transform::components::GlobalTransform, transform::components::GlobalTransform,
ui::{ ui::{
entity::{NodeBundle, TextBundle}, entity::{NodeBundle, TextBundle},
AlignSelf, FocusPolicy, Interaction, JustifyContent, PositionType, Size, Style, UiColor, AlignSelf,
UiRect, Val, FocusPolicy,
Interaction,
JustifyContent,
PositionType,
Size,
Style,
UiColor,
UiRect,
Val,
}, },
window::{CursorIcon, WindowDescriptor, Windows}, window::{CursorIcon, WindowDescriptor, Windows},
winit::WinitSettings, winit::WinitSettings,
}; };
use planet::Biome;
#[cfg(all(feature = "debug", feature = "render"))] #[cfg(all(feature = "debug", feature = "render"))]
use bevy::{ use bevy::{
diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin}, diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin},
@ -94,12 +99,19 @@ use components::{
markers::{InfoPanel, ToolbarButton}, markers::{InfoPanel, ToolbarButton},
third_party::PanCam, third_party::PanCam,
}; };
use planet::WorldManager;
use plugins::WorldPlugins;
#[cfg(feature = "render")] #[cfg(feature = "render")]
use resources::CursorMapPosition; use resources::CursorMapPosition;
#[cfg(feature = "render")] #[cfg(feature = "render")]
use ui_helpers::{toolbar_button, toolbar_button_text}; use ui_helpers::{toolbar_button, toolbar_button_text};
use {
bevy::{
app::App,
log::LogSettings,
utils::{default, tracing::Level},
},
planet::{Biome, WorldManager},
plugins::WorldPlugins,
};
#[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) {
@ -116,7 +128,8 @@ fn refresh_world_texture(images: &mut Assets<Image>, world_manager: &WorldManage
}); });
world_image.data = world_manager.world_color_bytes(); world_image.data = world_manager.world_color_bytes();
// TODO: Update Icosphere material... try to find out why it doesn't automatically= // TODO: Update Icosphere material. Try to find out why it doesn't
// automatically
} }
#[cfg(feature = "render")] #[cfg(feature = "render")]
@ -148,25 +161,25 @@ fn handle_toolbar_button(
debug!("Toggling rainfall"); debug!("Toggling rainfall");
world_manager.toggle_rainfall(); world_manager.toggle_rainfall();
refresh_world_texture(&mut images, &world_manager); refresh_world_texture(&mut images, &world_manager);
} },
ToolbarButton::Temperature => { ToolbarButton::Temperature => {
#[cfg(feature = "debug")] #[cfg(feature = "debug")]
debug!("Toggling temperature"); debug!("Toggling temperature");
world_manager.toggle_temperature(); world_manager.toggle_temperature();
refresh_world_texture(&mut images, &world_manager); refresh_world_texture(&mut images, &world_manager);
} },
ToolbarButton::Biomes => { ToolbarButton::Biomes => {
#[cfg(feature = "debug")] #[cfg(feature = "debug")]
debug!("Toggling biomes"); debug!("Toggling biomes");
world_manager.toggle_biomes(); world_manager.toggle_biomes();
refresh_world_texture(&mut images, &world_manager); refresh_world_texture(&mut images, &world_manager);
} },
ToolbarButton::Contours => { ToolbarButton::Contours => {
#[cfg(feature = "debug")] #[cfg(feature = "debug")]
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);
} },
ToolbarButton::GenerateWorld => { ToolbarButton::GenerateWorld => {
#[cfg(feature = "debug")] #[cfg(feature = "debug")]
debug!("Generating new world"); debug!("Generating new world");
@ -174,28 +187,28 @@ fn handle_toolbar_button(
.new_world() .new_world()
.expect("Failed to generate new world"); .expect("Failed to generate new world");
refresh_world_texture(&mut images, &world_manager); refresh_world_texture(&mut images, &world_manager);
} },
ToolbarButton::SaveWorld => { ToolbarButton::SaveWorld => {
#[cfg(feature = "debug")] #[cfg(feature = "debug")]
debug!("Saving world"); debug!("Saving world");
_ = world_manager.save_world("planet.ron"); _ = world_manager.save_world("planet.ron");
} },
ToolbarButton::LoadWorld => { ToolbarButton::LoadWorld => {
#[cfg(feature = "debug")] #[cfg(feature = "debug")]
debug!("Loading world"); debug!("Loading world");
_ = world_manager.load_world("planet.ron", &mut images); _ = world_manager.load_world("planet.ron", &mut images);
refresh_world_texture(&mut images, &world_manager); refresh_world_texture(&mut images, &world_manager);
},
} }
} },
}
Interaction::Hovered => { Interaction::Hovered => {
windows.primary_mut().set_cursor_icon(CursorIcon::Hand); windows.primary_mut().set_cursor_icon(CursorIcon::Hand);
*color = HOVERED_BUTTON.into(); *color = HOVERED_BUTTON.into();
} },
Interaction::None => { Interaction::None => {
windows.primary_mut().set_cursor_icon(CursorIcon::Default); windows.primary_mut().set_cursor_icon(CursorIcon::Default);
*color = NORMAL_BUTTON.into(); *color = NORMAL_BUTTON.into();
} },
} }
} }
} }

View file

@ -17,12 +17,22 @@ impl PluginGroup for WorldPlugins {
#[cfg(feature = "render")] #[cfg(feature = "render")]
{ {
use bevy::{ use {
asset::AssetPlugin, core_pipeline::CorePipelinePlugin, hierarchy::HierarchyPlugin, bevy::{
input::InputPlugin, render::RenderPlugin, sprite::SpritePlugin, text::TextPlugin, asset::AssetPlugin,
transform::TransformPlugin, ui::UiPlugin, window::WindowPlugin, winit::WinitPlugin, core_pipeline::CorePipelinePlugin,
hierarchy::HierarchyPlugin,
input::InputPlugin,
render::RenderPlugin,
sprite::SpritePlugin,
text::TextPlugin,
transform::TransformPlugin,
ui::UiPlugin,
window::WindowPlugin,
winit::WinitPlugin,
},
bevy_pancam::PanCamPlugin,
}; };
use bevy_pancam::PanCamPlugin;
_ = group _ = group
.add(TransformPlugin::default()) .add(TransformPlugin::default())

View file

@ -1,4 +1,6 @@
#[cfg(feature = "render")] #[cfg(feature = "render")]
use crate::{components::markers::ToolbarButton, NORMAL_BUTTON};
#[cfg(feature = "render")]
use bevy::{ use bevy::{
asset::AssetServer, asset::AssetServer,
ecs::system::Res, ecs::system::Res,
@ -7,14 +9,13 @@ use bevy::{
ui::{ ui::{
entity::{ButtonBundle, TextBundle}, entity::{ButtonBundle, TextBundle},
widget::Button, widget::Button,
AlignItems, JustifyContent, Style, AlignItems,
JustifyContent,
Style,
}, },
utils::default, utils::default,
}; };
#[cfg(feature = "render")]
use crate::{components::markers::ToolbarButton, NORMAL_BUTTON};
#[cfg(feature = "render")] #[cfg(feature = "render")]
pub(crate) fn toolbar_button() -> ButtonBundle { pub(crate) fn toolbar_button() -> ButtonBundle {
ButtonBundle { ButtonBundle {