From 4f2bb22420a8800c2dfaa8488470fc2a130ebb39 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 5 Mar 2025 07:00:50 +0100 Subject: [PATCH 1/4] Code coverage (with some shenenigans) --- weaponry/src/database.rs | 17 ++--- weaponry/src/interfaces.rs | 13 ++-- weaponry/src/lib.rs | 1 + .../equipement_advanced_tools.rs | 73 ++++++++++++++++++- .../weaponry_structs/equipement_structs.rs | 6 +- 5 files changed, 89 insertions(+), 21 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index ac8ccac..755a68c 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -34,16 +34,13 @@ fn generate_select_query( table_name: &str, filter: Option<&str>, ) -> String { - format!( - "SELECT {} FROM {}{};", - T::attributes_slice() - .iter() - .map(|(k, _v)| k.to_owned()) - .collect::>() - .join(","), - table_name, - filter.map_or_else(String::default, |j| " WHERE ".to_string() + j) - ) + let fields = T::attributes_slice() + .iter() + .map(|(k, _v)| k.to_owned()) + .collect::>() + .join(","); + let filter = filter.map_or_else(String::default, |j| " WHERE ".to_string() + j); + format!("SELECT {} FROM {}{};", fields, table_name, filter) } /// Generate create table_name with fields as columns diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index ba67fe1..bdafb57 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -61,24 +61,25 @@ where /// A blanket implementation giving all combinaisons of recipes with another RecipeCollection /// /// This method doesn't make use of parallel iterators as the workload is way faster than would be the memory dispatch + // #[coverage(off)] // Tarpaulin cannot deal with iter and long lines fn combine_all(&mut self, other: &G) where G: RecipeCollection, { self.assign_inner( self.ref_inner() - .iter() + .iter() // Iterate over every recipe .flat_map(|inner_recipes| { other - .ref_inner() - .iter() + .ref_inner() // Take a reference of recipe + .iter() // Iterate overe every recipe .filter(|&external_recipes| external_recipes.backward_filter(inner_recipes)) .map(|external_recipes: &Self::Recipes| { inner_recipes.add_ref_to_self(external_recipes) }) - .collect::>() - }) - .collect::>(), + .collect::>() // Collect all a vector of recipe + }) // Flatten all the vector of recipes into a big vector + .collect::>(), // Updates the inner collection to the collected recipes ); } diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index 8d2e64e..e035bd5 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -2,6 +2,7 @@ // File: weaponry/src/lib.rs //! Weaponry module, handling all weaponry creation and analysis +#![feature(coverage_attribute)] #![feature(int_roundings)] #![warn(missing_docs, clippy::missing_docs_in_private_items)] #![feature(iter_intersperse, generic_arg_infer)] diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index cec8a29..39d045b 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -81,7 +81,7 @@ pub(super) fn get_damage_with_simulation( precision: Precision(9), }, ]; - if value.speed >= 0 { + if (value.speed >= 5) || (value.range > 0) { turns.push(TurnInfo { actions, attacks, @@ -309,7 +309,10 @@ mod test { equipement_thin_types::{Actions, Attacks}, }; - use super::{BestDamageScenarios, Dices, Precision, binomial_dice_distribution}; + use super::{ + BestDamageScenarios, Dices, Precision, binomial_dice_distribution, + get_damage_with_simulation, + }; fn new_inner_eq() -> InnerEquipementStats { InnerEquipementStats { @@ -374,6 +377,7 @@ mod test { p_damage: 2, precision: 0, rmax: 2, + speed: 10, action_cost: 2, ..Default::default() }; @@ -382,6 +386,7 @@ mod test { p_damage: 2, precision: 0, rmax: 2, + range: 10, action_cost: 2, reload_cost: Some(2), ..Default::default() @@ -543,4 +548,68 @@ mod test { assert_close!(val.clone().map_or(0., |v| v.damage_done), res); }); } + + #[test] + fn test_scenario_damage() { + let eq1 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + action_cost: 2, + ..Default::default() + }; + let eq2 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + speed: 10, + action_cost: 2, + ..Default::default() + }; + let eq3 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + range: 10, + action_cost: 2, + reload_cost: Some(2), + ..Default::default() + }; + assert_close!( + get_damage_with_simulation(&eq1, Actions(2), Attacks(1)), + 8.3998 + ); + assert_close!( + get_damage_with_simulation(&eq2, Actions(2), Attacks(1)), + 9.6936 + ); + assert_close!( + get_damage_with_simulation(&eq3, Actions(2), Attacks(1)), + 9.6936 + ); + } + #[test] + fn test_basic_impl_damage_scenario() { + let eq1 = InnerEquipementStats { + damage: 10, + p_damage: 2, + precision: 0, + rmax: 2, + action_cost: 2, + ..Default::default() + }; + let d1 = BestDamageScenarios::from_action_constraints_it( + &eq1, + Actions(2), + Attacks(2), + Dices(2), + Precision(2), + ) + .unwrap(); + let d2 = d1.clone() + d1; + let _deref_damage = *d2; + } } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index c7a5a86..0014d36 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -61,8 +61,8 @@ pub(crate) fn filter_id_unique_and_right_category() (Some(a), Some(b)) => a.can_apply_onto(b), // TODO: Unsound to have a generic nature, this should be caught at serialisation // There is no target and the part about to be added is generic - (None, _) => panic!("The EqNature about to be added cannot be generic"), - (Some(_), None) => panic!("The part about to be added unto cannot be generic"), + (None, _) => false, //panic!("The part about to be added cannot be generic"), + (Some(_), None) => false, //panic!("The part about to be added unto cannot be generic"), } } } @@ -300,7 +300,7 @@ mod test { fn test_creating_all_equipements() { let shape = vec![EqShape::default().into(), EqShape::default().into()]; - let _nature: Vec = vec![EqNature::default().into(), EqNature::default().into()]; + // let _nature: Vec = vec![EqNature::default().into(), EqNature::default().into()]; let material = vec![EqMaterial::default().into(), EqMaterial::default().into()]; let finishing = vec![EqFinishing::default().into(), EqMaterial::default().into()]; -- 2.45.1 From 5a84833922c8fe777c468ba6f9f82ad34594a5b9 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 5 Mar 2025 20:05:36 +0100 Subject: [PATCH 2/4] More code coverage --- weaponry/src/interfaces.rs | 12 ++++++++++++ .../src/weaponry_structs/equipement_advanced_repr.rs | 3 ++- weaponry/src/weaponry_structs/equipement_scenario.rs | 7 +++++++ weaponry/src/weaponry_structs/equipement_structs.rs | 3 +-- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index bdafb57..8589d89 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -316,3 +316,15 @@ pub trait Scenario where for<'a> &'a <<::InitialEquipementList ) } } +#[cfg(test)] +mod test { + use super::RecipeCollection; + use crate::weaponry_structs::{InitialEquipementList, equipement_structs::EqShape}; + + #[test] + fn test_from_iter_intermediate() { + let _b = ::from_iter_intermediate::( + [Ok(EqShape::default()), Ok(EqShape::default())].into_iter(), + ); + } +} diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 7d593ff..87e6575 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -45,7 +45,8 @@ pub struct RefinedEquipement { /// The complete equipement list, refined with all advanced stats pub struct RefinedEquipementList { /// Inner list of Refined Equipements - inner: Vec, + // TODO[!]: The use of pub stays for the usage of the example showcasing the macro in export + pub inner: Vec, } // DONE: The use of Deref could be a subtle gotcha diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index c767e34..4c9b839 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -57,6 +57,7 @@ pub struct IndividualElementsScenario { impl CrossRecipeScenario { /// Generate all the operations to be processed with the current config + // TODO[!]: Consider adding to interface fn generate_selected_operation( &self, ) -> Result, FatalEquipementError> { @@ -134,3 +135,9 @@ impl Scenario for CrossRecipeScenario { &self.database } } + +#[cfg(test)] +mod test { + #[test] + fn test_scenario() {} +} diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 0014d36..29cc8c1 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -273,8 +273,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; -- 2.45.1 From b85545559668a79d49e604cc63f67ec9b69e2e4b Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 5 Mar 2025 20:28:08 +0100 Subject: [PATCH 3/4] adds xtask, lot of bloat tho ? --- .gitignore | 1 + Cargo.toml | 2 +- more_fields_macro/src/lib.rs | 2 ++ xtask/Cargo.toml | 7 +++++++ xtask/src/main.rs | 3 +++ 5 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 xtask/Cargo.toml create mode 100644 xtask/src/main.rs diff --git a/.gitignore b/.gitignore index deed149..13d712b 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,4 @@ callgrind* cache.out tarpaulin-report.html *.bkp +coverage/ diff --git a/Cargo.toml b/Cargo.toml index b294bf4..0b4e538 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ [workspace] members = [ "cli_parser", "config", "graphs", "make", "more_fields", "more_fields_macro", "ravenous-tools", "stats", - "tablegen", "weaponry", + "tablegen", "weaponry", "xtask", ] resolver = "3" diff --git a/more_fields_macro/src/lib.rs b/more_fields_macro/src/lib.rs index 4bfca29..f133eaf 100644 --- a/more_fields_macro/src/lib.rs +++ b/more_fields_macro/src/lib.rs @@ -12,6 +12,7 @@ // use proc_macro::TokenStream; // use quote::quote; // use syn::{Data, DeriveInput, Fields, parse_macro_input}; +#![feature(coverage_attribute)] extern crate proc_macro; use proc_macro::{Span, TokenStream}; @@ -21,6 +22,7 @@ use syn::Ident; use syn::parse_macro_input; use syn::{Data, Fields}; +#[coverage(off)] #[proc_macro_derive(FieldsAsSlice, attributes(INTEGER, NULL, REAL, TEXT, BLOB))] pub fn derive_iterable(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml new file mode 100644 index 0000000..2cdf5a3 --- /dev/null +++ b/xtask/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "xtask" +edition = "2024" +version.workspace = true + +[dependencies] +xtaskops = "0.4.2" diff --git a/xtask/src/main.rs b/xtask/src/main.rs new file mode 100644 index 0000000..90528e7 --- /dev/null +++ b/xtask/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + let _ = xtaskops::tasks::main(); +} -- 2.45.1 From d7e7ffcb17af5e99a997daba20c7b0f935d7f313 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 6 Mar 2025 01:37:24 +0100 Subject: [PATCH 4/4] Cleanup and adds a Flow doc --- README.md | 2 +- make/src/lib.rs | 2 +- more_fields_macro/src/lib.rs | 10 +- weaponry/examples/graph.rs | 180 --------------- weaponry/examples/usage_import_tex.rs | 215 ------------------ weaponry/flow_and_structure.md | 40 ++++ weaponry/src/interfaces.rs | 4 +- .../src/weaponry_structs/equipement_fields.rs | 4 +- .../weaponry_structs/equipement_scenario.rs | 61 ++++- .../weaponry_structs/equipement_structs.rs | 2 +- 10 files changed, 104 insertions(+), 416 deletions(-) delete mode 100644 weaponry/examples/graph.rs delete mode 100644 weaponry/examples/usage_import_tex.rs create mode 100644 weaponry/flow_and_structure.md diff --git a/README.md b/README.md index 64c2c63..77ed0ed 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg) +![version](badges/version.svg) ![code coverage](badges/plastic.svg) # ravenous-tools diff --git a/make/src/lib.rs b/make/src/lib.rs index bc35f63..2ecb392 100644 --- a/make/src/lib.rs +++ b/make/src/lib.rs @@ -2,7 +2,7 @@ // File: make/src/lib.rs //! The module `makepdf` is responsible for making a pdf using pdflatex. //! -//! The main function, [`make_pdf`](crate::makepdf::make_pdf), orchestrates the entire process of preparing, +//! The main function, [`make_pdf`], orchestrates the entire process of preparing, //! building, and cleaning up LaTeX files to produce a final PDF. It relies on several other modules //! within the `makepdf` workspace to perform specific tasks. //! diff --git a/more_fields_macro/src/lib.rs b/more_fields_macro/src/lib.rs index f133eaf..25ad5d2 100644 --- a/more_fields_macro/src/lib.rs +++ b/more_fields_macro/src/lib.rs @@ -1,13 +1,13 @@ // Workspace: more_fields_macro // File: more_fields_macro/src/lib.rs //! A very simple proc macro in chage of giving a field slice over ("name","sql_type") -//! This macro is a fork of the excellent work of : https://crates.io/crates/struct_iterable +//! This macro is a fork of the excellent work of : //! //! Other ressources include: -//! - https://github.com/rust-lang/reference/blob/master/src/procedural-macros.md#attribute-macros -//! - https://docs.rs/syn/latest/syn/struct.Attribute.html -//! - https://docs.rs/syn/latest/syn/struct.Attribute.html#parsing-from-tokens-to-attribute -//! - https://docs.rs/syn/latest/syn/struct.Ident.html +//! - +//! - +//! - +//! - //! // use proc_macro::TokenStream; // use quote::quote; diff --git a/weaponry/examples/graph.rs b/weaponry/examples/graph.rs deleted file mode 100644 index 053cb0a..0000000 --- a/weaponry/examples/graph.rs +++ /dev/null @@ -1,180 +0,0 @@ -// 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_import_tex.rs b/weaponry/examples/usage_import_tex.rs deleted file mode 100644 index a8a4721..0000000 --- a/weaponry/examples/usage_import_tex.rs +++ /dev/null @@ -1,215 +0,0 @@ -// Workspace: weaponry -// File: examples/usage_import_tex.rs -//! Example of a first initialisation -//! All this work is cursed and rushed - -// use logos::Logos; -// use more_fields::FieldsAsSlice; -// use serde::Serialize; -// use serde_rusqlite::to_params_named; -use weaponry::interfaces::RecipeDatabase; -use weaponry::weaponry_structs::equipement_impl_database::EquipementDatabase; -// use weaponry::weaponry_structs::{DamageMod, DamageType, WeaponMetaCategory}; -// use weaponry::weaponry_structs::PhysicalDamageType; -use weaponry::weaponry_structs::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}; - -// #[derive(Logos, Debug, PartialEq)] -// enum ModeParser { -// #[regex(r"\[\[\w+\]\]", |lex| std::convert::TryInto::::try_into(&lex.slice()[2..lex.slice().len()-2]).unwrap())] -// Tertiary(PhysicalDamageType), -// #[regex(r"\[\w+\]", |lex| std::convert::TryInto::::try_into(&lex.slice()[1..lex.slice().len()-1]).unwrap())] -// Secondary(PhysicalDamageType), -// #[regex(r"\w+", |lex| std::convert::TryInto::::try_into(lex.slice()).unwrap())] -// Primary(PhysicalDamageType), -// } -// let b = DamageMod::Primary() - -fn main() { - let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); - // init_db(&db); - let initial_deserialisation = db.serialize_vec_from_table::("Equipements", None); - // println!("Initial deserialisation in DatabaseEquipementStats: {:?}", initial_deserialisation); - // println!("First entry: {:?}", initial_deserialisation.as_ref().unwrap()[0]); - - let intermediate_deserialisation = initial_deserialisation.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::>(); - // let v = intermediate_deserialisation - // .iter() - // .scan(0, |status, eq| { - // if eq.is_ok() { - // *status = 1; - // } else { - // *status = 0; - // } - // Some(*status) - // }) - // .sum::(); - let f = intermediate_deserialisation.iter().fold((0, 0), |val, res| (val.0 + res.is_ok() as usize, val.1 + 1_usize)); - println!("Final data {:#?}", intermediate_deserialisation); - println!("Succeded in parsing {}/{}", f.0, f.1); -} - -// #[derive(Default)] -// struct FoundFields { -// reload: Option, -// range: Option, -// parmor: Option, -// } -// fn init_db(db: &EquipementDatabase) { -// let mut global_index = 0; -// let b = load_base(&mut global_index); -// db.initialize_empty_table::("Equipements").unwrap(); - -// db.conn.execute("DELETE FROM Equipements", []).unwrap(); -// println!("Added {global_index} ids to the new database"); - -// b.iter().for_each(|v| insert_into_db(db, v)); -// } -// fn parse_special_field(fields: &str) -> FoundFields { -// // "Arbalète & Distance & 4 & 1 & 3 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ", -// let re = regex::Regex::new(r"((?\d)reload)?(, )?(Gls\{parmure\} (?\d))?(, )?((?\d+)m)?").unwrap(); -// re.captures(fields).map_or(FoundFields::default(), |f| FoundFields { -// reload: f.name("reload").map(|n| n.as_str().parse().unwrap()), -// range: f.name("range").map(|v| v.as_str().parse().unwrap()), -// parmor: f.name("parmor").map(|v| v.as_str().parse().unwrap()), -// }) -// } - -// #[allow(dead_code)] -// fn insert_into_db(db: &EquipementDatabase, row: T) { -// let sql = &format!( -// "INSERT INTO Equipements ({}) VALUES ({})", -// DatabaseEquipementStats::attributes_slice() -// .iter() -// // .filter_map(|(k, _v)| (*k != "id").then_some(*k)) -// .map(|(k, _v)| *k) -// .collect::>() -// .join(", "), -// DatabaseEquipementStats::attributes_slice() -// .iter() -// // .filter_map(|(k, _v)| (*k != "id").then_some(":".to_string() + *k)) -// .map(|(k, _v)| ":".to_string() + *k) -// .collect::>() -// .join(", ") -// ); -// // println!("Database Request {}", sql); -// let r = db.conn.execute(sql, to_params_named(&row).unwrap().to_slice().as_slice()); -// match r { -// Ok(_r) => { -// // println!("Loaded {:?} entries into the database", _r); -// } -// Err(e) => println!("Error: {} while processing entry", e), -// }; -// } - -// // fn load_base(index: &mut u8) -> Vec { -// // BASE_FORME -// // .iter() -// // .map(|row| { -// // let fields = row.split("&").map(|field| field.trim()).collect::>(); -// // let FoundFields { reload, range, parmor } = parse_special_field(fields[15]); -// // *index += 1; -// // // "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ", -// // // 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 -// // DatabaseEquipementStats { -// // id: *index, -// // meta_category: "Forme".into(), -// // name: fields[0].to_string(), -// // category: serde_json::to_string(&parse_to_type(fields[1]).unwrap()).unwrap(), -// // rarity: 0, -// // cost: 0, -// // precision: 0, -// // difficulty: fields[16].parse().unwrap_or_default(), // NOT PARSED YET -// // // tier: , -// // damage: fields[2].parse().unwrap_or_default(), -// // p_damage: fields[3].parse().unwrap_or_default(), -// // rmax: fields[4].parse().unwrap_or_default(), -// // armor_break: fields[5].parse().unwrap_or_default(), -// // protection: fields[6].parse().unwrap_or_default(), -// // integrity: fields[7].parse().unwrap_or_default(), - -// // torque_two_handed: serde_json::to_string(&match fields[8] { -// // "-" => None, -// // v => Some(v.parse::().unwrap()), -// // }) -// // .unwrap(), -// // torque_one_handed: serde_json::to_string(&match fields[9] { -// // "-" => None, -// // v => Some(v.parse::().unwrap()), -// // }) -// // .unwrap(), // The or default is a problem -// // damage_type: serde_json::to_string(&parse_to_damagetype(fields[10])).unwrap(), - -// // dodge: fields[11].parse().unwrap_or_default(), -// // parry: fields[12].parse().unwrap_or_default(), -// // speed: fields[13].parse().unwrap_or_default(), -// // stealth: fields[14].parse().unwrap_or_default(), -// // reload_cost: serde_json::to_string(&reload).unwrap(), -// // range: range.unwrap_or_default(), -// // armor_pierce: parmor.unwrap_or_default(), -// // // meta_category: parse_to_type(fields[1]), - -// // // target: fields[5].parse().unwrap(), // Armors ? -// // ..Default::default() -// // } -// // }) -// // .collect::>() -// // } - -// fn parse_to_damagetype(fields: &str) -> DamageType { -// DamageType(fields.split(",").map(|v| ModeParser::lexer(v.trim()).next().unwrap().unwrap().into()).collect::>()) -// } - -// impl From for DamageMod { -// fn from(value: ModeParser) -> Self { -// match value { -// ModeParser::Primary(v) => DamageMod::Primary(v), -// ModeParser::Secondary(v) => DamageMod::Secondary(v), -// ModeParser::Tertiary(v) => DamageMod::Tertiary(v), -// } -// } -// } - -// fn parse_to_type(text: &str) -> Option { -// match text { -// "Hast" => Some(WeaponMetaCategory::Staves), -// "Tranchantes" => Some(WeaponMetaCategory::Slash), -// "Contondantes" => Some(WeaponMetaCategory::Blunt), -// "Distance" => Some(WeaponMetaCategory::Ranged), -// "Boucliers" => Some(WeaponMetaCategory::Shields), -// "Armures" => Some(WeaponMetaCategory::Armor), -// "Exotiques" => Some(WeaponMetaCategory::Exotic), -// _ => None, -// } -// } - -// const BASE_FORME: &[&str] = &[ -// // "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ", -// // "Name & Type & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & mode & 9 & 10 & 11 & 12 & 3reload, & ddlvl{13} ", -// "Griffes & Tranchantes & 2 & 1 & 4 & 1 & 1 & 2 & 3 & 6 & slash & 2 & 0 & 3 & 1 & - & ddlvl{1} ", -// "Hast & Hast & 4 & 1 & 2 & 1 & 4 & 3 & 10 & 18 & pierce, [slash] & -1 & -3 & 1 & 0 & - & ddlvl{1} ", -// "Épée & Tranchantes & 3 & 1 & 3 & 1 & 3 & 4 & 12 & 15 & slash, [pierce] & 0 & 1 & 0 & 0 & - & ddlvl{1} ", -// "Marteau & Contondantes & 5 & 1 & 1 & 1 & 4 & 3 & 11 & 18 & blunt & -1 & -1 & 0 & -2 & - & ddlvl{1} ", -// "Hache & Tranchantes & 4 & 2 & 1 & 3 & 4 & 3 & 9 & 14 & slash & 0 & -1 & 1 & 0 & - & ddlvl{1} ", -// "Arbalète & Distance & 4 & 1 & 3 & 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ", -// "Arc & Distance & 3 & 1 & 4 & 0 & 2 & 1 & - & 7 & pierce & 0 & 0 & 0 & 0 & 1reload, Gls{parmure} 2, 120m & ddlvl{1} ", -// "Boucliers & Boucliers & 1 & 1 & 2 & 0 & 3 & 2 & 6 & 8 & blunt & -2 & 0 & -1 & -2 & - & ddlvl{1} ", -// "Armures & Armures & & & & & 3 & 2 & 10 & - & blunt & -1 & 0 & 0 & -1 & - & ddlvl{1} ", -// // "% Explosive & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{5} ", -// // "% Flexible & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{2} ", -// // "% Exotique & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{3} ", -// ]; -// #[allow(dead_code)] -// const BASE_SHAPE: &[&str] = &[ -// // " Maniement & damagew & + & rmax & arbreakw & faShield* & faShieldVirus & $mathbb{T}2$ & $mathbb{T}$1 & Esq. & Par. & Vit. & Disc. & Spécial & Diff. " -// // " % Nom & Dg & + & RM & AB & Pr & In & T2 & T1 & Esq. & Par. & Vit. & Disc. & Sp & Diff", -// " Arme Légère & -1 & 0 & 2 & -1 & -1 & -1 & -5 & -6 & 2 & 2 & 0 & 0 & Ag+half, Esq.+half & ddlvl{1}", -// " Arme Moyenne & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & - & ddzero", -// " Arme Lourde & 2 & 1 & 1 & 0 & 1 & 0 & 8 & 11 & -2 & -2 & -1 & -1 & - & ddlvl{1}", -// " Arme Super-lourde & 3 & 2 & 1 & 1 & 2 & 1 & 23 & 23 & -3 & -3 & -3 & -3 & 2A, Ag-1, [[blunt]], Précision-1 & ddlvl{2}", -// // " Arme Combinée & - & - & - & - & - & -2 & - & - & - & - & - & - & - & ddlvl{3}", // We'll have to think about this one -// // " Arme Escamotable & - & - & - & - & - & - & - & - & - & - & - & - & - & ddlvl{3}", // We'll have to think about this one -// " Armure Légère & - & - & - & - & -1 & -1 & -1 & - & 1 & 0 & 0 & 1 & Ag+1 & ddlvl{1}", -// " Armure Moyenne & - & - & - & - & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & - & ddzero", -// " Armure Lourde & - & - & - & - & 1 & 1 & 13 & - & -3 & -3 & -2 & -3 & Ag-1, Précision -1 & ddlvl{1}", -// " Armure Super-lourde & - & - & - & - & 3 & 3 & 25 & - & -5 & -4 & -4 & -6 & Ag-1, Précision -1 & ddlvl{2}", -// ]; diff --git a/weaponry/flow_and_structure.md b/weaponry/flow_and_structure.md new file mode 100644 index 0000000..d5cba4e --- /dev/null +++ b/weaponry/flow_and_structure.md @@ -0,0 +1,40 @@ +# Introduction +The generic nature of the recipe generator makes it rather complicated to navigate and comprehend; +however while suffering from many developpement mistakes and shortcommings, a good deal of code reuse was averted + +# Structure +The inner structures follow the following. + +| Underlaying data | Encapsulating Element | Encapsulating list of elements | +|-----------------------|----------------------------|--------------------------------| +| DatabaseInner (DeSer) | None | None | +| BaseInner (Converted) | InitialElement | InitialElementList | +| AdvancedInner (Calc) | RefinedElement (+BaseInner)| RefinedElementList | + + +# Explainations +| Category | Explainations | Traits | Impls | +|---------------------|------------------------------|----------------------------------------|------------------------| +| DatabaseInner | Deserialization InnerData | FieldsAsSclice | DatabaseEquipementStats| +| BaseInner | BuildingBlock InnerData | FieldAsSlice, Add, From | InnerEquipementStats | +| AdvancedInner | Calculated data for analysis | Serialize, From | AdvancedStats | +| IntermediateElement | Setup InitialElement | | EqFinishing, etc.. | +| InitialElement | Real Elements by Combination | From, Combinable | Equipement | +| RefinedElement | Export & Analysis | Serialize | RefinedEquipement | +| InitialElementList | Create list by cross combin. | RecipeCollection | InitialEquipementList | +| RefinedElementList | Analysis & Export | From) -> Self; - /// Create a collection from an iterator of intermediate values + /// Create a collection from an iterator of intermediate values T fn from_iter_intermediate( iter_inter: impl Iterator>, ) -> Result @@ -302,7 +302,7 @@ pub trait Scenario where for<'a> &'a <<::InitialEquipementList /// Automatically deserialize into an equipement - fn deserde_into_equipement( + fn deserde_into_processed_representation( &self, filter: Option<&str>, ) -> Result diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 5780cbc..e3924e7 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -58,7 +58,7 @@ pub enum PhysicalDamageType { /// Weapon damage, combining the base weapon damage type and it's level /// -/// Signifying wether the damage is pure or [secondary] or [[tertiary]] +/// Signifying wether the damage is pure or \[secondary\] or \[\[tertiary\]\] #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Debug, Display, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] @@ -85,7 +85,7 @@ impl Deref for DamageType { } impl DamageType { - /// Create a new DamageType from a vector of [DamageMod] + /// Create a new DamageType from a vector of *DamageMod* pub fn new(inner_data: Vec) -> Self { Self(inner_data) } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 4c9b839..d228346 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -63,24 +63,27 @@ impl CrossRecipeScenario { ) -> Result, FatalEquipementError> { let mut operations = Vec::with_capacity(8); if self.config.shape.is_some() { - operations - .push(self.deserde_into_equipement::(Some("META_CATEGORY LIKE 'Shape'"))?); + operations.push(self.deserde_into_processed_representation::(Some( + "META_CATEGORY LIKE 'Shape'", + ))?); } if let Some(qt) = self.config.materials { for _ in 0..qt { - operations.push(self.deserde_into_equipement::(Some( - "META_CATEGORY LIKE 'Materials'", - ))?); + operations.push( + self.deserde_into_processed_representation::(Some( + "META_CATEGORY LIKE 'Materials'", + ))?, + ); } } if self.config.nature.is_some() { - operations.push( - self.deserde_into_equipement::(Some("META_CATEGORY LIKE 'Nature'"))?, - ); + operations.push(self.deserde_into_processed_representation::(Some( + "META_CATEGORY LIKE 'Nature'", + ))?); } if self.config.finishing.is_some() { operations.push( - self.deserde_into_equipement::(Some( + self.deserde_into_processed_representation::(Some( "META_CATEGORY LIKE 'Finishing'", ))?, ); @@ -138,6 +141,46 @@ impl Scenario for CrossRecipeScenario { #[cfg(test)] mod test { + use more_fields::FieldsAsSlice; + + use crate::{ + interfaces::{RecipeDatabase, Scenario}, + weaponry_structs::{ + equipement_impl_database::EquipementDatabase, + equipement_structs::{DatabaseEquipementStats, EqFinishing, InnerEquipementStats}, + }, + }; + + use super::{ConfigEquipementScenario, CrossRecipeScenario}; + + struct TestStruct { + id: usize, + name: String, + } #[test] fn test_scenario() {} + #[test] + fn test_deserde_into() { + let b = CrossRecipeScenario { + database: EquipementDatabase { + conn: rusqlite::Connection::open_in_memory().unwrap(), + }, + config: ConfigEquipementScenario { + table_name: "TestStruct".to_owned(), + db_path: "None".to_owned(), + shape: None, + materials: None, + nature: None, + finishing: None, + }, + }; + + b.get_database().conn.execute("CREATE TABLE IF NOT EXISTS Finishing (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",[]).unwrap(); + b.get_database() + .initialize_empty_table::("Finishing") + .unwrap(); + // let r = b + // .deserde_into_processed_representation::(None) + // .unwrap(); + } } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 29cc8c1..28891e6 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -104,7 +104,7 @@ pub struct InnerEquipementStats { /// /// The categories are: Staves, Blunt, Slash, Ranged, Armors, Shields, Exotic, None, pub category_base: Option, - /// The category size as [WeaponBaseSize] + /// The category size as WeaponBaseSize /// /// Categories are : (Light, Medium, Heavy and SuperHeavy) pub category_size: Option, -- 2.45.1