From 6d080230ee562be8b6b0931ba947ba07f8b4aef8 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 4 Mar 2025 21:21:19 +0100 Subject: [PATCH] Clears a lot of todo --- weaponry/Cargo.toml | 2 +- weaponry/src/interfaces.rs | 18 +-- weaponry/src/strategy.rs | 102 +++++------- .../equipement_advanced_repr.rs | 20 ++- .../equipement_advanced_tools.rs | 149 +----------------- .../src/weaponry_structs/equipement_fields.rs | 79 +++++----- .../equipement_impl_basics.rs | 44 +++++- .../weaponry_structs/equipement_impl_io.rs | 2 +- .../weaponry_structs/equipement_impl_logic.rs | 20 +-- .../weaponry_structs/equipement_impl_math.rs | 6 +- .../weaponry_structs/equipement_scenario.rs | 1 - .../weaponry_structs/equipement_structs.rs | 57 ++----- 12 files changed, 154 insertions(+), 346 deletions(-) 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/src/interfaces.rs b/weaponry/src/interfaces.rs index 98ebe99..99f5319 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -152,6 +152,7 @@ pub(super) type FilterType = Box>>; #[derive(Clone)] /// A generic Filtering function +// TODO: Deref pub(crate) struct FilterFunction(pub(super) FilterType); /// This element can be converted to tex @@ -172,7 +173,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; @@ -180,8 +180,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; @@ -204,7 +202,7 @@ 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 - // TODO[:] : This element is partly responsible for the difficulty simplifying and generalizing deserialisation + // POI: This element is partly responsible for the difficulty simplifying and generalizing deserialisation fn serialize_vec_from_table( &self, table: &str, @@ -299,20 +297,8 @@ pub trait Scenario where for<'a> &'a <<::InitialEquipementList /// Retrieve A config fn get_tablename(&self) -> &str; - // /// Automatically deserialize into an equipement - // // TODO: Add to trait - // // TODO: Add an optionnal initial filter ? - // fn deserde_into_equipement( - // &self, - // filter: Option<&str>, - // ) -> Result - // where - // T: From - // + Into<<::InitialEquipementListType as RecipeCollection>::Recipes>; /// Automatically deserialize into an equipement - // TODO: Add to trait - // TODO: Add an optionnal initial filter ? fn deserde_into_equipement( &self, filter: Option<&str>, 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 42253ea..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,19 +36,25 @@ 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 @@ -80,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 b8b6333..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; @@ -105,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, @@ -207,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, @@ -229,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)) @@ -250,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), @@ -259,123 +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 @@ -426,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::{ @@ -686,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..ace1a90 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::*; @@ -276,18 +288,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..aacec5e 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -128,10 +128,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 +170,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 +180,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_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 35aa891..0a6799b 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -96,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() @@ -106,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!( @@ -121,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,), ])), @@ -131,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,), ])), @@ -148,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 ff56227..ae883ac 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -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, @@ -74,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), @@ -93,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 4a99840..c767e34 100644 --- a/weaponry/src/weaponry_structs/equipement_scenario.rs +++ b/weaponry/src/weaponry_structs/equipement_scenario.rs @@ -57,7 +57,6 @@ pub struct IndividualElementsScenario { impl CrossRecipeScenario { /// 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> { diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index affad8a..8ad1f54 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -56,7 +56,7 @@ impl Default for Equipement { fn default() -> Self { Self { filter_function: FilterFunction::new(filter_id_unique()), - stats: InnerEquipementStats::random_new(), + stats: InnerEquipementStats::default(), } } } @@ -84,8 +84,8 @@ pub(crate) fn filter_id_unique_and_right_category() } } 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))) } @@ -136,9 +136,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))] @@ -233,43 +233,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 { @@ -327,7 +290,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; @@ -352,9 +316,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()];