Skip to content

Commit

Permalink
refactor: prelude and errors
Browse files Browse the repository at this point in the history
  • Loading branch information
eerii committed Jul 28, 2024
1 parent 1917c70 commit 0890947
Show file tree
Hide file tree
Showing 25 changed files with 161 additions and 101 deletions.
4 changes: 2 additions & 2 deletions .rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ normalize_comments = true
normalize_doc_attributes = true
overflow_delimited_expr = true
reorder_impl_items = true
single_line_if_else_max_width = 100 # 50
single_line_let_else_max_width = 100 # 50
single_line_if_else_max_width = 80 # 50
single_line_let_else_max_width = 80 # 50
unstable_features = true
use_field_init_shorthand = true
use_try_shorthand = true
Expand Down
7 changes: 7 additions & 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 @@ -45,6 +45,7 @@ log = { version = "*", features = [
macro_rules_attribute = { version = "0.2" }
serde = { version = "1.0", features = ["derive"] }
toml = { version = "0.8" }
anyhow = { version = "1.0" }

[profile.dev]
opt-level = 1
Expand Down
13 changes: 7 additions & 6 deletions macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub fn persistent(args: pm::TokenStream, input: pm::TokenStream) -> pm::TokenStr
let path = format!("{}/{}.toml", DATA_PATH, args.name);
let name = ident.to_string();

// TODO: Propperly handle errors
// TODO: Wasm support
let output = quote! {
#[derive(Resource, Serialize, Deserialize)]
#input
Expand All @@ -52,18 +52,19 @@ pub fn persistent(args: pm::TokenStream, input: pm::TokenStream) -> pm::TokenStr
};
}

fn persist(&self) {
let data = toml::to_string(self).unwrap();
let _ = std::fs::write(#path, data);
fn persist(&self) -> Result<()> {
let data = toml::to_string(self).with_context(|| format!("Failed to serialize data for {}", #name))?;
std::fs::write(#path, data).with_context(|| format!("Failed to save serialized data to {} for {}", #path, #name))?;
debug!("{} updated, saved in {}", #name, #path);
Ok(())
}

fn update(&mut self, f: impl Fn(&mut #ident)) {
fn update(&mut self, f: impl Fn(&mut #ident)) -> Result<()> {
f(self);
self.persist()
}

fn reset(&mut self) {
fn reset(&mut self) -> Result<()> {
*self = Self::default();
self.persist()
}
Expand Down
2 changes: 1 addition & 1 deletion src/assets.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use bevy::{prelude::*, utils::HashMap};
use crate::prelude::*;

#[cfg(feature = "embedded")]
pub(crate) mod embedded;
Expand Down
2 changes: 0 additions & 2 deletions src/assets/embedded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ use bevy::{
PathStream,
Reader,
},
prelude::*,
tasks::futures_lite::{AsyncRead, AsyncSeek, Stream},
utils::HashMap,
};
use include_dir::{include_dir, Dir};

Expand Down
3 changes: 0 additions & 3 deletions src/assets/fonts.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
use bevy::prelude::*;
use macros::asset_key;

use crate::prelude::*;

/// Preloads the font assets when the game starts
Expand Down
3 changes: 0 additions & 3 deletions src/assets/meta.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
use bevy::prelude::*;
use macros::asset_key;

use crate::prelude::*;

/// Preloads the meta assets when the game starts
Expand Down
3 changes: 0 additions & 3 deletions src/assets/music.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
use bevy::prelude::*;
use macros::asset_key;

use crate::prelude::*;

/// Preloads the music assets when the game starts
Expand Down
3 changes: 0 additions & 3 deletions src/assets/sound.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
use bevy::prelude::*;
use macros::asset_key;

use crate::prelude::*;

/// Preloads the sound assets when the game starts
Expand Down
4 changes: 2 additions & 2 deletions src/base.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use crate::prelude::*;

mod data;
mod later;
mod sets;
mod states;

use bevy::prelude::*;

pub(super) fn plugin(app: &mut App) {
app.add_plugins((data::plugin, later::plugin, sets::plugin, states::plugin));
}
Expand Down
15 changes: 9 additions & 6 deletions src/base/data.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use bevy::prelude::*;
use macros::persistent;
use serde::{de::DeserializeOwned, Deserialize, Serialize};

use crate::prelude::*;

const DATA_PATH: &str = ".data"; // If changed, update in `macros/lib.rs`

pub(super) fn plugin(app: &mut App) {
let _ = std::fs::create_dir_all(DATA_PATH);
#[cfg(not(target_arch = "wasm32"))]
if let Err(e) = std::fs::create_dir_all(DATA_PATH) {
warn!("Couldn't create the save directory {}: {}", DATA_PATH, e);
};
app.insert_resource(SaveData::load());
}

Expand All @@ -19,7 +22,7 @@ pub struct SaveData {
pub trait Persistent: Resource + Serialize + DeserializeOwned + Default {
fn load() -> Self;
fn reload(&mut self);
fn persist(&self);
fn update(&mut self, f: impl Fn(&mut Self));
fn reset(&mut self);
fn persist(&self) -> Result<()>;
fn update(&mut self, f: impl Fn(&mut Self)) -> Result<()>;
fn reset(&mut self) -> Result<()>;
}
4 changes: 3 additions & 1 deletion src/base/later.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
//! Based on the work by dylanj https://discord.com/channels/691052431525675048/937158127491633152/1266369728402948136

use bevy::{ecs::system::EntityCommands, prelude::*};
use bevy::ecs::system::EntityCommands;

use crate::prelude::*;

pub(super) fn plugin(app: &mut App) {
app.add_systems(PreUpdate, handle_later_commands);
Expand Down
2 changes: 0 additions & 2 deletions src/base/sets.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use bevy::prelude::*;

use crate::prelude::*;

/// Adds the `PlaySet` to the `App`.
Expand Down
2 changes: 0 additions & 2 deletions src/base/states.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use bevy::prelude::*;

use crate::prelude::*;

/// Adds the `GameState` to the `App`.
Expand Down
2 changes: 1 addition & 1 deletion src/components.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use bevy::prelude::*;
use crate::prelude::*;

mod camera;
mod music;
Expand Down
2 changes: 0 additions & 2 deletions src/components/camera.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use bevy::prelude::*;

use crate::prelude::*;

pub(super) fn plugin(app: &mut App) {
Expand Down
2 changes: 1 addition & 1 deletion src/components/music.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use bevy::{audio::PlaybackMode, prelude::*};
use bevy::audio::PlaybackMode;

use crate::prelude::*;

Expand Down
16 changes: 16 additions & 0 deletions src/helpers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/// Gets a single `Entity` from a `Query` or returns gracefully (no panic).
#[macro_export]
macro_rules! single {
($q:expr, $r:expr) => {
match $q.get_single() {
Ok(m) => m,
_ => {
debug!("get single failed for ${}", stringify!($e));
$r
},
}
};
($q:expr) => {
single!($q, return)
};
}
4 changes: 1 addition & 3 deletions src/input.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use bevy::prelude::*;
use leafwing_input_manager::prelude::*;

use crate::prelude::*;
Expand All @@ -17,10 +16,9 @@ pub mod prelude {
/// These are all the possible game actions that have an input mapping
/// You can use them like so:
/// ```
/// use bevy::prelude::*;
/// use game::prelude::*;
/// fn handle_input(input: Query<&ActionState<Action>>) {
/// let Ok(input) = input.get_single() else { return };
/// let input = single!(input);
/// if input.just_pressed(&Action::Jump) {
/// info!("Hi! c:");
/// }
Expand Down
8 changes: 7 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ extern crate macro_rules_attribute;
// TODO: Documentation and code examples
// Readme
// TODO: Main menu
// UI Navigation with input (custom implementation)
// TODO: Keybind remapping
// TODO: Text to speech
// TODO: Migrate proc macros to macro_rules_attribute?
Expand All @@ -19,16 +18,23 @@ use bevy::{prelude::*, window::WindowResolution};
mod assets;
mod base;
mod components;
#[macro_use]
mod helpers;
mod input;
mod ui;

pub mod prelude {
pub use anyhow::{Context, Result};
pub use bevy::{color::palettes::css, prelude::*, utils::HashMap};
pub use macros::*;

pub use super::{
assets::prelude::*,
base::prelude::*,
components::prelude::*,
input::prelude::*,
ui::prelude::*,
GamePlugin,
};

// Shorthands for derive macros
Expand Down
3 changes: 1 addition & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use bevy::prelude::*;
use game::GamePlugin;
use game::prelude::*;

fn main() {
App::new().add_plugins(GamePlugin).run();
Expand Down
50 changes: 14 additions & 36 deletions src/ui.rs
Original file line number Diff line number Diff line change
@@ -1,50 +1,28 @@
use bevy::prelude::*;

// use crate::{prelude::*, ui::navigation::*};
use crate::prelude::*;

mod navigation;
mod widgets;

pub(super) fn plugin(app: &mut App) {
app.add_plugins(navigation::plugin);
// app.register_component_as::<dyn Navigable, MenuItem>()
// .add_systems(OnEnter(GameState::Startup), init);
app.add_plugins((navigation::plugin, widgets::plugin));
app.add_systems(OnEnter(GameState::Startup), init);
}

pub mod prelude {
pub use bevy_trait_query::RegisterExt;

pub use super::{
navigation::NavBundle,
widgets::{Container, Stylable, Widget},
navigation::{NavBundle, NavContainer, Navigable},
widgets::{Container, NavigableExt, Stylable, Widget},
};
}

// #[derive(Component)]
// struct MenuItem {
// label: String,
// }
//
// impl Navigable for MenuItem {
// fn label(&self) -> String {
// self.label.clone()
// }
//
// fn action(&self) {
// info!("action {}", self.label());
// }
// }
//
// fn init(mut cmd: Commands) {
// let mut root = cmd.ui_root();
// root.with_children(|node| {
// node.button("hey").insert(MenuItem {
// label: "hey".into(),
// });
// node.button("hi").insert(MenuItem { label: "hi".into() });
// node.button("hello").insert(MenuItem {
// label: "hello".into(),
// });
// })
// .insert(NavContainer::default());
// }
fn init(mut cmd: Commands) {
let mut root = cmd.ui_root();
root.with_children(|node| {
node.button("hey");
node.button("hi").no_nav();
node.button("hello");
})
.nav_container();
}
Loading

0 comments on commit 0890947

Please sign in to comment.