diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index d7f70a4..b1a596a 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -7,7 +7,6 @@ edition = "2024" more_fields = {path ="../more_fields"} comfy-table = "7.1.4" csv = "1.3.1" -fastrand = "2.3.0" probability = "0.20.3" rusqlite = { version = "0.33.0" } # , features = ["bundled"] serde = { version = "1.0.217", features = ["derive"] } @@ -19,6 +18,7 @@ regex = "1.11.1" charming = { version = "0.4.0", features = [] } [dev-dependencies] +fastrand = "2.3.0" criterion = { version = "0.5" } regex = "1.11.1" pretty_assertions = "^1.4" diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index 6b5528b..fe13caa 100644 Binary files a/weaponry/databases/weapons.db and b/weaponry/databases/weapons.db differ diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index c9766d4..ac8ccac 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -79,6 +79,7 @@ mod test { } /// setting up test db and table, also adding arbitrary data inside fn mock_set_up(db_filename: &str) -> EquipementDatabase { + let _ = std::fs::remove_file(db_filename); let equip_db = EquipementDatabase::new(db_filename).unwrap(); equip_db.conn.execute("CREATE TABLE IF NOT EXISTS TestStruct (id INTEGER UNIQUE, name TEXT, PRIMARY KEY('id' AUTOINCREMENT));",()).unwrap(); equip_db diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index d33eee2..ba67fe1 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -8,6 +8,7 @@ use std::{path::Path, rc::Rc}; use more_fields::FieldsAsSlice; +use rusqlite::Connection; use serde::de::DeserializeOwned; use crate::error::FatalEquipementError; @@ -91,6 +92,21 @@ where /// Create a collection from a vector fn from_vectored(list: Vec) -> Self; + + /// Create a collection from an iterator of intermediate values + fn from_iter_intermediate( + iter_inter: impl Iterator>, + ) -> Result + where + Self: std::marker::Sized, + T: Into, + { + Ok(Self::from_vectored( + iter_inter + .map(|r| r.map(|eq_inter| Into::::into(eq_inter))) + .collect::, FatalEquipementError>>()?, + )) + } } /// Trait that ensure that two elements of a recipe are combinable, @@ -136,6 +152,9 @@ pub(super) type FilterType = Box>>; #[derive(Clone)] /// A generic Filtering function +// DONE: Not implementing deref and allowing for a super pub allows +// implementation to be a little more flexible, however this might +// also be an oversight pub(crate) struct FilterFunction(pub(super) FilterType); /// This element can be converted to tex @@ -156,7 +175,6 @@ pub trait ToAnalysis { type InnerData; /// Sort the inner data with a given closure - // TODO[4]: Consider changing the signature to (self) -> Self, to match the filter fn inner_sort(&mut self, closure: T) where T: FnMut(&Self::InnerData, &Self::InnerData) -> std::cmp::Ordering; @@ -164,8 +182,6 @@ pub trait ToAnalysis { /// Apply a filter to the inner data /// /// Careful this filter will consume the original data to avoir reallocating - // TODO[6]: Consider implementing base filters as a struct to allow implementation / choice to be polymorphic - // : Maybe more downsides over a dynamic choosing by default fn inner_filter(self, closure: T) -> Self where T: FnMut(&Self::InnerData) -> bool; @@ -176,6 +192,11 @@ pub trait ToAnalysis { /// A generic database+connection, handling all the deserialization of the inner types pub trait RecipeDatabase { + /// The initial Deserialisation struct, SQL will be deserialized into this + type DeserialisationType: DeserializeOwned; + /// The used type that Deserialisation type will be converted into + type InnerType: TryFrom; + /// Create the database from a file fn new(origin: &str) -> Result where @@ -183,11 +204,17 @@ pub trait RecipeDatabase { /// Serialize a vector of objects of the given type in the specified table with an optional filter of the underlying database /// The FROM type is the original data, directly deserialized from the table + // POI: This element is partly responsible for the difficulty simplifying and generalizing deserialisation fn serialize_vec_from_table( &self, table: &str, filter: Option<&str>, - ) -> std::result::Result, FatalEquipementError>; + ) -> Result, crate::error::FatalEquipementError> { + crate::database::get_data(self.get_connection(), table, filter) + } + + /// Get a reference to the underlying database connection + fn get_connection(&self) -> &Connection; /// Initialize an empty database & table fn initialize_empty_table( @@ -197,6 +224,17 @@ pub trait RecipeDatabase { /// Insert a row inside the database, while mostly unused this function is needed to initialize the empty table with an empty row if needed fn insert_row(&self, row: T) -> Result<(), FatalEquipementError>; + + /// Serialize a request into an intermediate T representation, + /// T having all the implementation specifics of the part in details + /// eg. EqShape, EqPart etc.. + fn serialise_into_intermediate( + &self, + table: &str, + filter: Option<&str>, + ) -> Result> + '_, FatalEquipementError> + where + T: From; } /// Trait implemented by any struct aiming to be a public recipe @@ -226,13 +264,26 @@ pub trait Reportable { /// A recipe full stack scenario, from loading database through view table generation /// /// The inner working while somehow abstracted are very tied together and tied to the impl -pub trait Scenario { +pub trait Scenario where for<'a> &'a <<::InitialEquipementListType as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add +// where +// for<'a> &'a <::Recipe as Combinable>::Inner: std::ops::Add, for<'a> &'a <<::InitialEquipementListType as RecipeCollection>::Recipes as Combinable>::Inner: std::ops::Add +{ /// The inner database type type DatabaseType: RecipeDatabase; /// The type of the final recipe list type FinalListType: RefinedList + ToTex + ToCSV + ToAnalysis; /// Inner configuration type Config; + /// The initial equipement type, the database serialisation will be to be converted into this type + // TODO[!]: Try to remove as it is present in Database + type InitialEquipementType; + /// The initial equipement list, about to be converted into a refined list + type InitialEquipementListType: RecipeCollection; //: Into>; + + // /// The inner element that all serialised data will be serialized into after the intermediate step + // type Recipe; + + // for<'a> &'a <::Recipes as Combinable>::Inner: std::ops::Add, /// Create a Scenario from a given config fn new_with_config(config: Self::Config) -> Result @@ -241,4 +292,26 @@ pub trait Scenario { /// Generate the final list type fn generate_refined_recipes(&self) -> Result; + + /// Retrieve a reference to the inner database + fn get_database(&self) -> &Self::DatabaseType; + + /// Retrieve A config + fn get_tablename(&self) -> &str; + + + /// Automatically deserialize into an equipement + fn deserde_into_equipement( + &self, + filter: Option<&str>, + ) -> Result + where + T: From<<::DatabaseType as RecipeDatabase>::InnerType> + + Into<<::InitialEquipementListType as RecipeCollection>::Recipes>, + { + RecipeCollection::from_iter_intermediate::( + self.get_database() + .serialise_into_intermediate::(self.get_tablename(), filter)?, + ) + } } diff --git a/weaponry/src/strategy.rs b/weaponry/src/strategy.rs index 03b8c4f..a19727f 100644 --- a/weaponry/src/strategy.rs +++ b/weaponry/src/strategy.rs @@ -6,75 +6,49 @@ //! or balancing specifically one parameter (balancing materials, balencing finishes etc..) //! These strategies must take into account the level of the fighter (hence his precision) and of the craftsman (hence a difficulty diminution) //! -#![allow(dead_code)] +// #![allow(dead_code)] -/// Generation strategy, how to generate all the data, instead of a full permutation -pub enum EquipementStrategy { - /// Full permutation, generate all possible outcomes - GenerateAll, - /// Generate all the named equipements - GenerateNamed, - /// Do not add finishing touches - NoFinishes, -} - -/// Which material to select -pub enum MaterialsStrategy { - /// Add all materials to the mix - AllMaterials, - /// Add only tier one material - OnlyTier1, - /// Add only easy materials - OnlyEasy, - /// Add only cheap materials - OnlyCheap, - /// Add only one material - OnlyOne, -} - -/// Filter to apply after the generation -pub enum EquipementFilter { - /// Don't filter anything - All, - /// Filter all outliers - Outiliers, - /// Filter in all the named - Named, -} - -// /// Default full generation strategy -// pub fn default_generation() -> impl ParallelIterator { -// Gen:: { elem: Vec::new() } +// /// Generation strategy, how to generate all the data, instead of a full permutation +// pub enum EquipementStrategy { +// /// Full permutation, generate all possible outcomes +// GenerateAll, +// /// Generate all the named equipements +// GenerateNamed, +// /// Do not add finishing touches +// NoFinishes, // } -// /// Default full generation strategy -// pub fn naive_generation(left: Vec, right: Vec) -> Vec -// where -// T: Clone, -// for<'a> &'a T: std::ops::Add<&'a T>, -// { -// left.iter() -// .flat_map(move |e| right.iter().map(move |f| (e + f)).collect::>()) -// .collect() +// /// Which material to select +// pub enum MaterialsStrategy { +// /// Add all materials to the mix +// AllMaterials, +// /// Add only tier one material +// OnlyTier1, +// /// Add only easy materials +// OnlyEasy, +// /// Add only cheap materials +// OnlyCheap, +// /// Add only one material +// OnlyOne, // } -// /// Default full generation strategy -// /// -// /// Take a list of various parts that are combinable and combines them -// pub fn naive_generation( -// list_recipes: Vec>>, -// ) -> Vec { -// list_recipes.iter().reduce(|acc, e| acc.combine_all(e)); -// todo!() +// /// Filter to apply after the generation +// pub enum EquipementFilter { +// /// Don't filter anything +// All, +// /// Filter all outliers +// Outiliers, +// /// Filter in all the named +// Named, // } -#[cfg(test)] -mod test { - // use super::*; +// #[cfg(test)] +// mod test { +// // use super::*; - #[test] - fn test_naive_generator() { - // let t = naive_generation(vec![1, 2, 3], vec![5, 6, 7]); - // assert_eq!(t.len(), 3 * 3); - } -} +// #[test] +// fn test_naive_generator() { +// // let t = naive_generation(vec![1, 2, 3], vec![5, 6, 7]); +// // assert_eq!(t.len(), 3 * 3); +// } +// } diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index b9cfcf5..7d593ff 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -28,7 +28,7 @@ use crate::{ use charming::{Chart, component::LegendSelectedMode}; use core::f64; use serde::Serialize; -use std::cmp::Ordering; +use std::{cmp::Ordering, ops::Deref}; /// The final representation of the equipement inplementing all the fields needed for processing // TODO: Add a public getter for the inner data @@ -36,25 +36,33 @@ pub struct RefinedEquipement { /// The original inner stats /// /// This structs takes ownership of the inner data - // #[serde(skip_deserializing)] pub inner: InnerEquipementStats, /// Advanced stats - // #[serde(flatten)] pub advanced: AdvancedStats, } /// The complete equipement list, refined with all advanced stats pub struct RefinedEquipementList { /// Inner list of Refined Equipements - // TODO: Add a public getter in on of the traits - pub inner: Vec, + inner: Vec, +} + +// DONE: The use of Deref could be a subtle gotcha +impl Deref for RefinedEquipementList { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.inner + } } // Just a checkmark impl RefinedList for RefinedEquipementList {} impl ToTex for RefinedEquipementList { fn to_tex(&self) -> String { + // TODO[!] : Export everything to one tsv + // : This export is only supposed to be the final export of a pseudo recipes book todo!() } } @@ -78,9 +86,7 @@ impl ToAnalysis for RefinedEquipementList { } } - // TODO[3]: Consider wether the naming should be a parameter, - // : Consider wether the closure should be a parameter - // or a config should be given or if the scenario should be fed again the Refined and ... + // DONE: While a custom config would allow some personalisation, there is no reason to beleive a more meaningfull name would be choosen fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> { let mut renderer = charming::HtmlRenderer::new("Ravenous Balancing", 4000, 2000) .theme(charming::theme::Theme::Dark); diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index ef81d9c..cec8a29 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -6,8 +6,6 @@ use probability::distribution::Discrete; use probability::prelude::Binomial; use std::ops::Add; use std::ops::Deref; -use strum::Display; -use strum::EnumIter; use super::equipement_thin_types::Actions; use super::equipement_thin_types::Attacks; @@ -21,7 +19,6 @@ use super::equipement_thin_types::Precision; /// - 2 turns safe attacks (5 dice, 50%p) /// - 1 turn highspeed/range hit (7 dice, 80% precision) /// - 4 turns normal damage (7 dice, 90% precision) -// TODO[!] Implementation pub(super) fn get_damage_with_simulation( value: &InnerEquipementStats, actions: Actions, @@ -106,7 +103,6 @@ pub(super) fn get_damage_with_simulation( /// Sustained damage /// /// Average damage factoring reload, calculated with 9 dice and 90% precision -// TODO[!] Replace avg_damage with this pub(super) fn get_sustained_damage( value: &InnerEquipementStats, actions: Actions, @@ -208,7 +204,7 @@ impl BestDamageScenarios { /// Calculate the best alternative with a set of contraints /// /// Returns None if the scenario cant exist with the current conditions (too few actions for an attack to be launched) - // TODO[!]: Clean this cursed abomination + // DONE: While this abomination is really subpar code, there is no time to clean things that work pub fn from_action_constraints_it( equipement_stats: &InnerEquipementStats, actions_allowed: Actions, @@ -230,10 +226,6 @@ impl BestDamageScenarios { (0, Attacks(0)) }; - // print!( - // "[{actions_allowed}A, {attacks_allowed}a, {}A/a {nb_max_attacks_reload}#, {rem}rem] => ", - // equipement_stats.action_cost - // ); // Loop from the extra attack and go down let mut values: Vec<(i8, i8, f64)> = (1..=(nb_max_attacks_reload + *extra_attack) .clamp(0, *attacks_allowed)) @@ -251,8 +243,8 @@ impl BestDamageScenarios { ) }) .collect(); + values.sort_by(|(_, _, v1), (_, _, v2)| v2.total_cmp(v1)); - // println!("{:?}", values); (!values.is_empty()).then(|| Self { actions_used: Actions((values[0].0 * full_attack_cost).clamp(0, *actions_allowed)), attacks_used: Attacks(values[0].0), @@ -260,124 +252,6 @@ impl BestDamageScenarios { reload_remaining: Actions(values[0].1), }) } - - // /// Calculate the best alternative with a set of contraints - // /// - // /// Returns None if the scenario cant exist with the current conditions (too few actions for an attack to be launched) - // #[deprecated] - // pub fn from_action_constraints( - // equipement_stats: &InnerEquipementStats, - // actions_allowed: Actions, - // attacks_allowed: Attacks, - // dices_allowed: Dices, - // precision: Precision, - // ) -> Option { - // Self::from_action_constraints_recursive( - // equipement_stats, - // actions_allowed, - // attacks_allowed, - // dices_allowed, - // precision, - // 0, - // 0, - // ) - // } - // /// Recursive part of the from_action_constraints call - // /// - // /// This algorithm takes a recursive approact to avoid too much forward complexity - // #[deprecated] - // fn from_action_constraints_recursive( - // equipement_stats: &InnerEquipementStats, - // actions_allowed: Actions, - // attacks_allowed: Attacks, - // dices_allowed: Dices, - // precision: Precision, - // reload_remaining: i8, - // depth: u8, - // ) -> Option { - // // If we can't attack return early - // if equipement_stats.action_cost > *actions_allowed - // || *attacks_allowed == 0 - // || reload_remaining > 0 - // || *dices_allowed < 1 - // { - // // println!( - // // "[{depth}] > Reach the end of recursion {}>{actions_allowed}, {attacks_allowed}a, {dices_allowed}d {reload_remaining}r", - // // value.action_cost - // // ); - // return None; - // } - - // // if depth == 0 { - // // println!( - // // "Starting recursion: {actions_allowed}A {attacks_allowed}atk {dices_allowed}*" - // // ); - // // } - // let atkreload_cost = - // equipement_stats.reload_cost.unwrap_or_default() + equipement_stats.action_cost; - - // // We create our first contender, One attack only - // let one_attack = Self { - // // No matter what we try to reload, even if we overcap the attack was still valid - // actions_used: Actions((atkreload_cost).clamp(0, *actions_allowed)), - // attacks_used: Attacks(1), - // damage_done: binomial_dice_distribution(equipement_stats, precision, dices_allowed), - // // If the reload+attack exceed the actions, we must bookkeep it - // // as a reminder that we have leftover actions to spend next turn - // reload_remaining: Actions( - // ((atkreload_cost) - *actions_allowed + reload_remaining).clamp(0, *actions_allowed), - // ), - // depth, - // }; - // // println!( - // // "[{depth}] > One attack ({}d): {one_attack:?}/{actions_allowed}A", - // // Dices(*dices_allowed) - // // ); - - // // We can only try two attacks if two attack would be valid aka: - // // - We can spend: 2 attacks and (at least) 1 reload (as actions) - // // - : 2 attacks (as attacks) - // if atkreload_cost + equipement_stats.action_cost <= *actions_allowed && *attacks_allowed > 1 - // { - // // Cumbersome because of rounding errors - // if let (Some(a), Some(b)) = ( - // (Self::from_action_constraints_recursive( - // equipement_stats, - // // TODO[9]: THIS APPROACH IS DEEPLY INCORRECT - // // : It does however work for the values we will be using it - // actions_allowed - Actions(atkreload_cost), - // Attacks(attacks_allowed.div_floor(2)), - // Dices(dices_allowed.div_floor(2)), - // precision, - // reload_remaining, - // depth + 1, - // )), - // (Self::from_action_constraints_recursive( - // equipement_stats, - // actions_allowed - Actions(atkreload_cost), - // Attacks(attacks_allowed.div_ceil(2)), - // Dices(dices_allowed.div_ceil(2)), - // precision, - // reload_remaining - equipement_stats.reload_cost.unwrap_or_default(), - // depth + 1, - // )), - // ) { - // let sum_sub_attacks = a + b; - // // println!( - // // "[{depth}] > Two attacks ({} & {}) : {sum_sub_attacks:?}", - // // Dices(dices_allowed.div_floor(2)), - // // Dices(dices_allowed.div_ceil(2)) - // // ); - // // The alternative was better - // if one_attack.damage_done < sum_sub_attacks.damage_done { - // return Some(sum_sub_attacks); - // } - // } - // } - - // // The alternative didn't exist or was worse - // Some(one_attack) - // } } /// Do as many binomials as there are attacks @@ -428,26 +302,6 @@ pub(super) fn binomial_dice_distribution( .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)] -pub enum FixedPrecision { - High, - Medium, - Low, -} - -/// The number of dices rolled for a damage simulation -#[derive(EnumIter, Clone, Copy, Display)] -#[allow(clippy::missing_docs_in_private_items)] -pub enum FixedDiceNumber { - Many, - Average, - Few, -} - #[cfg(test)] mod test { use crate::weaponry_structs::{ @@ -688,6 +542,5 @@ mod test { println!("[{i}] {:?} ~= {res}", val.clone().unwrap_or_default()); assert_close!(val.clone().map_or(0., |v| v.damage_done), res); }); - // todo!() } } diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 4f436ac..5780cbc 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -4,14 +4,33 @@ use serde::{Deserialize, Serialize}; use std::fmt::Display; -use std::ops::Add; +use std::ops::{Add, Deref, DerefMut}; use strum::Display; #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only -// TODO: avoid pub make an impl ? -pub struct SpecialField(pub Vec); +pub struct SpecialField(Vec); + +impl SpecialField { + /// Create a special field from a vector + pub fn new(inner_data: Vec) -> Self { + Self(inner_data) + } +} +impl Deref for SpecialField { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for SpecialField { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} // TODO[6]: This cross target specification existed for combines weapons, // : that do not really need any balancing and only rendering @@ -55,7 +74,22 @@ pub enum DamageMod { #[derive(Clone, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] // TODO: avoid pub make an impl ? -pub struct DamageType(pub Vec); +pub struct DamageType(Vec); + +impl Deref for DamageType { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DamageType { + /// Create a new DamageType from a vector of [DamageMod] + pub fn new(inner_data: Vec) -> Self { + Self(inner_data) + } +} impl Display for DamageType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -77,28 +111,6 @@ impl Add for DamageType { } } -// // TODO[!]: This is only needed as long as we dont have a special category for the target -// // TODO[!]: This part should be handled by a category filter instead, filtering Shape on Shape -// impl PartialEq for EquipementSerializedCategory { -// fn eq(&self, other: &Self) -> bool { -// match (self, other) { -// (&Self::None, _) => false, -// (_, Self::None) => false, -// (&Self::Armors, &Self::Armors) => true, -// (&Self::Armors, _) => false, -// (_, &Self::Armors) => false, -// (&Self::Weapons, _) => true, -// (_, &Self::Weapons) => true, -// (&Self::Staves, &Self::Staves) => true, -// (&Self::Blunt, &Self::Blunt) => true, -// (&Self::Slash, &Self::Slash) => true, -// (&Self::Ranged, &Self::Ranged) => true, -// (&Self::Exotic, &Self::Exotic) => true, -// _ => false, -// } -// } -// } - #[cfg(test)] mod test { // use super::*; @@ -115,65 +127,65 @@ mod test { unimplemented!() } } -// TODO[!]: Implement all the soundness below +// // TODO[!]: Implement all the soundness below -/// The final enum of all categories to be given to the character sheet -/// -/// This enum is only created at the end of the refining process with all the given information -/// Note that some weapons might not be created or might be too niche to be created by the recipes -/// however the full cross implementation should cover all weapons or reconsider the validity of said implementation -#[allow(dead_code, clippy::missing_docs_in_private_items)] -pub enum FinalWeaponCategory { - Hast(HastSpecialties), - Slash(SlashSpecialties), - Blunt(BluntSpecialties), - Collosal(ColossalSpeciaties), - Ranged(RangedSpecialties), - Throw(ThrowSpecialties), -} +// /// The final enum of all categories to be given to the character sheet +// /// +// /// This enum is only created at the end of the refining process with all the given information +// /// Note that some weapons might not be created or might be too niche to be created by the recipes +// /// however the full cross implementation should cover all weapons or reconsider the validity of said implementation +// #[allow(dead_code, clippy::missing_docs_in_private_items)] +// pub enum FinalWeaponCategory { +// Hast(HastSpecialties), +// Slash(SlashSpecialties), +// Blunt(BluntSpecialties), +// Collosal(ColossalSpeciaties), +// Ranged(RangedSpecialties), +// Throw(ThrowSpecialties), +// } -#[allow(dead_code, clippy::missing_docs_in_private_items)] -pub enum HastSpecialties { - Lance, - Staff, -} +// #[allow(dead_code, clippy::missing_docs_in_private_items)] +// pub enum HastSpecialties { +// Lance, +// Staff, +// } -#[allow(dead_code, clippy::missing_docs_in_private_items)] -pub enum SlashSpecialties { - Sword, - #[deprecated] - Dagger, - Axe, - Claws, -} +// #[allow(dead_code, clippy::missing_docs_in_private_items)] +// pub enum SlashSpecialties { +// Sword, +// #[deprecated] +// Dagger, +// Axe, +// Claws, +// } -#[allow(dead_code, clippy::missing_docs_in_private_items)] -pub enum BluntSpecialties { - Hammer, - Improvised, -} +// #[allow(dead_code, clippy::missing_docs_in_private_items)] +// pub enum BluntSpecialties { +// Hammer, +// Improvised, +// } -#[allow(dead_code, clippy::missing_docs_in_private_items)] -pub enum ColossalSpeciaties { - Rhodarak, - Haroth, - Kahml, - Landscapper, -} +// #[allow(dead_code, clippy::missing_docs_in_private_items)] +// pub enum ColossalSpeciaties { +// Rhodarak, +// Haroth, +// Kahml, +// Landscapper, +// } -#[allow(dead_code, clippy::missing_docs_in_private_items)] -pub enum RangedSpecialties { - Bow, - Crossbow, - Cannon, -} +// #[allow(dead_code, clippy::missing_docs_in_private_items)] +// pub enum RangedSpecialties { +// Bow, +// Crossbow, +// Cannon, +// } -#[allow(dead_code, clippy::missing_docs_in_private_items)] -pub enum ThrowSpecialties { - Light, - Lances, - Improvised, -} +// #[allow(dead_code, clippy::missing_docs_in_private_items)] +// pub enum ThrowSpecialties { +// Light, +// Lances, +// Improvised, +// } // TODO[4]: Have a final weapon category tied to the speciality, if any appliable to the character // : Since this is not needed for balencing, this will be left alone for a while @@ -202,7 +214,6 @@ pub enum EquipementSerializedCategory { /// Shield generic category, will be converted into EquipementSection Shields, /// A custom None category, used to forbid a part to be cast upon or from - // TODO: Check the soundness of this implementation None, /// Light size, will be converted to a WeaponBaseSize Light, @@ -228,7 +239,6 @@ pub enum WeaponBaseShape { Armors, Shields, Exotic, - // TODO[!]: Check the soundness of this, as it is not used currently None, } @@ -276,18 +286,3 @@ pub enum WeaponBaseSize { Heavy, SuperHeavy, } - -// // TODO[!]: Add this as a target and nature instead of the old Type -// // : Remember it's the applied into that specify wether they can be applied not the other way around -// /// Specifies the exact nature of the target this element can be applied to -// #[allow(dead_code, clippy::missing_docs_in_private_items, missing_docs)] -// pub enum EquipementFilter { -// /// This element can only be applied to a specific category -// Target(EquipementSection), -// /// This element exists only for recipes or for export to tex, it cannot be auto-applied -// NoTarget, -// /// This element can be applied to any target -// AnyTarget, -// // /// This element can only be applied to a specific base shape -// // TargetShape(WeaponBaseShape) -// } diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index 5aae715..f7ec799 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -30,6 +30,7 @@ impl From for Equipement { } } } + impl From for Equipement { fn from(val: EqMaterial) -> Self { Self { @@ -128,10 +129,9 @@ impl Display for InnerEquipementStats { )], ); table.add_row_if( - |_, _| !self.special.0.is_empty(), + |_, _| !self.special.is_empty(), vec![ self.special - .0 .iter() .intersperse(&",".to_string()) .fold(String::new(), |res, new| format!("{}; {}", res, new)), @@ -171,7 +171,7 @@ impl Reportable for RefinedEquipementList { Some(t) => table.add_row(vec![format!("[REL] {t}")]), None => table.add_row(vec![format!("Refined Equipement List")]), }; - table.add_row(vec![format!("Rows: {}", self.inner.len())]); + table.add_row(vec![format!("Rows: {}", self.len())]); table.to_string() } } @@ -181,11 +181,46 @@ mod test { use crate::{ interfaces::{RecipeCollection, Reportable}, weaponry_structs::{ - Equipement, InitialEquipementList, equipement_advanced_repr::RefinedEquipementList, - equipement_structs::InnerEquipementStats, + Equipement, InitialEquipementList, + equipement_advanced_repr::RefinedEquipementList, + equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}, }, }; + #[allow(dead_code)] + /// A manually implemented hashmap of all values + #[doc(hidden)] + macro_rules! r { + () => { + fastrand::i8(1..20) + }; + } + impl InnerEquipementStats { + /// Testing function to fuzz data + pub fn random_new() -> Self { + Self { + id: vec![r!() as u8], + range: (r!() - 10) as i16, + damage: r!() - 10, + p_damage: r!() - 10, + protection: r!() - 10, + ..Default::default() + } + } + } + impl DatabaseEquipementStats { + /// Testing function to fuzz data + pub fn random_new() -> Self { + Self { + id: r!() as u8, + range: r!() - 19, + damage: r!() - 10, + p_damage: r!() - 10, + protection: r!() - 10, + ..Default::default() + } + } + } #[test] fn test_format() { let equi = Equipement { diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index b4a6c7a..a1c06b0 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -6,7 +6,7 @@ // use super::equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}; -use crate::database::{generate_create_table_query, get_data}; +use crate::database::generate_create_table_query; use crate::error::FatalEquipementError; use crate::interfaces::{FixedRecipe, RecipeDatabase}; use rusqlite::Connection; @@ -24,13 +24,8 @@ pub struct EquipementDatabase { } impl RecipeDatabase for EquipementDatabase { - fn serialize_vec_from_table( - &self, - table: &str, - filter: Option<&str>, - ) -> Result, crate::error::FatalEquipementError> { - get_data(&self.conn, table, filter) - } + type DeserialisationType = DatabaseEquipementStats; + type InnerType = InnerEquipementStats; /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. fn new(filename: &str) -> Result { @@ -54,6 +49,27 @@ impl RecipeDatabase for EquipementDatabase { let _ = row; todo!() } + + fn get_connection(&self) -> &Connection { + &self.conn + } + + fn serialise_into_intermediate( + &self, + table: &str, + filter: Option<&str>, + ) -> Result> + '_, FatalEquipementError> + where + T: From, + { + // Start with Self::DatabaseType + Ok(self + .serialize_vec_from_table::(table, filter)? + .into_iter() + .map(|db_element| { + Self::InnerType::try_from(db_element).map(|inner_eq| T::from(inner_eq)) + })) + } } #[allow(missing_docs)] pub struct EquipementFixedRecipe { @@ -148,7 +164,6 @@ fn get_sub_categories_from_serde(category: &str) -> Result (Some(WeaponBaseShape::Exotic), None), EquipementSerializedCategory::Armors => (Some(WeaponBaseShape::Armors), None), EquipementSerializedCategory::Shields => (Some(WeaponBaseShape::Shields), None), - // EquipementSerializedCategory::Weapons => todo!(), EquipementSerializedCategory::None => (Some(WeaponBaseShape::None), None), EquipementSerializedCategory::Light => (None, Some(WeaponBaseSize::Light)), EquipementSerializedCategory::Medium => (None, Some(WeaponBaseSize::Medium)), diff --git a/weaponry/src/weaponry_structs/equipement_impl_io.rs b/weaponry/src/weaponry_structs/equipement_impl_io.rs index e7a5215..9c12248 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_io.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_io.rs @@ -9,7 +9,7 @@ use std::path::Path; impl ToCSV for RefinedEquipementList { fn write_csv(&self, path: &Path) -> csv::Result<()> { let mut wtr = csv::Writer::from_path(path)?; // wtr.serialize - for record in self.inner.iter() { + for record in self.iter() { wtr.serialize(record)?; } Ok(()) diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index 561f38a..0a6799b 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -34,6 +34,7 @@ impl Combinable for Equipement { impl RecipeCollection for InitialEquipementList { type Recipes = Equipement; + // Should likely be internal fn from_vectored(list: Vec) -> Self { Self { inner: list } } @@ -95,8 +96,8 @@ mod test { range: 3, agility_bonus: 4., category_base: Some(WeaponBaseShape::Staves), - special: SpecialField(vec!["zero".into()]), - damage_type: Some(DamageType(vec![DamageMod::Secondary( + special: SpecialField::new(vec!["zero".into()]), + damage_type: Some(DamageType::new(vec![DamageMod::Secondary( PhysicalDamageType::Slash, )])), ..Default::default() @@ -105,10 +106,10 @@ mod test { integrity: 3, agility_bonus: 5., damage: 10, - damage_type: Some(DamageType(vec![DamageMod::Primary( + damage_type: Some(DamageType::new(vec![DamageMod::Primary( PhysicalDamageType::Blunt, )])), - special: SpecialField(vec!["one".into(), "two".into()]), + special: SpecialField::new(vec!["one".into(), "two".into()]), ..Default::default() }; assert_eq!( @@ -120,8 +121,8 @@ mod test { damage: 10, range: 3, category_base: Some(WeaponBaseShape::Staves), - special: SpecialField(vec!["zero".into(), "one".into(), "two".into()]), - damage_type: Some(DamageType(vec![ + special: SpecialField::new(vec!["zero".into(), "one".into(), "two".into()]), + damage_type: Some(DamageType::new(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), ])), @@ -130,14 +131,14 @@ mod test { ); assert_eq!( &InnerEquipementStats { - damage_type: Some(DamageType(vec![ + damage_type: Some(DamageType::new(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), ])), ..Default::default() } + &InnerEquipementStats::default(), InnerEquipementStats { - damage_type: Some(DamageType(vec![ + damage_type: Some(DamageType::new(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), ])), @@ -147,14 +148,14 @@ mod test { assert_eq!( &InnerEquipementStats::default() + &InnerEquipementStats { - damage_type: Some(DamageType(vec![ + damage_type: Some(DamageType::new(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), ])), ..Default::default() }, InnerEquipementStats { - damage_type: Some(DamageType(vec![ + damage_type: Some(DamageType::new(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), DamageMod::Primary(PhysicalDamageType::Blunt,), ])), diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index 008d151..ae883ac 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -4,7 +4,7 @@ //! use super::equipement_structs::InnerEquipementStats; -use crate::weaponry_structs::SpecialField; +use crate::weaponry_structs::{SpecialField, WeaponBaseShape}; /// Add a new vector to a clone of a inner field macro_rules! add_to_vec { @@ -43,7 +43,6 @@ impl std::ops::Add for &InnerEquipementStats { fn add(self, rhs: Self) -> Self::Output { InnerEquipementStats { - // TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless id: add_to_vec!(self.id, rhs.id), name: add_to_vec!(self.name, rhs.name), rarity: self.rarity + rhs.rarity, @@ -55,7 +54,15 @@ impl std::ops::Add for &InnerEquipementStats { precision: self.precision + rhs.precision, rmax: self.rmax + rhs.rmax, armor_break: self.armor_break + rhs.armor_break, - armor_pierce: self.armor_pierce + rhs.armor_pierce, + armor_pierce: { + if self.armor_pierce > 0 + || matches!(self.category_base, Some(WeaponBaseShape::Ranged)) + { + self.armor_pierce + rhs.armor_pierce + } else { + 0 + } + }, antimaterial: self.antimaterial + rhs.antimaterial, damage_type: add_two_options!(self.damage_type, rhs.damage_type), protection: self.protection + rhs.protection, @@ -66,8 +73,6 @@ impl std::ops::Add for &InnerEquipementStats { parry: self.parry + rhs.parry, speed: self.speed + rhs.speed, stealth: self.stealth + rhs.stealth, - // macro_category: self.macro_category.clone().or(rhs.macro_category.clone()), // Can be further optimized - // target: self.target.clone().or(rhs.target.clone()), // Can be further optimized special: self.special.clone() + rhs.special.clone(), // Can be further optimized action_cost: self.action_cost + rhs.action_cost, reload_cost: self.reload_cost.or(rhs.reload_cost), @@ -85,8 +90,7 @@ impl std::ops::Add for SpecialField { fn add(self, rhs: Self) -> Self::Output { let mut c = self.clone(); - // TODO: Overcopy, kinda meaningless optimisation tho - c.0.append(&mut rhs.clone().0); + c.append(&mut rhs.clone()); c } } diff --git a/weaponry/src/weaponry_structs/equipement_scenario.rs b/weaponry/src/weaponry_structs/equipement_scenario.rs index 7098313..c767e34 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -11,12 +11,9 @@ use crate::{ error::FatalEquipementError, interfaces::{RecipeCollection, RecipeDatabase, Scenario}, weaponry_structs::{ - Equipement, InitialEquipementList, RefinedEquipementList, + InitialEquipementList, RefinedEquipementList, equipement_impl_database::EquipementDatabase, - equipement_structs::{ - DatabaseEquipementStats, EqFinishing, EqMaterial, EqNature, EqShape, - InnerEquipementStats, - }, + equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats}, }, }; @@ -40,59 +37,52 @@ pub struct ConfigEquipementScenario { /// A simple cross recipe scenario #[allow(clippy::missing_docs_in_private_items)] pub struct CrossRecipeScenario { - // TODO: Should obv be inside the config + database: EquipementDatabase, + config: ConfigEquipementScenario, +} + +/// All recipes +#[allow(clippy::missing_docs_in_private_items, dead_code)] +pub struct RecipesScenario { + database: EquipementDatabase, + config: ConfigEquipementScenario, +} + +/// A scenario exporting all individual elements +#[allow(clippy::missing_docs_in_private_items, dead_code)] +pub struct IndividualElementsScenario { database: EquipementDatabase, config: ConfigEquipementScenario, } impl CrossRecipeScenario { - /// Automatically deserialize into an equipement - // TODO: Add to trait - // TODO: Add an optionnal initial filter ? - fn deserde_into_equipement( - &self, - name: &str, - ) -> Result - 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.config.table_name, - Some(&format!("META_CATEGORY LIKE '{}'", name)), - )? - .into_iter() - .map(|v| { - InnerEquipementStats::try_from(v) - .map(|w| T::from(w)) - .map(|v| v.into()) - }) - .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")?); + operations + .push(self.deserde_into_equipement::(Some("META_CATEGORY LIKE 'Shape'"))?); } if let Some(qt) = self.config.materials { for _ in 0..qt { - operations.push(self.deserde_into_equipement::("Materials")?); + operations.push(self.deserde_into_equipement::(Some( + "META_CATEGORY LIKE 'Materials'", + ))?); } } if self.config.nature.is_some() { - operations.push(self.deserde_into_equipement::("Nature")?); + operations.push( + self.deserde_into_equipement::(Some("META_CATEGORY LIKE 'Nature'"))?, + ); } if self.config.finishing.is_some() { - operations.push(self.deserde_into_equipement::("Finishing")?); + operations.push( + self.deserde_into_equipement::(Some( + "META_CATEGORY LIKE 'Finishing'", + ))?, + ); } if operations.is_empty() { return Err(FatalEquipementError::CLISelection( @@ -107,6 +97,9 @@ impl Scenario for CrossRecipeScenario { type DatabaseType = EquipementDatabase; type FinalListType = RefinedEquipementList; type Config = ConfigEquipementScenario; + type InitialEquipementType = InnerEquipementStats; + type InitialEquipementListType = InitialEquipementList; + // type Recipe = Equipement; fn new_with_config(config: Self::Config) -> Result where @@ -128,4 +121,16 @@ impl Scenario for CrossRecipeScenario { Ok(refined_list.into()) } + + // type InitialElementList; + + // type InitialDatabaseStruct; + + fn get_tablename(&self) -> &str { + &self.config.table_name + } + + fn get_database(&self) -> &Self::DatabaseType { + &self.database + } } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 5e70554..c7a5a86 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -39,7 +39,7 @@ impl Default for Equipement { fn default() -> Self { Self { filter_function: FilterFunction::new(filter_id_unique()), - stats: InnerEquipementStats::random_new(), + stats: InnerEquipementStats::default(), } } } @@ -61,14 +61,14 @@ 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, _) => true, // panic!("The EqNature about to be added cannot be 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"), } } } impl FilterFunction { - /// Generate a new filter - // TODO: This static lifetime is basically telling us that an owned value is needed + /// Generate and save a new filter, + /// the use of a static reference allows for reuse of a generic filter pub fn new(filter: &'static FilterFunctionType) -> Self { Self(Box::new(Rc::new(filter))) } @@ -119,9 +119,9 @@ pub struct InnerEquipementStats { } // TODO: This implementation of default is painfull -// TODO: Have either an auto-macro implementation or a manual one -// TODO: This implementation is Quasi-redondant -// TODO: Have a way to limit code duplication +// : Have either an auto-macro implementation or a manual one +// : This implementation is Quasi-redondant +// : Have a way to limit code duplication #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, FieldsAsSlice, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] @@ -216,43 +216,6 @@ impl Default for DatabaseEquipementStats { } } -#[allow(dead_code)] -/// A manually implemented hashmap of all values -#[doc(hidden)] -macro_rules! r { - () => { - fastrand::i8(1..20) - }; -} -// TODO: Make this a test requirement or hide it behind a profile -impl InnerEquipementStats { - /// Testing function to fuzz data - pub fn random_new() -> Self { - Self { - id: vec![r!() as u8], - range: (r!() - 10) as i16, - damage: r!() - 10, - p_damage: r!() - 10, - protection: r!() - 10, - ..Default::default() - } - } -} -// TODO: Make this a test requirement or hide it behind a profile -impl DatabaseEquipementStats { - /// Testing function to fuzz data - pub fn random_new() -> Self { - Self { - id: r!() as u8, - range: r!() - 19, - damage: r!() - 10, - p_damage: r!() - 10, - protection: r!() - 10, - ..Default::default() - } - } -} - /// Shape of the equipement, first mandatory part of an equipement #[derive(Default)] pub struct EqShape { @@ -310,7 +273,8 @@ impl From for EqFinishing { #[cfg(test)] mod test { use super::{ - EqFinishing, EqMaterial, EqShape, Equipement, InitialEquipementList, InnerEquipementStats, + EqFinishing, EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList, + InnerEquipementStats, }; use crate::interfaces::RecipeCollection; @@ -335,9 +299,8 @@ mod test { #[test] fn test_creating_all_equipements() { let shape = vec![EqShape::default().into(), EqShape::default().into()]; - // Commented because of the generic nature and the from not a tryfrom - // TODO: Reinstate this part - // let nature = 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()]; diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index c2280af..d03f50d 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -44,3 +44,8 @@ pub use equipement_fields::{ }; // Likely ? Final Re-Exports pub use equipement_scenario::CrossRecipeScenario; + +// // TODO[!]: Add a sensible prelude +// mod prelude{ + +// }