From a231dfdd194139e9b32f0666c580d938a5826dd7 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 22 Feb 2025 01:51:36 +0100 Subject: [PATCH 1/6] Adds a draft of an html render --- weaponry/Cargo.toml | 4 + weaponry/examples/graph.rs | 149 ++++++++++++++++++ weaponry/examples/usage_scenario.rs | 58 ++++++- .../equipement_advanced_repr.rs | 74 ++++++--- .../weaponry_structs/equipement_scenario.rs | 8 +- .../weaponry_structs/equipement_structs.rs | 5 +- weaponry/src/weaponry_structs/mod.rs | 1 + 7 files changed, 269 insertions(+), 30 deletions(-) create mode 100644 weaponry/examples/graph.rs diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index ae487b4..0146cdd 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -16,6 +16,10 @@ serde_json = { version = "1.0.138", features = ["alloc"] } strum = { version = "0.27.0", features = ["derive"] } thiserror = "2.0.11" regex = "1.11.1" +charming = { version = "0.4.0", features = ["deno_core", "image", "resvg", "ssr", "wasm"] } +chrono = "0.4.39" +leptos = { version = "0.7.7", features = ["csr"] } +leptos-use = "0.15" [dev-dependencies] criterion = { version = "0.5" } diff --git a/weaponry/examples/graph.rs b/weaponry/examples/graph.rs new file mode 100644 index 0000000..c4a20fb --- /dev/null +++ b/weaponry/examples/graph.rs @@ -0,0 +1,149 @@ +// use charming::{ +// Chart, WasmRenderer, +// component::{Axis, Title}, +// element::AxisType, +// series::Line, +// }; +// use leptos::prelude::*; +// use leptos_use::use_interval_fn; +// use leptos_use::utils::Pausable; + +// #[component] +// fn App() -> impl IntoView { +// let data = RwSignal::new(vec![150, 230, 224, 218, 135, 147, 260]); +// let action = Action::new(move |_input: &()| { +// let local = data.get(); +// async move { +// let chart = Chart::new() +// .title(Title::new().text("Demo: Leptos + Charming")) +// .x_axis(Axis::new().type_(AxisType::Category).data(vec!["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])) +// .y_axis(Axis::new().type_(AxisType::Value)) +// .series(Line::new().data(local)); + +// let renderer = WasmRenderer::new(600, 400); +// renderer.render("chart", &chart).unwrap(); +// } +// }); + +// let Pausable { pause, resume, is_active: _ } = use_interval_fn( +// move || { +// data.update(|d| d.rotate_right(1)); +// action.dispatch(()); +// }, +// 1000, +// ); + +// action.dispatch(()); + +// view! { +//
+//
+// +// +//
+// } +// } + +// fn main() { +// mount_to_body(|| view! { }) +// } +use charming::{ + Chart, + component::{Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, ToolboxDataZoom, VisualMap, VisualMapType}, + element::{AxisType, Tooltip, Trigger}, + series::Line, +}; +// use rand::Rng; + +pub fn chart() -> Chart { + let raw_data = vec![ + ("2000-06-05", 116), + ("2000-06-06", 129), + ("2000-06-07", 135), + ("2000-06-08", 86), + ("2000-06-09", 73), + ("2000-06-10", 85), + ("2000-06-11", 73), + ("2000-06-12", 68), + ("2000-06-13", 92), + ("2000-06-14", 130), + ("2000-06-15", 245), + ("2000-06-16", 139), + ("2000-06-17", 115), + ("2000-06-18", 111), + ("2000-06-19", 309), + ("2000-06-20", 206), + ("2000-06-21", 137), + ("2000-06-22", 128), + ("2000-06-23", 85), + ("2000-06-24", 94), + ("2000-06-25", 71), + ("2000-06-26", 106), + ("2000-06-27", 84), + ("2000-06-28", 93), + ("2000-06-29", 85), + ("2000-06-30", 73), + ("2000-07-01", 83), + ("2000-07-02", 125), + ("2000-07-03", 107), + ("2000-07-04", 82), + ("2000-07-05", 44), + ("2000-07-06", 72), + ("2000-07-07", 106), + ("2000-07-08", 107), + ("2000-07-09", 66), + ("2000-07-10", 91), + ("2000-07-11", 92), + ("2000-07-12", 113), + ("2000-07-13", 107), + ("2000-07-14", 131), + ("2000-07-15", 111), + ("2000-07-16", 64), + ("2000-07-17", 69), + ("2000-07-18", 88), + ("2000-07-19", 77), + ("2000-07-20", 83), + ("2000-07-21", 111), + ("2000-07-22", 57), + ("2000-07-23", 55), + ("2000-07-24", 60), + ]; + + let mut data_list = vec![]; + let mut value_list = vec![]; + + raw_data.into_iter().for_each(|(date, value)| { + data_list.push(date); + value_list.push(value); + }); + + Chart::new() + .title(Title::new().text("Gradient along the y axis").left("center")) + // .title(Title::new().text("Gradient along the x axis").left("center").top("55%")) + .tooltip(Tooltip::new().trigger(Trigger::Axis)) + .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(0).min(0).max(400)) + // .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(1).dimension(0).min(0).max(10).max((data_list.len() - 1) as f64)) + .x_axis(Axis::new().data(data_list.to_vec()).type_(AxisType::Category).boundary_gap(false)) + // .x_axis(Axis::new().data(data_list.to_vec()).grid_index(1)) + .y_axis(Axis::new()) + // .y_axis(Axis::new().grid_index(1)) + .grid(Grid::new()) + // .grid(Grid::new().top("60%")) + .series(Line::new().show_symbol(false).data(value_list.clone())) + .data_zoom(DataZoom::new().type_(DataZoomType::Inside).start(0).end(100)) + .data_zoom(DataZoom::new().start(0).end(100)) + .toolbox(Toolbox::new().feature(Feature::new().data_zoom(ToolboxDataZoom::new().y_axis_index("none")).restore(Restore::new()).save_as_image(SaveAsImage::new()))) + .tooltip(Tooltip::new().trigger(Trigger::Axis)) + // .series(Line::new().show_symbol(false).x_axis_index(1).y_axis_index(1).data(value_list)) +} + +fn main() { + let chart = chart(); + use charming::HtmlRenderer; + + let mut renderer = HtmlRenderer::new("MOOO", 1800, 1800).theme(charming::theme::Theme::Dark); + // // Render the chart as HTML string. + // let html_str = renderer.render(&chart).unwrap(); + // Save the chart as HTML file. + renderer.save(&chart, "./chart.html").unwrap(); +} diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index f12cdb3..f5f6174 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -4,19 +4,69 @@ //! //! +use charming::HtmlRenderer; +use charming::{ + Chart, + component::{Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, ToolboxDataZoom, VisualMap, VisualMapType}, + element::{AxisType, Tooltip, Trigger}, + series::Line, +}; use std::path::Path; // TODO : All of these should likely be in the prelude if used like this -use weaponry::interfaces::{Reportable, Scenario, ToCSV}; use weaponry::weaponry_structs::CrossRecipeScenario; use weaponry::weaponry_structs::equipement_scenario::ConfigMock; +use weaponry::{ + interfaces::{Reportable, Scenario, ToCSV}, + weaponry_structs::RefinedEquipementList, +}; // use weaponry::interfaces:: fn main() { - let save_path = "data/first_data.csv"; + let save_path = "data/first_data"; let scenarios = CrossRecipeScenario::new_with_config(ConfigMock {}).unwrap(); - let refined_list = scenarios.generate_refined_recipes().unwrap(); + let mut refined_list = scenarios.generate_refined_recipes().unwrap(); + // Render as html + render_data(&mut refined_list, save_path); + // // Export as csv + // export_as_csv(&refined_list, save_path); +} + +#[allow(dead_code)] +fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) { println!("{}", refined_list.get_report(Some("Refined List"))); - println!("Saved initial data as {}: {:?}", save_path, refined_list.write_csv(Path::new(save_path))); + println!("Saved initial data as {}.html: {:?}", save_path, refined_list.write_csv(Path::new(&format!("{save_path}.csv")))); +} + +pub fn make_chart(data: &mut RefinedEquipementList) -> Chart { + data.inner.sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); + let raw_data = data.inner.iter().map(|refeq| (refeq.inner.name.join(" "), refeq.advanced.dps_safe)); + let mut data_list = vec![]; + let mut value_list = vec![]; + + raw_data.into_iter().for_each(|(date, value)| { + data_list.push(date); + value_list.push(value); + }); + + Chart::new() + .title(Title::new().text("Gradient along the y axis").left("center")) + .tooltip(Tooltip::new().trigger(Trigger::Axis)) + .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(0).min(0).max(400)) + .x_axis(Axis::new().data(data_list.to_vec()).type_(AxisType::Category).boundary_gap(false)) + .y_axis(Axis::new()) + .grid(Grid::new()) + .series(Line::new().show_symbol(false).data(value_list.clone())) + .data_zoom(DataZoom::new().type_(DataZoomType::Inside).start(0).end(100)) + .data_zoom(DataZoom::new().start(0).end(100)) + .toolbox(Toolbox::new().feature(Feature::new().data_zoom(ToolboxDataZoom::new().y_axis_index("none")).restore(Restore::new()).save_as_image(SaveAsImage::new()))) + .tooltip(Tooltip::new().trigger(Trigger::Axis)) +} + +fn render_data(data: &mut RefinedEquipementList, save_path: &str) { + let mut renderer = HtmlRenderer::new("MOOO", 1920, 1080).theme(charming::theme::Theme::Dark); + // Save the chart as HTML file. + println!("Saving to {save_path}.html"); + renderer.save(&make_chart(data), format!("{save_path}.html")).unwrap(); } // // Load DB diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index d03f9c2..0e79e09 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -18,19 +18,23 @@ use probability::prelude::{Binomial, Discrete}; use serde::Serialize; use strum::{Display, EnumIter, IntoEnumIterator}; -use super::{Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats}; +use super::{ + Equipement, InitialEquipementList, WeaponMacroCategory, + equipement_structs::InnerEquipementStats, +}; /// The final representation of the equipement inplementing all the fields needed for processing +// TODO: Add a public getter for the inner data pub struct RefinedEquipement { /// The original inner stats /// /// This structs takes ownership of the inner data // #[serde(skip_deserializing)] - inner: InnerEquipementStats, + pub inner: InnerEquipementStats, /// Advanced stats // #[serde(flatten)] - advanced: AdvancedStats, + pub advanced: AdvancedStats, } impl Serialize for RefinedEquipement { @@ -54,7 +58,8 @@ impl From for RefinedEquipement { /// The complete equipement list, refined with all advanced stats pub struct RefinedEquipementList { /// Inner list of Refined Equipements - pub(super) inner: Vec, + // TODO: Add a public getter in on of the traits + pub inner: Vec, } // Just a checkmark @@ -85,19 +90,25 @@ impl Default for RefinedEquipementList { /// The list of advanced stats infered from an Equipement // TODO: The two philosophies to drop the old inner or convert the useful fields are considered right now +// TODO: This whole public might be overkill ? A good inner view or scenario could implement what is needed #[allow(missing_docs, clippy::missing_docs_in_private_items)] #[derive(Serialize)] pub struct AdvancedStats { - display_name: String, - damage_per_attack: f64, - damage_per_turn: f64, - damage_per_action: f64, - armor_break_per_attack: f64, - armor_break_per_turn: f64, - armor_break_per_action: f64, - damage_matrix: DamageMatrix, + pub display_name: String, + pub damage_per_attack: f64, + pub damage_per_turn: f64, + pub damage_per_action: f64, + pub armor_break_per_attack: f64, + pub armor_break_per_turn: f64, + pub armor_break_per_action: f64, + pub damage_matrix: DamageMatrix, + pub category: Option, /// Armor break factoring in the damage output: While a weapon might have high AB, not having any damage will seriously hinder that AB - expected_armor_break_per_turn: f64, + pub expected_armor_break_per_turn: f64, + /// Dps with two actions and 5 dices + pub dps_safe: f64, + /// Dps with four actions and 11 dices + pub dps_unsafe: f64, // All other criterias are already in the inner as raw criterias } impl From<&InnerEquipementStats> for AdvancedStats { @@ -105,7 +116,9 @@ impl From<&InnerEquipementStats> for AdvancedStats { let damage_per_attack = (value.damage + value.p_damage * (value.rmax.saturating_sub(1))) as f64; let armor_break_per_attack = (value.armor_break as f64).min(damage_per_attack); + let damage_matrix = DamageMatrix::calculate_for(value); Self { + category: value.macro_category.clone(), display_name: value.name.join(" "), damage_per_attack, damage_per_turn: damage_per_attack * 2., @@ -117,8 +130,9 @@ impl From<&InnerEquipementStats> for AdvancedStats { // Adds the base strength, substracts the expected protection expected_armor_break_per_turn: (damage_per_attack + 6. - 8.) .min(armor_break_per_attack), - damage_matrix: value.into(), - // armor_break_matrix: , + dps_safe: damage_matrix.get_safe_dmg(value.action_cost), + dps_unsafe: damage_matrix.get_unsafe_dmg(value.action_cost), + damage_matrix, } } } @@ -127,7 +141,7 @@ impl From<&InnerEquipementStats> for AdvancedStats { /// /// This simulation does only calculate a very limited preset of damage values #[cfg_attr(test, derive(Debug))] -struct DamageMatrix { +pub struct DamageMatrix { /// The inner damage matrix damage_matrix: Vec, } @@ -136,6 +150,25 @@ impl DamageMatrix { pub fn get_damage(&self, precision: Precision, dices: DiceNumber) -> f64 { self.damage_matrix[precision as usize + 3 * dices as usize] } + + /// The "safe" damage, as in 5 dices, 2 attacks + // TODO: This safe damage actually uses 5 dices * 2 instead of doing max(5 * 1 , 2 * 1 + 3 * 1) + pub fn get_safe_dmg(&self, attack_cost: i8) -> f64 { + let _ = attack_cost; + (self.damage_matrix[0] + self.damage_matrix[1] + self.damage_matrix[2]) / 3. + } + /// The "unsage" damage, as in, full dice, 2 attacks + // TODO: This damages does max(Max dices * 1, 5 dices * 2), which might not be optimal + pub fn get_unsafe_dmg(&self, attack_cost: i8) -> f64 { + match attack_cost { + 1 => f64::max( + self.get_safe_dmg(attack_cost) * 2., + (self.damage_matrix[0] + self.damage_matrix[1] + self.damage_matrix[2]) / 3., + ), + 2 => (self.damage_matrix[0] + self.damage_matrix[1] + self.damage_matrix[2]) / 3., + _ => 0., + } + } } impl Serialize for DamageMatrix { fn serialize(&self, serializer: S) -> Result @@ -172,8 +205,9 @@ impl Display for DamageMatrix { } } -impl From<&InnerEquipementStats> for DamageMatrix { - fn from(value: &InnerEquipementStats) -> Self { +impl DamageMatrix { + /// Calculate the DamageMatrix for a given InnerEquipementStats + fn calculate_for(value: &InnerEquipementStats) -> Self { DamageMatrix { damage_matrix: (DiceNumber::iter() .flat_map(|dices| { @@ -259,7 +293,7 @@ mod test { #[test] fn test_binomial() { let damage = new_inner_eq(); - let mat: DamageMatrix = DamageMatrix::from(&damage); + let mat: DamageMatrix = DamageMatrix::calculate_for(&damage); println!("{:#?}", damage); println!("{:#?}", mat); } @@ -277,7 +311,7 @@ mod test { #[test] fn test_creation() { - let mat = DamageMatrix::from(&new_inner_eq()); + let mat = DamageMatrix::calculate_for(&new_inner_eq()); println!("{}", mat); println!( "(High,Many): {}, (Low,Few): {}", diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 5e11109..d21b8d6 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -113,11 +113,13 @@ impl Scenario for CrossRecipeScenario { // No op, just clarity // TODO: Depending on config this step might differ let mut f_list = eq_shape; - // println!("{}", f_list.get_report(Some("Initial Weapons "))); + println!("{}", f_list.get_report(Some("Initial Weapons "))); f_list.combine_all(&eq_material); - // println!("{}", f_list.get_report(Some("Combined with Materials"))); + println!("{}", f_list.get_report(Some("Combined with Materials"))); + f_list.combine_all(&eq_material); + println!("{}", f_list.get_report(Some("Combined with Materials"))); f_list.combine_all(&eq_nature); - // println!("{}", f_list.get_report(Some("Combined with Natures "))); + println!("{}", f_list.get_report(Some("Combined with Natures "))); // f_list.combine_all(&eq_finishing); // println!("{}", f_list.get_report(Some("Combined with Finishing"))); // TODO: The finishes are interesting if they are configured or at least tamed a little diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 4e92388..3fc66ce 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -42,7 +42,7 @@ impl Default for Equipement { /// The default filter to use, usefull to implement a new filter function that also uses the default filter pub(crate) fn default_filter() -> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool { - &|self_, lhs| !self_.id.iter().any(|a| *a == lhs.id[0]) + &|self_, lhs| lhs.id.iter().all(|a| *a != self_.id[0]) } impl FilterFunction { @@ -281,8 +281,7 @@ impl From for EqFinishing { #[cfg(test)] mod test { use super::{ - EqFinishing, EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList, - InnerEquipementStats, + EqFinishing, EqMaterial, EqShape, Equipement, InitialEquipementList, InnerEquipementStats, }; use crate::interfaces::RecipeCollection; diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index f347a40..5a09399 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -33,6 +33,7 @@ pub use equipement_structs::{Equipement, InitialEquipementList}; // All generic fields // #[allow(unused_imports)] +pub use crate::weaponry_structs::equipement_advanced_repr::RefinedEquipementList; pub use equipement_fields::PhysicalDamageType; pub use equipement_fields::{ DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory, WeaponMacroCategory, -- 2.45.1 From 04bc4d57ecb4eb95d35974e5d6e2dd700b16415f Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 22 Feb 2025 02:06:22 +0100 Subject: [PATCH 2/6] Bad database selected --- weaponry/Cargo.toml | 8 ++++---- weaponry/src/weaponry_structs/equipement_scenario.rs | 5 ++++- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 0146cdd..291e2c0 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -16,10 +16,10 @@ serde_json = { version = "1.0.138", features = ["alloc"] } strum = { version = "0.27.0", features = ["derive"] } thiserror = "2.0.11" regex = "1.11.1" -charming = { version = "0.4.0", features = ["deno_core", "image", "resvg", "ssr", "wasm"] } -chrono = "0.4.39" -leptos = { version = "0.7.7", features = ["csr"] } -leptos-use = "0.15" +charming = { version = "0.4.0", features = [] } +# chrono = "0.4.39" +# leptos = { version = "0.7.7", features = ["csr"] } +# leptos-use = "0.15" [dev-dependencies] criterion = { version = "0.5" } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index d21b8d6..d48a426 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -47,6 +47,8 @@ impl ViewTable for ViewtableMock { /// A simple cross recipe scenario #[allow(clippy::missing_docs_in_private_items)] pub struct CrossRecipeScenario { + // TODO: Should obv be inside the config + database_name: String, database: EquipementDatabase, config: ConfigMock, } @@ -63,7 +65,7 @@ impl CrossRecipeScenario { Ok(InitialEquipementList::from_vectored( self.database .serialize_vec_from_table::( - &name, + &self.database_name, Some(&format!("META_CATEGORY LIKE '{}'", name)), )? .into_iter() @@ -89,6 +91,7 @@ impl Scenario for CrossRecipeScenario { { Ok(Self { // TODO: Correct this relative path abomination + database_name: "Equipements".into(), database: Self::DatabaseType::new("./databases/weapons.db")?, config, }) -- 2.45.1 From 5b3972a906fad2a3a015bf2c7d0545603dc63eb1 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 22 Feb 2025 05:45:42 +0100 Subject: [PATCH 3/6] Adds more to the graph --- weaponry/Cargo.toml | 4 +- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/.rustfmt.toml | 2 +- weaponry/examples/usage_scenario.rs | 108 +++++++++++++++--- .../equipement_advanced_repr.rs | 32 +++--- .../equipement_impl_basics.rs | 30 +---- .../weaponry_structs/equipement_structs.rs | 31 ++++- 7 files changed, 145 insertions(+), 62 deletions(-) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 291e2c0..d7f70a4 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -17,15 +17,13 @@ strum = { version = "0.27.0", features = ["derive"] } thiserror = "2.0.11" regex = "1.11.1" charming = { version = "0.4.0", features = [] } -# chrono = "0.4.39" -# leptos = { version = "0.7.7", features = ["csr"] } -# leptos-use = "0.15" [dev-dependencies] criterion = { version = "0.5" } regex = "1.11.1" pretty_assertions = "^1.4" logos = "^0.15" +clap = { version = "4.5.30", features = ["derive"] } [[bench]] name = "iter_creation" diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index 1ad235a301c6a91c31f9aefb22ec8b527a47bebb..2dd403301c8450cdaeccac0c60f736c15d055347 100644 GIT binary patch delta 221 zcmZp8z}WDBae_2s^F$eE#^#L)3+;J1|1xMZN74%Id=Mgr$+iocSelC9@*aai&rx4aRGX)r1xtS2@3BOq^^bA~kuQlgH%gA{v|byL@C}0b1%cd5fppW_PchssOK{ BKu`bx delta 181 zcmZp8z}WDBae_2s<3t%}#>R~a3+;KCDj2jGG8y=n@tg4-oy;d-rO4FG;>-M>xt}4E z=^2w6<4wkPMjeKO4EaC^0h1M-BQ^^-ZfE3Xc3|LE*X7_~*NWptef4vcB%pZU1KzS diff --git a/weaponry/examples/.rustfmt.toml b/weaponry/examples/.rustfmt.toml index 98b9e7f..9a9035c 100644 --- a/weaponry/examples/.rustfmt.toml +++ b/weaponry/examples/.rustfmt.toml @@ -1 +1 @@ -max_width = 278 +# max_width = 278 diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index f5f6174..4ccdb25 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -3,11 +3,24 @@ //! Test use case of a scenario //! //! +use charming::component::Legend; +use charming::element::Orient; +use clap::Parser; + +#[derive(Parser, Debug)] +/// Basic cli +pub struct ParserCLIArgs { + /// The path to save to. + pub path: Option, +} use charming::HtmlRenderer; use charming::{ Chart, - component::{Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, ToolboxDataZoom, VisualMap, VisualMapType}, + component::{ + Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, + ToolboxDataZoom, + }, element::{AxisType, Tooltip, Trigger}, series::Line, }; @@ -34,39 +47,100 @@ fn main() { #[allow(dead_code)] fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) { println!("{}", refined_list.get_report(Some("Refined List"))); - println!("Saved initial data as {}.html: {:?}", save_path, refined_list.write_csv(Path::new(&format!("{save_path}.csv")))); + println!( + "Saved initial data as {}.html: {:?}", + save_path, + refined_list.write_csv(Path::new(&format!("{save_path}.csv"))) + ); } pub fn make_chart(data: &mut RefinedEquipementList) -> Chart { - data.inner.sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); - let raw_data = data.inner.iter().map(|refeq| (refeq.inner.name.join(" "), refeq.advanced.dps_safe)); + data.inner + .sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); + let raw_data = data.inner.iter().map(|refeq| { + ( + &refeq.advanced.display_name, + refeq.advanced.dps_safe, + refeq.advanced.max_damage_per_action, + refeq.advanced.armor_break_per_turn, + ) + }); let mut data_list = vec![]; - let mut value_list = vec![]; + let mut dps_safe = vec![]; + let mut max_damage_per_action = vec![]; + let mut armor_break_per_turn = vec![]; - raw_data.into_iter().for_each(|(date, value)| { - data_list.push(date); - value_list.push(value); + raw_data.into_iter().for_each(|(index, dps_s, dpa, abpt)| { + data_list.push(index); + dps_safe.push(dps_s); + max_damage_per_action.push(dpa); + armor_break_per_turn.push(abpt); }); Chart::new() - .title(Title::new().text("Gradient along the y axis").left("center")) + .title( + Title::new() + .text("Damage for all cross-gen products") + .left("center"), + ) + .legend( + Legend::new() + .left(10) + .top("middle") + .orient(Orient::Vertical) + .data(vec![ + "dps_safe", + "max_damage_per_action", + "armor_break_per_turn", + ]), + ) .tooltip(Tooltip::new().trigger(Trigger::Axis)) - .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(0).min(0).max(400)) - .x_axis(Axis::new().data(data_list.to_vec()).type_(AxisType::Category).boundary_gap(false)) + .x_axis( + Axis::new() + .data(data_list.to_vec()) + .type_(AxisType::Category), + ) .y_axis(Axis::new()) - .grid(Grid::new()) - .series(Line::new().show_symbol(false).data(value_list.clone())) - .data_zoom(DataZoom::new().type_(DataZoomType::Inside).start(0).end(100)) + .grid(Grid::new().contain_label(true)) + .series( + Line::new().data(dps_safe).name("dps_safe"), // .line_style(LineStyle::new().color("paleblue")), + ) + .series( + Line::new() + .data(max_damage_per_action) + .name("max_damage_per_action"), + ) + .series( + Line::new() + .data(armor_break_per_turn) + .name("armor_break_per_turn"), + ) + .data_zoom( + DataZoom::new() + .type_(DataZoomType::Inside) + .start(0) + .end(100), + ) .data_zoom(DataZoom::new().start(0).end(100)) - .toolbox(Toolbox::new().feature(Feature::new().data_zoom(ToolboxDataZoom::new().y_axis_index("none")).restore(Restore::new()).save_as_image(SaveAsImage::new()))) + .toolbox( + Toolbox::new().feature( + Feature::new() + .data_zoom(ToolboxDataZoom::new().y_axis_index("none")) + .restore(Restore::new()) + .save_as_image(SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + ), + ) .tooltip(Tooltip::new().trigger(Trigger::Axis)) } fn render_data(data: &mut RefinedEquipementList, save_path: &str) { - let mut renderer = HtmlRenderer::new("MOOO", 1920, 1080).theme(charming::theme::Theme::Dark); + let mut renderer = + HtmlRenderer::new("Ravenous Balancing", 4000, 2000).theme(charming::theme::Theme::Dark); // Save the chart as HTML file. println!("Saving to {save_path}.html"); - renderer.save(&make_chart(data), format!("{save_path}.html")).unwrap(); + renderer + .save(&make_chart(data), format!("{save_path}.html")) + .unwrap(); } // // Load DB diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 0e79e09..5221e02 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -97,7 +97,7 @@ pub struct AdvancedStats { pub display_name: String, pub damage_per_attack: f64, pub damage_per_turn: f64, - pub damage_per_action: f64, + pub max_damage_per_action: f64, pub armor_break_per_attack: f64, pub armor_break_per_turn: f64, pub armor_break_per_action: f64, @@ -107,8 +107,8 @@ pub struct AdvancedStats { pub expected_armor_break_per_turn: f64, /// Dps with two actions and 5 dices pub dps_safe: f64, - /// Dps with four actions and 11 dices - pub dps_unsafe: f64, + // /// Dps with four actions and 11 dices + // pub dps_unsafe: f64, // All other criterias are already in the inner as raw criterias } impl From<&InnerEquipementStats> for AdvancedStats { @@ -122,7 +122,7 @@ impl From<&InnerEquipementStats> for AdvancedStats { display_name: value.name.join(" "), damage_per_attack, damage_per_turn: damage_per_attack * 2., - damage_per_action: damage_per_attack / (value.action_cost as f64), + max_damage_per_action: damage_per_attack / (value.action_cost as f64), armor_break_per_attack, armor_break_per_turn: armor_break_per_attack * 2., armor_break_per_action: armor_break_per_attack / value.action_cost as f64, @@ -131,7 +131,7 @@ impl From<&InnerEquipementStats> for AdvancedStats { expected_armor_break_per_turn: (damage_per_attack + 6. - 8.) .min(armor_break_per_attack), dps_safe: damage_matrix.get_safe_dmg(value.action_cost), - dps_unsafe: damage_matrix.get_unsafe_dmg(value.action_cost), + // dps_unsafe: damage_matrix.get_unsafe_dmg(value.action_cost), damage_matrix, } } @@ -155,19 +155,21 @@ impl DamageMatrix { // TODO: This safe damage actually uses 5 dices * 2 instead of doing max(5 * 1 , 2 * 1 + 3 * 1) pub fn get_safe_dmg(&self, attack_cost: i8) -> f64 { let _ = attack_cost; - (self.damage_matrix[0] + self.damage_matrix[1] + self.damage_matrix[2]) / 3. + (self.get_damage(Precision::Low, DiceNumber::Few) + + self.get_damage(Precision::Medium, DiceNumber::Few) + + self.get_damage(Precision::High, DiceNumber::Few)) + / 3. } /// The "unsage" damage, as in, full dice, 2 attacks // TODO: This damages does max(Max dices * 1, 5 dices * 2), which might not be optimal pub fn get_unsafe_dmg(&self, attack_cost: i8) -> f64 { - match attack_cost { - 1 => f64::max( - self.get_safe_dmg(attack_cost) * 2., - (self.damage_matrix[0] + self.damage_matrix[1] + self.damage_matrix[2]) / 3., - ), - 2 => (self.damage_matrix[0] + self.damage_matrix[1] + self.damage_matrix[2]) / 3., - _ => 0., - } + f64::max( + self.get_safe_dmg(attack_cost) * 2., + (self.get_damage(Precision::Low, DiceNumber::Many) + + self.get_damage(Precision::Medium, DiceNumber::Many) + + self.get_damage(Precision::High, DiceNumber::Many)) + / 3., + ) } } impl Serialize for DamageMatrix { @@ -267,7 +269,7 @@ impl Precision { match self { Precision::High => 9, Precision::Medium => 6, - Precision::Low => 3, + Precision::Low => 4, } } } diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index 4e199f4..dc7870d 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -16,7 +16,10 @@ use crate::interfaces::{FilterFunction, Reportable}; use super::{ Equipement, InitialEquipementList, equipement_advanced_repr::RefinedEquipementList, - equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats}, + equipement_structs::{ + EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats, + filter_id_unique_and_right_category, + }, }; impl From for Equipement { @@ -31,7 +34,7 @@ impl From for Equipement { fn from(val: EqMaterial) -> Self { Self { stats: val.stats, - ..Default::default() + filter_function: FilterFunction::new(filter_id_unique_and_right_category()), } } } @@ -44,28 +47,7 @@ impl From for Equipement { // TODO : Checks that this is exactly desired behavious // :Also check for Cross Weapon/Armor contamination // Checks that the nature is compatible with the previous iteration - filter_function: FilterFunction::new(&|sel, lhs| { - // println!( - // "Trying to match {:?} with {:?}. {:?} {:?}", - // sel.name, lhs.name, sel.target, lhs.macro_category - // ); - - match (&sel.target, &lhs.macro_category) { - // There is a specific target and the part about to be added has a category - (Some(a), Some(b)) => { - // println!("{} {}", a, b); - a == b - } - // There is no target and the part about to be added is generic - // TODO: Unsound to have a generic nature, this should be caught at serialisation - (None, _) => panic!("The EqNature about to be added cannot be generic"), - // There is a specific target but the part about to be added is generic - // TODO: Impossible - (Some(_), None) => panic!("The part about to be added unto cannot be generic"), - // // There is restriction on the target and the recipient - // (None, Some(_)) => true, - } - }), + filter_function: FilterFunction::new(filter_id_unique_and_right_category()), } } } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 3fc66ce..15ceb05 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -33,18 +33,45 @@ pub struct Equipement { impl Default for Equipement { fn default() -> Self { Self { - filter_function: FilterFunction::new(default_filter()), + filter_function: FilterFunction::new(filter_id_unique()), stats: InnerEquipementStats::random_new(), } } } /// The default filter to use, usefull to implement a new filter function that also uses the default filter -pub(crate) fn default_filter() +pub(crate) fn filter_id_unique() -> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool { &|self_, lhs| lhs.id.iter().all(|a| *a != self_.id[0]) } +/// Create a new filter function mandating the object be of the right category +pub(crate) fn filter_id_unique_and_right_category() +-> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool { + &|sel, lhs| { + // println!( + // "Trying to match {:?} with {:?}. {:?} {:?}", + // sel.name, lhs.name, sel.target, lhs.macro_category + // ); + lhs.id.iter().all(|a| *a != sel.id[0]) + & match (&sel.target, &lhs.macro_category) { + // There is a specific target and the part about to be added has a category + (Some(a), Some(b)) => { + // println!("{} {}", a, b); + a == b + } + // There is no target and the part about to be added is generic + // TODO: Unsound to have a generic nature, this should be caught at serialisation + // TODO: Testing a generic anyway + (None, _) => true, // panic!("The EqNature about to be added cannot be generic"), + // There is a specific target but the part about to be added is generic + // TODO: Impossible + (Some(_), None) => panic!("The part about to be added unto cannot be generic"), + // // There is restriction on the target and the recipient + // (None, Some(_)) => true, + } + } +} impl FilterFunction { /// Generate a new filter // TODO: This static lifetime is basically telling us that an owned value is needed -- 2.45.1 From f3bb2c9d8007fc4b95f246c46ded0628f708694e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 23 Feb 2025 00:19:44 +0100 Subject: [PATCH 4/6] Cleaning up the scenario and progressive integration into the main impl --- weaponry/examples/usage_scenario.rs | 167 ++++-------------- weaponry/src/error.rs | 37 ++-- weaponry/src/interfaces.rs | 47 ++--- .../equipement_advanced_repr.rs | 144 ++++++++++++++- .../equipement_impl_basics.rs | 13 -- .../weaponry_structs/equipement_impl_io.rs | 6 +- .../weaponry_structs/equipement_scenario.rs | 144 +++++++-------- 7 files changed, 280 insertions(+), 278 deletions(-) diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index 4ccdb25..bb614ca 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -3,46 +3,56 @@ //! Test use case of a scenario //! //! -use charming::component::Legend; -use charming::element::Orient; use clap::Parser; - -#[derive(Parser, Debug)] -/// Basic cli -pub struct ParserCLIArgs { - /// The path to save to. - pub path: Option, -} - -use charming::HtmlRenderer; -use charming::{ - Chart, - component::{ - Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, - ToolboxDataZoom, - }, - element::{AxisType, Tooltip, Trigger}, - series::Line, -}; use std::path::Path; +use weaponry::interfaces::ToAnalysis; // TODO : All of these should likely be in the prelude if used like this use weaponry::weaponry_structs::CrossRecipeScenario; -use weaponry::weaponry_structs::equipement_scenario::ConfigMock; +use weaponry::weaponry_structs::equipement_scenario::ConfigEquipementScenario; use weaponry::{ interfaces::{Reportable, Scenario, ToCSV}, weaponry_structs::RefinedEquipementList, }; // use weaponry::interfaces:: fn main() { - let save_path = "data/first_data"; - let scenarios = CrossRecipeScenario::new_with_config(ConfigMock {}).unwrap(); - let mut refined_list = scenarios.generate_refined_recipes().unwrap(); - // Render as html - render_data(&mut refined_list, save_path); - // // Export as csv + let args = CLIArgs::parse(); + let save_path = args.path.unwrap_or("data/first_data".into()); + let scenarios = CrossRecipeScenario::new_with_config(ConfigEquipementScenario { + table_name: "Equipements".into(), + db_path: "./databases/weapons.db".into(), + shape: args.shapes.then_some(()), + materials: args.materials, + nature: args.natures.then_some(()), + finishing: args.finishing.then_some(()), + }) + .unwrap(); + let refined_list = scenarios.generate_refined_recipes().unwrap(); + + // if args.html_export{} + refined_list.write_html(&save_path).unwrap(); + + // if args.csv_export{} // export_as_csv(&refined_list, save_path); } +#[derive(Parser, Debug)] +/// Basic cli +pub struct CLIArgs { + /// The path to save to. + pub path: Option, + /// Wether to generate shapes + #[arg(short, long, default_value_t = true)] + pub shapes: bool, + /// Wether to generate materials + #[arg(short, long)] + pub materials: Option, + /// Wether to generate all natures + #[arg(short, long, default_value_t = true)] + pub natures: bool, + /// Wether to generate all finishing + #[arg(short, long, default_value_t = false)] + pub finishing: bool, +} #[allow(dead_code)] fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) { @@ -53,106 +63,3 @@ fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) { refined_list.write_csv(Path::new(&format!("{save_path}.csv"))) ); } - -pub fn make_chart(data: &mut RefinedEquipementList) -> Chart { - data.inner - .sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); - let raw_data = data.inner.iter().map(|refeq| { - ( - &refeq.advanced.display_name, - refeq.advanced.dps_safe, - refeq.advanced.max_damage_per_action, - refeq.advanced.armor_break_per_turn, - ) - }); - let mut data_list = vec![]; - let mut dps_safe = vec![]; - let mut max_damage_per_action = vec![]; - let mut armor_break_per_turn = vec![]; - - raw_data.into_iter().for_each(|(index, dps_s, dpa, abpt)| { - data_list.push(index); - dps_safe.push(dps_s); - max_damage_per_action.push(dpa); - armor_break_per_turn.push(abpt); - }); - - Chart::new() - .title( - Title::new() - .text("Damage for all cross-gen products") - .left("center"), - ) - .legend( - Legend::new() - .left(10) - .top("middle") - .orient(Orient::Vertical) - .data(vec![ - "dps_safe", - "max_damage_per_action", - "armor_break_per_turn", - ]), - ) - .tooltip(Tooltip::new().trigger(Trigger::Axis)) - .x_axis( - Axis::new() - .data(data_list.to_vec()) - .type_(AxisType::Category), - ) - .y_axis(Axis::new()) - .grid(Grid::new().contain_label(true)) - .series( - Line::new().data(dps_safe).name("dps_safe"), // .line_style(LineStyle::new().color("paleblue")), - ) - .series( - Line::new() - .data(max_damage_per_action) - .name("max_damage_per_action"), - ) - .series( - Line::new() - .data(armor_break_per_turn) - .name("armor_break_per_turn"), - ) - .data_zoom( - DataZoom::new() - .type_(DataZoomType::Inside) - .start(0) - .end(100), - ) - .data_zoom(DataZoom::new().start(0).end(100)) - .toolbox( - Toolbox::new().feature( - Feature::new() - .data_zoom(ToolboxDataZoom::new().y_axis_index("none")) - .restore(Restore::new()) - .save_as_image(SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), - ), - ) - .tooltip(Tooltip::new().trigger(Trigger::Axis)) -} - -fn render_data(data: &mut RefinedEquipementList, save_path: &str) { - let mut renderer = - HtmlRenderer::new("Ravenous Balancing", 4000, 2000).theme(charming::theme::Theme::Dark); - // Save the chart as HTML file. - println!("Saving to {save_path}.html"); - renderer - .save(&make_chart(data), format!("{save_path}.html")) - .unwrap(); -} - -// // Load DB -// let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); -// // Do a first deserialisation -// let initial_deserialisation = db.serialize_vec_from_table::("Equipements", None).unwrap(); -// // Follow up by parsing this deserialisation by a transformation into the right intermediate representation -// let intermediate_deserialisation = initial_deserialisation.into_iter().map(InnerEquipementStats::try_from).collect::>(); - -// // // Inspect the sucesses/filures -// // let f = intermediate_deserialisation.iter().fold((0, 0), |val, res| (val.0 + res.is_ok() as usize, val.1 + 1_usize)); -// // println!("Succeded in parsing {}/{}", f.0, f.1); - -// // println!("Final data {:#?}", intermediate_deserialisation); -// // println!("Failed to parse: {:#?}", intermediate_deserialisation.into_iter().filter_map(|v| v.err()).collect::>()); diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index 808b9d8..fba7e58 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -3,6 +3,7 @@ //! Inner weaponry error definition #![allow(missing_docs, clippy::missing_docs_in_private_items)] +use charming::EchartsError; use thiserror::Error; #[derive(Error, Debug)] @@ -32,22 +33,28 @@ pub enum FatalEquipementError { #[error("Couldn't convert into type {origin_type} with data {data}")] Conversion { origin_type: String, data: String }, + + #[error("An error occured with your current CLI configuration: {0}")] + CLISelection(String), + + #[error("Couldn't save the chart as an error occured during the process : {0}")] + SaveCharmingChart(#[from] EchartsError), } -#[derive(Error, Debug)] -/// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program -pub enum LocalEquipementError { - #[error("Very simple error")] - Oops, -} +// #[derive(Error, Debug)] +// /// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program +// pub enum LocalEquipementError { +// #[error("Very simple error")] +// Oops, +// } -#[derive(Error, Debug)] -/// An equipement error, either unrecoverable, indicating a that the execution -/// flow must be stopped and only an user input can solve the issue -pub enum EquipementError { - #[error("An unrecoverable error occured: {0}")] - Fatal(#[from] FatalEquipementError), +// #[derive(Error, Debug)] +// /// An equipement error, either unrecoverable, indicating a that the execution +// /// flow must be stopped and only an user input can solve the issue +// pub enum EquipementError { +// #[error("An unrecoverable error occured: {0}")] +// Fatal(#[from] FatalEquipementError), - #[error("A local error occured an wasn't recovered from: {0}")] - Local(#[from] LocalEquipementError), -} +// #[error("A local error occured an wasn't recovered from: {0}")] +// Local(#[from] LocalEquipementError), +// } diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index 05a8d0e..b4a4a75 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -10,7 +10,7 @@ use std::{path::Path, rc::Rc}; use more_fields::FieldsAsSlice; use serde::de::DeserializeOwned; -use crate::error::{EquipementError, FatalEquipementError}; +use crate::error::FatalEquipementError; /// Trait representing a view table /// @@ -42,7 +42,7 @@ pub trait ViewTable { /// While it is possible to enforce from_recipe_collection, doing so would require the viewtable /// lock itseld to a particular recipe. /// While it is the case as of now, matters are not yet set in stone -pub trait RefinedList { +pub trait RefinedList: ToTex + ToCSV + ToAnalysis { // Must implement From, is it worth adding as a prerequite type ? // type OriginCollection: Into; } @@ -150,6 +150,14 @@ pub trait ToCSV { fn write_csv(&self, path: &Path) -> csv::Result<()>; } +/// This element can be converted to an interactive .html +pub trait ToAnalysis { + /// Write as html + fn write_html(&self, path: &str) -> Result<(), FatalEquipementError>; + + // TODO: Add sorting methods as no analysis can be done without filtering and sorting +} + /// A generic database+connection, handling all the deserialization of the inner types pub trait RecipeDatabase { /// Create the database from a file @@ -205,45 +213,16 @@ pub trait Reportable { pub trait Scenario { /// The inner database type type DatabaseType: RecipeDatabase; - /// The type of viewtable that must be returned by the scenario - // Could also use dyn dispatch but since all of it is so tied down... - type ViewTableType: ViewTable; /// The type of the final recipe list - type FinalListType: RefinedList; + type FinalListType: RefinedList + ToTex + ToCSV + ToAnalysis; /// Inner configuration type Config; /// Create a Scenario from a given config - fn new_with_config(config: Self::Config) -> Result + fn new_with_config(config: Self::Config) -> Result where Self: Sized; - // /// Load all database into intermediate representation - // fn load_from_database() -> Result - // where - // Self: std::marker::Sized; - - // /// Configure the scenario to the user's needs - // fn configure_scenario(&mut self, config: Self::Config) -> Result<(), FatalEquipementError>; - - // All these steps should be implemented but not required - // enforcing them helps writing new impls more easily but is not really nice in any way - // - // /// Process the inner representations and get a list of results - // fn process_inner_representation(&self) -> Result<(), FatalEquipementError>; //Result<(), EquipementError> - - // /// Process inner recipes into a Final list - // /// - // /// This will generate the recipe list using the prefered method of the Scenario (Fixed Recipes or Cross Recipes or Whatever) - // fn process_recipes(&self); - - // /// Process the recipes into a Refined Recipes - // fn refine_recipes(&self); - /// Generate the final list type - fn generate_refined_recipes(&self) -> Result; - - /// Gather the selected view tables - /// All the inner generation is done gradually and populate all section to finally generate the views - fn generate_view_tables(&self, equipement_list: Self::FinalListType) -> Self::ViewTableType; + fn generate_refined_recipes(&self) -> Result; } diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 5221e02..f680f8b 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -12,7 +12,11 @@ use core::f64; use std::fmt::Display; -use crate::interfaces::RefinedList; +use crate::{ + error::FatalEquipementError, + interfaces::{RefinedList, ToAnalysis, ToTex}, +}; +use charming::element::Orient; use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; use probability::prelude::{Binomial, Discrete}; use serde::Serialize; @@ -64,6 +68,126 @@ pub struct RefinedEquipementList { // Just a checkmark impl RefinedList for RefinedEquipementList {} +impl ToTex for RefinedEquipementList { + fn to_tex(&self) -> String { + todo!() + } +} +impl ToAnalysis for RefinedEquipementList { + fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> { + let mut renderer = charming::HtmlRenderer::new("Ravenous Balancing", 4000, 2000) + .theme(charming::theme::Theme::Dark); + // Save the chart as HTML file. + renderer.save(&make_chart(self), format!("{save_path}.html"))?; + return Ok(()); + + // TODO: Migrate this into the view / renderer + // TODO: End the view idea and only focus on this renderer + pub fn make_chart(data: &RefinedEquipementList) -> charming::Chart { + // TODO: Add back sorting + // data.inner + // .sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); + + // TODO: Convert to macro + let raw_data = data.inner.iter().map(|refeq| { + ( + &refeq.advanced.display_name, + refeq.advanced.dps_safe, + refeq.advanced.max_damage_per_action, + refeq.advanced.damage_per_turn, + refeq.advanced.armor_break_per_turn, + ) + }); + let mut data_list = vec![]; + let mut dps_safe = vec![]; + let mut max_damage_per_action = vec![]; + let mut max_damage_per_turn = vec![]; + let mut armor_break_per_turn = vec![]; + + raw_data + .into_iter() + .for_each(|(index, dps_s, dpa, dpt, abpt)| { + data_list.push(index); + dps_safe.push(dps_s); + max_damage_per_action.push(dpa); + max_damage_per_turn.push(dpt); + armor_break_per_turn.push(abpt); + }); + + // TODO: End of macro conversion + + // TODO: Call this iteratively with all elements in macro + charming::Chart::new() + .title( + charming::component::Title::new() + .text("Damage for all cross-gen products") + .left("center"), + ) + .legend( + charming::component::Legend::new() + .left(10) + .top("middle") + .orient(Orient::Vertical) + .data(vec![ + "dps_safe", + "max_damage_per_action", + "max_damage_per_turn", + "armor_break_per_turn", + ]), + ) + .tooltip( + charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis), + ) + .x_axis( + charming::component::Axis::new() + .data(data_list.to_vec()) + .type_(charming::element::AxisType::Category), + ) + .y_axis(charming::component::Axis::new()) + .grid(charming::component::Grid::new().contain_label(true)) + .series( + charming::series::Line::new() + .data(dps_safe) + .name("dps_safe"), // .line_style(LineStyle::new().color("paleblue")), + ) + .series( + charming::series::Line::new() + .data(max_damage_per_action) + .name("max_damage_per_action"), + ) + .series( + charming::series::Line::new() + .data(max_damage_per_turn) + .name("max_damage_per_turn"), + ) + .series( + charming::series::Line::new() + .data(armor_break_per_turn) + .name("armor_break_per_turn"), + ) + .data_zoom( + charming::component::DataZoom::new() + .type_(charming::component::DataZoomType::Inside) + .start(0) + .end(100), + ) + .data_zoom(charming::component::DataZoom::new().start(0).end(100)) + .toolbox( + charming::component::Toolbox::new().feature( + charming::component::Feature::new() + .data_zoom( + charming::component::ToolboxDataZoom::new().y_axis_index("none"), + ) + .restore(charming::component::Restore::new()) + .save_as_image(charming::component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + ), + ) + .tooltip( + charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis), + ) + } + } +} impl From for RefinedEquipementList { fn from(value: InitialEquipementList) -> Self { @@ -225,17 +349,23 @@ impl DamageMatrix { } /// Calculate the binomial distribution and average the damage from there -fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, dices: usize) -> f64 { - let p = ((precision as i8 + value.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10); +fn binomial_dice_distribution( + equipement: &InnerEquipementStats, + precision: usize, + dices: usize, +) -> f64 { + let p = ((precision as i8 + equipement.precision) as f64 / 10.).clamp(0. + 1E-10, 1. - 1E-10); let binomial = Binomial::new(dices, p); (0..dices + 1) .map(|target_dices| { let probability_success = binomial.mass(target_dices); // Let's have weird half dices as usize; if target_dices >= 1 { - (value.damage as f64 - + value.p_damage as f64 - * (target_dices.clamp(0, value.rmax as usize).saturating_sub(1)) as f64) + (equipement.damage as f64 + + equipement.p_damage as f64 + * (target_dices + .clamp(0, equipement.rmax as usize) + .saturating_sub(1)) as f64) * probability_success } else { 0. @@ -244,6 +374,8 @@ fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, di .fold(0., |a, b| a + b) } +// TODO: Change this to be a thin type and replace enum by new(nb) et high(), med() etc.. +// : And add a way to do ranges easily /// The precision infered for a damage calculation event #[derive(EnumIter, Clone, Copy, Display)] #[allow(clippy::missing_docs_in_private_items)] diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index dc7870d..4c069e9 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -39,29 +39,16 @@ impl From for Equipement { } } -// TODO: Change this into tryfrom impl From for Equipement { fn from(val: EqNature) -> Self { Self { stats: val.stats, - // TODO : Checks that this is exactly desired behavious - // :Also check for Cross Weapon/Armor contamination // Checks that the nature is compatible with the previous iteration filter_function: FilterFunction::new(filter_id_unique_and_right_category()), } } } -// (Some(a), Some(b)) => { -// println!("{} {}", a, b); -// a == b -// } -// // There is no target and the part about to be added is generic -// (None, None) => true, -// // There is a specific target but the part about to be added is generic -// (Some(_), None) => true, -// // There is restriction on the target and the recipient -// (None, Some(_)) => true, impl From for Equipement { fn from(val: EqFinishing) -> Self { Self { diff --git a/weaponry/src/weaponry_structs/equipement_impl_io.rs b/weaponry/src/weaponry_structs/equipement_impl_io.rs index ee62cf8..e7a5215 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_io.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_io.rs @@ -2,11 +2,9 @@ // File: weaponry/src/weaponry_structs/equipement_impl_io.rs //! All implementation IO specific (mainly export and serde) -use std::path::Path; - -use crate::interfaces::ToCSV; - use super::equipement_advanced_repr::RefinedEquipementList; +use crate::interfaces::ToCSV; +use std::path::Path; impl ToCSV for RefinedEquipementList { fn write_csv(&self, path: &Path) -> csv::Result<()> { diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index d48a426..4e180cb 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -7,54 +7,48 @@ //! and therefore mostly serves as a TO-DO list //! -#![allow(dead_code)] -use crate::error::FatalEquipementError; -#[allow(unused_imports)] -use crate::interfaces::Reportable; -use crate::weaponry_structs::InitialEquipementList; -use crate::weaponry_structs::equipement_structs::DatabaseEquipementStats; -use crate::weaponry_structs::equipement_structs::EqFinishing; -use crate::weaponry_structs::equipement_structs::EqMaterial; -use crate::weaponry_structs::equipement_structs::EqNature; -use crate::weaponry_structs::equipement_structs::EqShape; use crate::{ - error::EquipementError, - interfaces::{RecipeCollection, RecipeDatabase, Scenario, ViewTable}, + error::FatalEquipementError, + interfaces::{RecipeCollection, RecipeDatabase, Scenario}, + weaponry_structs::{ + Equipement, InitialEquipementList, RefinedEquipementList, + equipement_impl_database::EquipementDatabase, + equipement_structs::{ + DatabaseEquipementStats, EqFinishing, EqMaterial, EqNature, EqShape, + InnerEquipementStats, + }, + }, }; -use super::Equipement; -use super::equipement_advanced_repr::RefinedEquipementList; -use super::equipement_impl_database::EquipementDatabase; -use super::equipement_structs::InnerEquipementStats; - -/// Mock config -pub struct ConfigMock {} -/// Mock Viewtable -pub struct ViewtableMock {} -impl ViewTable for ViewtableMock { - type InterestElementList = RefinedEquipementList; - - fn index_of_interest_points(&self) -> Vec { - todo!() - } - - fn find_points_of_interest(representation: &Self::InterestElementList) -> Self { - let _ = representation; - todo!() - } +/// Base Equipement Scenario config +pub struct ConfigEquipementScenario { + /// Table Name + pub table_name: String, + /// Database path + pub db_path: String, + // TODO[2]: Add something smart here to take care of the selection process + /// Wether the shapes are selected + pub shape: Option<()>, + /// Wether the materials are selected, and how many iteration there are + pub materials: Option, + /// Wether the natures are selected + pub nature: Option<()>, + /// Wether the finishing touches are selected + pub finishing: Option<()>, } /// A simple cross recipe scenario #[allow(clippy::missing_docs_in_private_items)] pub struct CrossRecipeScenario { // TODO: Should obv be inside the config - database_name: String, database: EquipementDatabase, - config: ConfigMock, + config: ConfigEquipementScenario, } impl CrossRecipeScenario { /// Automatically deserialize into an equipement + // TODO: Add to trait + // TODO: Add an optionnal filter fn deserde_into_equipement( &self, name: &str, @@ -62,10 +56,12 @@ impl CrossRecipeScenario { where T: TryFrom + From + Into, { + // TODO: This likely has too high a complexity and should either be a blanket implementation + // : or require the inner workings to implement methods to easily allow this deserialisation Ok(InitialEquipementList::from_vectored( self.database .serialize_vec_from_table::( - &self.database_name, + &self.config.table_name, Some(&format!("META_CATEGORY LIKE '{}'", name)), )? .into_iter() @@ -77,63 +73,59 @@ impl CrossRecipeScenario { .collect::, FatalEquipementError>>()?, )) } + + /// Generate all the operations to be processed with the current config + // TODO: Defer this to a custom type in the config some sort of OperationSelector + fn generate_selected_operation( + &self, + ) -> Result, FatalEquipementError> { + let mut operations = Vec::with_capacity(8); + if self.config.shape.is_some() { + operations.push(self.deserde_into_equipement::("Shape")?); + } + if let Some(qt) = self.config.materials { + for _ in 0..qt { + operations.push(self.deserde_into_equipement::("Materials")?); + } + } + if self.config.nature.is_some() { + operations.push(self.deserde_into_equipement::("Nature")?); + } + if self.config.finishing.is_some() { + operations.push(self.deserde_into_equipement::("Finishing")?); + } + if operations.is_empty() { + return Err(FatalEquipementError::CLISelection( + "No step was selected for generation, please select at least one step".into(), + )); + }; + Ok(operations) + } } impl Scenario for CrossRecipeScenario { type DatabaseType = EquipementDatabase; - type ViewTableType = ViewtableMock; type FinalListType = RefinedEquipementList; - type Config = ConfigMock; + type Config = ConfigEquipementScenario; - fn new_with_config(config: Self::Config) -> Result + fn new_with_config(config: Self::Config) -> Result where Self: Sized, { Ok(Self { - // TODO: Correct this relative path abomination - database_name: "Equipements".into(), - database: Self::DatabaseType::new("./databases/weapons.db")?, + database: Self::DatabaseType::new(&config.db_path)?, config, }) } - fn generate_refined_recipes(&self) -> Result { - // TODO: Depending on config, a different filter might be given here - let eq_shape = self.deserde_into_equipement::("Shape")?; - let eq_material = self.deserde_into_equipement::("Materials")?; - let eq_nature = self.deserde_into_equipement::("Nature")?; - #[allow(unused_variables)] - let eq_finishing = self.deserde_into_equipement::("Finishing")?; + fn generate_refined_recipes(&self) -> Result { + let operations = self.generate_selected_operation()?; - // println!( - // "{}\n{}\n{}\n{}", - // eq_shape.get_report(Some("EqShape ")), - // eq_material.get_report(Some("EqMaterials")), - // eq_nature.get_report(Some("EqNature ")), - // eq_finishing.get_report(Some("EqFinishing")) - // ); + let mut opertation_it = operations.into_iter(); + let mut refined_list = opertation_it.next().unwrap(); - // No op, just clarity - // TODO: Depending on config this step might differ - let mut f_list = eq_shape; - println!("{}", f_list.get_report(Some("Initial Weapons "))); - f_list.combine_all(&eq_material); - println!("{}", f_list.get_report(Some("Combined with Materials"))); - f_list.combine_all(&eq_material); - println!("{}", f_list.get_report(Some("Combined with Materials"))); - f_list.combine_all(&eq_nature); - println!("{}", f_list.get_report(Some("Combined with Natures "))); - // f_list.combine_all(&eq_finishing); - // println!("{}", f_list.get_report(Some("Combined with Finishing"))); - // TODO: The finishes are interesting if they are configured or at least tamed a little - // TODO: As a high cost finish cannot hope to compete with a low one - // TODO: and therefore need a special metric and fixed entry data to be mesured - Ok(f_list.into()) - } + opertation_it.for_each(|operation| refined_list.combine_all(&operation)); - fn generate_view_tables(&self, equipement_list: Self::FinalListType) -> Self::ViewTableType { - // TODO: Change this depending on the config ? or maybe a scenario is inerently tied to a viewtable ? - // The polymorphism will depend on many factors not yet known :( - Self::ViewTableType::find_points_of_interest(&equipement_list) + Ok(refined_list.into()) } } -- 2.45.1 From 8825587e537c195bcf39cd255010e0af2570c446 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 23 Feb 2025 06:14:51 +0100 Subject: [PATCH 5/6] First working commit on the macro --- weaponry/examples/usage_scenario.rs | 1 + weaponry/src/export.rs | 109 +++++++++ weaponry/src/lib.rs | 1 + .../equipement_advanced_repr.rs | 210 +++++++++--------- .../equipement_impl_database.rs | 2 + 5 files changed, 216 insertions(+), 107 deletions(-) create mode 100644 weaponry/src/export.rs diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index bb614ca..8a0646a 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -29,6 +29,7 @@ fn main() { .unwrap(); let refined_list = scenarios.generate_refined_recipes().unwrap(); + let b = RefinedEquipementList::default(); // if args.html_export{} refined_list.write_html(&save_path).unwrap(); diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs new file mode 100644 index 0000000..dea3e48 --- /dev/null +++ b/weaponry/src/export.rs @@ -0,0 +1,109 @@ +// Workspace: weaponry +// File: weaponry/src/export.rs +//! Module regrouping all generic function related to the exporting +//! +//! Mostly graphs and csv auto conversion + +/// A very complex macro created to add criterias to the graph +/// without repeating self explanatory parameter names in strings +/// +/// The syntax involved in the usage of this macro hence become esoteric +/// +/// # Example +/// ``` +/// # use weaponry::interfaces::RecipeCollection; +/// # use weaponry::add_field_to_chart; +/// # use weaponry::weaponry_structs::RefinedEquipementList; +/// # use weaponry::export::initial_chart; +/// # let self_ = RefinedEquipementList::default(); +/// # let initial_chart: charming::Chart = initial_chart("Damage for all cross-gen products"); +/// add_field_to_chart!( +/// self_, // Usually used inside the implementation and therefore self there +/// initial_chart, +/// ( +/// index # &String, +/// dps_safe # f64, +/// max_damage_per_action # f64, +/// armor_break_per_turn # f64, +/// ), +/// |ref_equipement| { +/// ( +/// &ref_equipement.advanced.display_name, +/// ref_equipement.advanced.max_damage_per_action, +/// ref_equipement.advanced.damage_per_turn, +/// ref_equipement.advanced.armor_break_per_turn, +/// ) +/// } +/// ); +/// ``` +/// +/// # Complexity and maintanability +/// +/// While the added complexity cannot be understated, the whole existence of this macro is +/// first and foremost based on the desire NOT to iterate multiple times on a dataset +/// which could easily reach 600k elements +/// +/// Knowing this tradeoff, the difficulty to maintain is considered an acceptable tradeoff +#[macro_export] +macro_rules! add_field_to_chart { + ($base_struct:expr, $chart:ident, ($names:ident # $name_type:ty, $($table_names:ident # $table_type:ty),* $(,)*), | $closure_name:ident | {($($fields:expr,)*)} + ) => { + let data_collection = $base_struct.inner.iter().map(|$closure_name| ( $($fields,)*) ); + let ($names, $($table_names),*) = data_collection.collect::<(Vec<$name_type>, $(Vec<$table_type>,)*)>(); + let $chart = $chart + .x_axis( + charming::component::Axis::new() + .data($names.to_vec()) + .type_(charming::element::AxisType::Category), + ); + $( + let $chart = $chart + .series( + charming::series::Line::new() + .data($table_names) + .name(stringify!($table_names)), // .line_style(LineStyle::new().color("paleblue")), + ); + )* + } +} + +/// Generate a generic graph, ready to be filled with data +pub fn initial_chart(chart_name: &str) -> charming::Chart { + charming::Chart::new() + .title( + charming::component::Title::new() + .text(chart_name) + .left("center"), + ) + .legend( + charming::component::Legend::new() + .left(10) + .top("middle") + .orient(charming::element::Orient::Vertical) + .data(vec![ + "dps_safe", + "max_damage_per_action", + "max_damage_per_turn", + "armor_break_per_turn", + ]), + ) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) + .data_zoom( + charming::component::DataZoom::new() + .type_(charming::component::DataZoomType::Inside) + .start(0) + .end(100), + ) + .data_zoom(charming::component::DataZoom::new().start(0).end(100)) + .toolbox( + charming::component::Toolbox::new().feature( + charming::component::Feature::new() + .data_zoom(charming::component::ToolboxDataZoom::new().y_axis_index("none")) + .restore(charming::component::Restore::new()) + .save_as_image(charming::component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + ), + ) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) + .y_axis(charming::component::Axis::new()) + .grid(charming::component::Grid::new().contain_label(true)) +} diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index cf331bd..4392409 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -7,6 +7,7 @@ mod database; pub mod error; +pub mod export; pub mod interfaces; mod strategy; pub mod weaponry_structs; diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index f680f8b..dafcd93 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -9,6 +9,7 @@ //! of all the fields even when the user will not be interested in them #![allow(dead_code)] +use crate::{add_field_to_chart, export::initial_chart, interfaces::RecipeCollection}; use core::f64; use std::fmt::Display; @@ -16,7 +17,7 @@ use crate::{ error::FatalEquipementError, interfaces::{RefinedList, ToAnalysis, ToTex}, }; -use charming::element::Orient; +use charming::Chart; use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; use probability::prelude::{Binomial, Discrete}; use serde::Serialize; @@ -73,119 +74,116 @@ impl ToTex for RefinedEquipementList { todo!() } } + impl ToAnalysis for RefinedEquipementList { + // TODO[3]: Consider wether the naming should be a parameter, + // or a config should be given or if the scenario should be fed again the Refined and ... fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> { let mut renderer = charming::HtmlRenderer::new("Ravenous Balancing", 4000, 2000) .theme(charming::theme::Theme::Dark); - // Save the chart as HTML file. - renderer.save(&make_chart(self), format!("{save_path}.html"))?; - return Ok(()); - // TODO: Migrate this into the view / renderer - // TODO: End the view idea and only focus on this renderer - pub fn make_chart(data: &RefinedEquipementList) -> charming::Chart { - // TODO: Add back sorting - // data.inner - // .sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); + let initial_chart: Chart = initial_chart("Damage for all cross-gen products"); - // TODO: Convert to macro - let raw_data = data.inner.iter().map(|refeq| { + // TODO[!]: Add sorting + // data.inner + // .sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); + + // let index: Vec<_>; + // let data_list: Vec<_>; + // (index, data_list) = self + // .inner + // .iter() + // .map(|ref_equipement| { + // ( + // &ref_equipement.advanced.display_name, + // &ref_equipement.advanced.damage_per_turn, + // ) + // }) + // .collect(); + + // // TODO[5]: This macro work is interesting while flawed and the optimisations are not worth more time invested now + // // TODO: Add this as a function and a macro + // // TODO: Convert to macro + // // TODO: Call this iteratively with all elements in macro + // let raw_data = self.inner.iter().map(|refeq| { + // ( + // &refeq.advanced.display_name, + // refeq.advanced.dps_safe, + // refeq.advanced.max_damage_per_action, + // refeq.advanced.damage_per_turn, + // refeq.advanced.armor_break_per_turn, + // ) + // }); + + add_field_to_chart!( + self, + initial_chart, + ( + index # &String, + dps_safe # f64, + max_damage_per_action # f64, + armor_break_per_turn # f64, + ), + |ref_equipement| { ( - &refeq.advanced.display_name, - refeq.advanced.dps_safe, - refeq.advanced.max_damage_per_action, - refeq.advanced.damage_per_turn, - refeq.advanced.armor_break_per_turn, + &ref_equipement.advanced.display_name, + ref_equipement.advanced.max_damage_per_action, + ref_equipement.advanced.damage_per_turn, + ref_equipement.advanced.armor_break_per_turn, ) - }); - let mut data_list = vec![]; - let mut dps_safe = vec![]; - let mut max_damage_per_action = vec![]; - let mut max_damage_per_turn = vec![]; - let mut armor_break_per_turn = vec![]; + } + ); + // add_field_to_chart!(dps_safe, graph); - raw_data - .into_iter() - .for_each(|(index, dps_s, dpa, dpt, abpt)| { - data_list.push(index); - dps_safe.push(dps_s); - max_damage_per_action.push(dpa); - max_damage_per_turn.push(dpt); - armor_break_per_turn.push(abpt); - }); + // let (data_list, dps_safe, max_damage_per_action, max_damage_per_turn, armor_break_per_turn) = + // raw_data.collect::<(Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>)>(); + // let mut data_list = vec![]; + // let mut dps_safe = vec![]; + // let mut max_damage_per_action = vec![]; + // let mut max_damage_per_turn = vec![]; + // let mut armor_break_per_turn = vec![]; - // TODO: End of macro conversion + // raw_data + // .into_iter() + // .for_each(|(index, dps_s, dpa, dpt, abpt)| { + // data_list.push(index); + // dps_safe.push(dps_s); + // max_damage_per_action.push(dpa); + // max_damage_per_turn.push(dpt); + // armor_break_per_turn.push(abpt); + // }); - // TODO: Call this iteratively with all elements in macro - charming::Chart::new() - .title( - charming::component::Title::new() - .text("Damage for all cross-gen products") - .left("center"), - ) - .legend( - charming::component::Legend::new() - .left(10) - .top("middle") - .orient(Orient::Vertical) - .data(vec![ - "dps_safe", - "max_damage_per_action", - "max_damage_per_turn", - "armor_break_per_turn", - ]), - ) - .tooltip( - charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis), - ) - .x_axis( - charming::component::Axis::new() - .data(data_list.to_vec()) - .type_(charming::element::AxisType::Category), - ) - .y_axis(charming::component::Axis::new()) - .grid(charming::component::Grid::new().contain_label(true)) - .series( - charming::series::Line::new() - .data(dps_safe) - .name("dps_safe"), // .line_style(LineStyle::new().color("paleblue")), - ) - .series( - charming::series::Line::new() - .data(max_damage_per_action) - .name("max_damage_per_action"), - ) - .series( - charming::series::Line::new() - .data(max_damage_per_turn) - .name("max_damage_per_turn"), - ) - .series( - charming::series::Line::new() - .data(armor_break_per_turn) - .name("armor_break_per_turn"), - ) - .data_zoom( - charming::component::DataZoom::new() - .type_(charming::component::DataZoomType::Inside) - .start(0) - .end(100), - ) - .data_zoom(charming::component::DataZoom::new().start(0).end(100)) - .toolbox( - charming::component::Toolbox::new().feature( - charming::component::Feature::new() - .data_zoom( - charming::component::ToolboxDataZoom::new().y_axis_index("none"), - ) - .restore(charming::component::Restore::new()) - .save_as_image(charming::component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), - ), - ) - .tooltip( - charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis), - ) - } + // TODO: End of macro conversion + + // let initial_chart = initial_chart + // .x_axis( + // charming::component::Axis::new() + // .data(data_list.to_vec()) + // .type_(charming::element::AxisType::Category), + // ) + // .series( + // charming::series::Line::new() + // .data(dps_safe) + // .name("dps_safe"), // .line_style(LineStyle::new().color("paleblue")), + // ) + // .series( + // charming::series::Line::new() + // .data(max_damage_per_action) + // .name("max_damage_per_action"), + // ) + // .series( + // charming::series::Line::new() + // .data(max_damage_per_turn) + // .name("max_damage_per_turn"), + // ) + // .series( + // charming::series::Line::new() + // .data(armor_break_per_turn) + // .name("armor_break_per_turn"), + // ); + + renderer.save(&initial_chart, format!("{save_path}.html"))?; + Ok(()) } } @@ -201,10 +199,8 @@ impl From for RefinedEquipementList { } } -#[cfg(test)] -use crate::interfaces::RecipeCollection; - -#[cfg(test)] +// #[cfg(test)] +// Used in exemples impl Default for RefinedEquipementList { fn default() -> Self { let eq = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]); diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index ebc47db..7f4ef60 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -61,6 +61,7 @@ pub struct EquipementFixedRecipe { #[allow(missing_docs)] pub struct MockRecipe {} +// TODO[1] : Add fixed recipes impl FixedRecipe for EquipementFixedRecipe { type KeyList = MockRecipe; @@ -73,6 +74,7 @@ impl FixedRecipe for EquipementFixedRecipe { } } +// TODO[3]: Migrate ASAP from this manual implementation /// Macro converting a value using serde and mapping an in house error macro_rules! from_serde { ($value: expr) => { -- 2.45.1 From f726b7ce15e93f2343dfe00ae393c7860f56e7da Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 23 Feb 2025 06:34:19 +0100 Subject: [PATCH 6/6] Cleans up most of the code of the html render --- weaponry/examples/usage_scenario.rs | 4 +- weaponry/src/interfaces.rs | 8 ++ .../equipement_advanced_repr.rs | 86 +++---------------- 3 files changed, 20 insertions(+), 78 deletions(-) diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index 8a0646a..23800e1 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -27,9 +27,9 @@ fn main() { finishing: args.finishing.then_some(()), }) .unwrap(); - let refined_list = scenarios.generate_refined_recipes().unwrap(); + let mut refined_list = scenarios.generate_refined_recipes().unwrap(); + refined_list.inner_sort(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); - let b = RefinedEquipementList::default(); // if args.html_export{} refined_list.write_html(&save_path).unwrap(); diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index b4a4a75..44b93ee 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -152,6 +152,14 @@ pub trait ToCSV { /// This element can be converted to an interactive .html pub trait ToAnalysis { + /// The explicit type of the underlying data + type InnerData; + + /// Sort the inner data with a given closure + fn inner_sort(&mut self, closure: T) + where + T: FnMut(&Self::InnerData, &Self::InnerData) -> std::cmp::Ordering; + /// Write as html fn write_html(&self, path: &str) -> Result<(), FatalEquipementError>; diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index dafcd93..5e73461 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -11,7 +11,7 @@ use crate::{add_field_to_chart, export::initial_chart, interfaces::RecipeCollection}; use core::f64; -use std::fmt::Display; +use std::{cmp::Ordering, fmt::Display}; use crate::{ error::FatalEquipementError, @@ -76,6 +76,15 @@ impl ToTex for RefinedEquipementList { } impl ToAnalysis for RefinedEquipementList { + type InnerData = RefinedEquipement; + + fn inner_sort(&mut self, closure: T) + where + T: FnMut(&RefinedEquipement, &RefinedEquipement) -> Ordering, + { + self.inner.sort_by(closure) + } + // TODO[3]: Consider wether the naming should be a parameter, // or a config should be given or if the scenario should be fed again the Refined and ... fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> { @@ -88,33 +97,6 @@ impl ToAnalysis for RefinedEquipementList { // data.inner // .sort_by(|a, b| a.advanced.dps_safe.total_cmp(&b.advanced.dps_safe)); - // let index: Vec<_>; - // let data_list: Vec<_>; - // (index, data_list) = self - // .inner - // .iter() - // .map(|ref_equipement| { - // ( - // &ref_equipement.advanced.display_name, - // &ref_equipement.advanced.damage_per_turn, - // ) - // }) - // .collect(); - - // // TODO[5]: This macro work is interesting while flawed and the optimisations are not worth more time invested now - // // TODO: Add this as a function and a macro - // // TODO: Convert to macro - // // TODO: Call this iteratively with all elements in macro - // let raw_data = self.inner.iter().map(|refeq| { - // ( - // &refeq.advanced.display_name, - // refeq.advanced.dps_safe, - // refeq.advanced.max_damage_per_action, - // refeq.advanced.damage_per_turn, - // refeq.advanced.armor_break_per_turn, - // ) - // }); - add_field_to_chart!( self, initial_chart, @@ -133,54 +115,6 @@ impl ToAnalysis for RefinedEquipementList { ) } ); - // add_field_to_chart!(dps_safe, graph); - - // let (data_list, dps_safe, max_damage_per_action, max_damage_per_turn, armor_break_per_turn) = - // raw_data.collect::<(Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>)>(); - // let mut data_list = vec![]; - // let mut dps_safe = vec![]; - // let mut max_damage_per_action = vec![]; - // let mut max_damage_per_turn = vec![]; - // let mut armor_break_per_turn = vec![]; - - // raw_data - // .into_iter() - // .for_each(|(index, dps_s, dpa, dpt, abpt)| { - // data_list.push(index); - // dps_safe.push(dps_s); - // max_damage_per_action.push(dpa); - // max_damage_per_turn.push(dpt); - // armor_break_per_turn.push(abpt); - // }); - - // TODO: End of macro conversion - - // let initial_chart = initial_chart - // .x_axis( - // charming::component::Axis::new() - // .data(data_list.to_vec()) - // .type_(charming::element::AxisType::Category), - // ) - // .series( - // charming::series::Line::new() - // .data(dps_safe) - // .name("dps_safe"), // .line_style(LineStyle::new().color("paleblue")), - // ) - // .series( - // charming::series::Line::new() - // .data(max_damage_per_action) - // .name("max_damage_per_action"), - // ) - // .series( - // charming::series::Line::new() - // .data(max_damage_per_turn) - // .name("max_damage_per_turn"), - // ) - // .series( - // charming::series::Line::new() - // .data(armor_break_per_turn) - // .name("armor_break_per_turn"), - // ); renderer.save(&initial_chart, format!("{save_path}.html"))?; Ok(()) -- 2.45.1