From e99d723e5d6203896e33c185baa1ff5b8e9392e7 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 25 Feb 2025 18:27:00 +0100 Subject: [PATCH 1/4] Not fearless refactoring of Categories --- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/usage_scenario.rs | 6 +- .../src/weaponry_structs/equipement_fields.rs | 155 +++++++++--------- .../equipement_impl_basics.rs | 7 +- .../equipement_impl_database.rs | 37 ++++- .../weaponry_structs/equipement_impl_logic.rs | 6 +- .../weaponry_structs/equipement_impl_math.rs | 69 +++----- .../weaponry_structs/equipement_structs.rs | 44 ++--- weaponry/src/weaponry_structs/mod.rs | 3 +- 9 files changed, 171 insertions(+), 156 deletions(-) diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index 2dd403301c8450cdaeccac0c60f736c15d055347..e1924d36cf44cba642d2cc9b13c86e237650d0ec 100644 GIT binary patch delta 466 zcmZp8z}WDBae_2s-$WT_#=eaS3+-bW7#Oq}7BcWJ<2U0w%9qV2#Jin0ftQ7enP(SI zDUTlaYwiWyVcfi2OPMw?C36{a?&U1uZ3&w#>l@Y{R!x@sEE8E2 znNKq3Gp=QfW@Kep$jmaa(U~!6vaX;cld9}w4?#V%;L?KBB9GL>vPvZ-$D-W)qGF}! z*u2u5oc|%3@(hyd92`KyIT(SMLy(hGP?Up_kx^Q9@?t?%L#(<2G=RD^LCT>(kb{F? z6vUR5o%~f$(a<+FC9^aa&9V@6pe|jAU0{8JjEq3LI5{|hc1?6rwNmoQOwTAm(-p@l z&mb-hwFg9*gLMHJva*64Kud!&5(_4u)6o_zM$_p#d84G%=A1644S$elP7qJ zOtx{B-2B^#iJd)7P@X|vo^$d>amCH~Ugk`jS$zKrF)^u3W==3-)Yxp6@Q#rU7)>li XE|VQ|r6xNh=}dl^B)qvfsg@T2_aSp= delta 313 zcmZp8z}WDBae_2s^F$eE#^#L)3+;J1|1xMZN74%Id=Mgr$+iocSelC9@*aai&rx4aRGX)rj+9QiAqo2>!8b>SDKTf6ep`V=}-P9qrX|z_l^(~1H)wI1S3Y3&1MPj7@5jkCOhUzGRjVNNz&m^3QEjN NPfbzUT$0qo3jnQ3S 0.)) .inner_filter(|e| { - e.inner.macro_category.as_ref().is_some_and(|v| { - !matches!(v, weaponry::weaponry_structs::WeaponMacroCategory::Shields) - && !matches!(v, weaponry::weaponry_structs::WeaponMacroCategory::Armor) + e.inner.category_base.as_ref().is_some_and(|v| { + !matches!(v, weaponry::weaponry_structs::WeaponBaseShape::Shields) + && !matches!(v, weaponry::weaponry_structs::WeaponBaseShape::Armors) }) }); diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 1f6be28..84679d9 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -29,8 +29,8 @@ pub enum NatureTarget { /// Enum of all different physical weapon damage types #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] -// #[cfg_attr(test, derive(PartialEq))] +#[derive(Clone, Debug, Deserialize, Serialize)] +#[cfg_attr(test, derive(PartialEq))] pub enum PhysicalDamageType { Blunt, Slash, @@ -77,53 +77,27 @@ impl Add for DamageType { } } -// TODO: Convert into this category at the end, depending on all important factors -/// List all the final weapon categories, this enum should be infered from and if they were defined -#[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, PartialEq, Display, Deserialize, Serialize, strum::EnumString)] -// #[cfg_attr(test, derive(PartialEq))] -pub enum WeaponCategory { - Exotic, - // HeavyExotic ? - Dagger, // Light sword ? Kill it tbh - Claws, - Blade, - Haroth, - Axe, - Kahml, - Hammer, - Rhodarak, - Staff, - Lance, - Landscapper, - Bow, - Crossbow, - Cannon, - // Armor, - // Shield, -} - -// 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 WeaponMacroCategory { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (&Self::None, _) => false, - (_, Self::None) => false, - (&Self::Armor, &Self::Armor) => true, - (&Self::Armor, _) => false, - (_, &Self::Armor) => 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, - } - } -} +// // 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 { @@ -217,20 +191,27 @@ pub enum ThrowSpecialties { // TODO[!]: This enum should only include Weapons, Shields, Armors and no #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] -pub enum WeaponMacroCategory { +pub enum EquipementSerializedCategory { Staves, Blunt, Slash, Ranged, - Armor, - Shields, Exotic, - /// A custom weapon category, only used by the target - // TODO: Get rid of this category and make a custom category for target - Weapons, - /// A custom none category, used to forbid a part to be cast upon of from + /// Armor generic category, will be converted into EquipementSection + Armors, + /// 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, + /// Medium size, will be converted to a WeaponBaseSize + Medium, + /// Heavy size, will be converted to a WeaponBaseSize + Heavy, + /// SuperHeavy size, will be converted to a WeaponBaseSize + SuperHeavy, } // TODO[!] : This is the corrected real initial shape @@ -238,49 +219,73 @@ pub enum WeaponMacroCategory { /// The Base Shape of the weapon, used to infer the final category of the weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] +#[cfg_attr(test, derive(PartialEq))] pub enum WeaponBaseShape { Staves, Blunt, Slash, Ranged, - Armor, + Armors, Shields, Exotic, - // TODO[!]: Check the soundness of this + // TODO[!]: Check the soundness of this, as it is not used currently None, } // TODO[!]: While maybe not directly filling a field these categories should be inferred by the BaseShape for comparison // [!]: However using a new column for this Section will greatly help in the Serde soundness and avoidance on over-reliance of implicit conversions /// Specifies the exact nature of the weapon, used for generic filter mainly +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[allow(dead_code, clippy::missing_docs_in_private_items, missing_docs)] -pub enum EquipementSection { - Weapon, - Armor, - Shield, +pub enum EquipementTargets { + Weapons, + Armors, + Shields, + Ranged, } -// 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) + +impl EquipementTargets { + /// Assert wether a target can be applied to an original shape + pub fn can_apply_onto(&self, lsh: &WeaponBaseShape) -> bool { + match (self, lsh) { + (EquipementTargets::Weapons, WeaponBaseShape::Staves) => true, + (EquipementTargets::Weapons, WeaponBaseShape::Blunt) => true, + (EquipementTargets::Weapons, WeaponBaseShape::Slash) => true, + (EquipementTargets::Weapons, WeaponBaseShape::Ranged) => true, + (EquipementTargets::Weapons, WeaponBaseShape::Exotic) => true, + // You can apply weapon modifiers to shields, not the best behaviour but well + (EquipementTargets::Weapons, WeaponBaseShape::Shields) => true, + (EquipementTargets::Armors, WeaponBaseShape::Armors) => true, + (EquipementTargets::Shields, WeaponBaseShape::Shields) => true, + (EquipementTargets::Ranged, WeaponBaseShape::Ranged) => true, + _ => false, + } + } } // TODO[!] : This part is initialized by the natures subtable and might be better of being a new column in the database /// The Base Size of the weapon, used to infer the final category of the weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] +#[cfg_attr(test, derive(PartialEq))] pub enum WeaponBaseSize { Light, Medium, 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 4c069e9..5aae715 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -76,12 +76,15 @@ impl Display for InnerEquipementStats { self.name.join(" & ") )]); table.add_row(vec![format!( - "Rarity: {}, Cost {}, Difficulty: {}, Tier: {} [{}]", + "Rarity: {}, Cost {}, Difficulty: {}, Tier: {} [{}+{}]", self.rarity, self.cost, self.difficulty, self.tier, - self.macro_category + self.category_base + .clone() + .map_or_else(|| "ø".to_string(), |v| v.to_string()), + self.category_size .clone() .map_or_else(|| "ø".to_string(), |v| v.to_string()) )]); diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 7f4ef60..b4a6c7a 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -12,6 +12,8 @@ use crate::interfaces::{FixedRecipe, RecipeDatabase}; use rusqlite::Connection; use serde::de::DeserializeOwned; +use super::EquipementSerializedCategory; +use super::equipement_fields::{WeaponBaseShape, WeaponBaseSize}; use super::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}; /// Struct for database connection. @@ -92,6 +94,8 @@ impl TryFrom for InnerEquipementStats { type Error = FatalEquipementError; fn try_from(value: DatabaseEquipementStats) -> Result { + let (category_base, category_size): SubCategories = + get_sub_categories_from_serde(&value.category)?; Ok(Self { id: vec![value.id], // Special case where manual is better than serde name: vec![value.name], @@ -116,13 +120,42 @@ impl TryFrom for InnerEquipementStats { parry: value.parry, speed: value.speed, stealth: value.stealth, - macro_category: from_serde!(&value.category)?, - target: from_serde!(&value.target)?, + // macro_category: from_serde!(&value.category)?, + // target: from_serde!(&value.target)?, special: from_serde!(&value.special)?, action_cost: value.action_cost, reload_cost: from_serde!(&value.reload_cost)?, range: value.range as i16, agility_bonus: value.agility_bonus, + category_base, + category_size, + target_category: from_serde!(value.target)?, }) } } + +/// A type englobing the three subcategores +type SubCategories = (Option, Option); + +/// Infer all subcategories from a deserialized DatabaseCategory +fn get_sub_categories_from_serde(category: &str) -> Result { + Ok(if let Some(category) = from_serde!(category)? { + match category { + EquipementSerializedCategory::Staves => (Some(WeaponBaseShape::Staves), None), + EquipementSerializedCategory::Blunt => (Some(WeaponBaseShape::Blunt), None), + EquipementSerializedCategory::Slash => (Some(WeaponBaseShape::Slash), None), + EquipementSerializedCategory::Ranged => (Some(WeaponBaseShape::Ranged), None), + EquipementSerializedCategory::Exotic => (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)), + EquipementSerializedCategory::Heavy => (None, Some(WeaponBaseSize::Heavy)), + EquipementSerializedCategory::SuperHeavy => (None, Some(WeaponBaseSize::SuperHeavy)), + } + } else { + (None, None) + }) +} diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index c3da801..561f38a 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -53,7 +53,7 @@ mod test { interfaces::RecipeCollection, weaponry_structs::{ DamageMod, DamageType, Equipement, InitialEquipementList, SpecialField, - equipement_fields::{PhysicalDamageType, WeaponMacroCategory}, + equipement_fields::{PhysicalDamageType, WeaponBaseShape}, equipement_structs::InnerEquipementStats, }, }; @@ -94,7 +94,7 @@ mod test { integrity: 2, range: 3, agility_bonus: 4., - macro_category: Some(WeaponMacroCategory::Staves), + category_base: Some(WeaponBaseShape::Staves), special: SpecialField(vec!["zero".into()]), damage_type: Some(DamageType(vec![DamageMod::Secondary( PhysicalDamageType::Slash, @@ -119,7 +119,7 @@ mod test { agility_bonus: 9., damage: 10, range: 3, - macro_category: Some(WeaponMacroCategory::Staves), + category_base: Some(WeaponBaseShape::Staves), special: SpecialField(vec!["zero".into(), "one".into(), "two".into()]), damage_type: Some(DamageType(vec![ DamageMod::Secondary(PhysicalDamageType::Slash,), diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index ab587fb..008d151 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -18,15 +18,26 @@ macro_rules! add_to_vec { /// Adds either of the vectors or merge them macro_rules! add_two_options { ($self: expr, $rhs: expr) => {{ - match ($self.clone(), $rhs.clone()) { + match ($self.as_ref(), $rhs.as_ref()) { (None, None) => None, - (None, Some(a)) => Some(a), - (Some(a), None) => Some(a), - (Some(a), Some(b)) => Some(a + b), + (None, Some(a)) => Some(a.clone()), + (Some(a), None) => Some(a.clone()), + (Some(a), Some(b)) => Some(a.clone() + b.clone()), } }}; } +/// Clones the first option that has some data +macro_rules! first_correct_option { + ($self:expr, $rhs:expr) => { + match ($self.as_ref(), $rhs.as_ref()) { + (Some(a), _) => Some(a.clone()), + (_, Some(b)) => Some(b.clone()), + _ => None, + } + }; +} + impl std::ops::Add for &InnerEquipementStats { type Output = InnerEquipementStats; @@ -55,13 +66,16 @@ 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 + // 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), range: self.range + rhs.range, agility_bonus: self.agility_bonus + rhs.agility_bonus, + category_base: first_correct_option!(self.category_base, rhs.category_base), + category_size: first_correct_option!(self.category_size, rhs.category_size), + target_category: first_correct_option!(self.target_category, rhs.target_category), } } } @@ -76,46 +90,3 @@ impl std::ops::Add for SpecialField { c } } - -// impl std::ops::AddAssign for SpecialCategory { -// fn add_assign(&mut self, rhs: Self) { -// todo!() -// } -// } - -// impl std::ops::Add for OptionnalReloadType { -// type Output = OptionnalReloadType; - -// fn add(self, rhs: Self) -> Self::Output { -// todo!() -// } -// } -// impl std::ops::AddAssign for OptionnalReloadType { -// fn add_assign(&mut self, rhs: Self) { -// todo!() -// } -// } -// impl std::ops::Add for OptionnalWeaponCategory { -// type Output = OptionnalWeaponCategory; - -// fn add(self, rhs: Self) -> Self::Output { -// todo!() -// } -// } -// impl std::ops::AddAssign for OptionnalWeaponCategory { -// fn add_assign(&mut self, rhs: Self) { -// todo!() -// } -// } -// impl std::ops::Add for OptionnalDamageType { -// type Output = OptionnalDamageType; - -// fn add(self, rhs: Self) -> Self::Output { -// todo!() -// } -// } -// impl std::ops::AddAssign for OptionnalDamageType { -// fn add_assign(&mut self, rhs: Self) { -// todo!() -// } -// } diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index c26d605..5e70554 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -8,7 +8,12 @@ use crate::interfaces::{FilterFunction, FilterFunctionType}; use more_fields::FieldsAsSlice; use serde::{Deserialize, Serialize}; -use super::{DamageType, SpecialField, WeaponCategory, equipement_fields::WeaponMacroCategory}; +use super::{ + DamageType, SpecialField, + equipement_fields::{ + EquipementSerializedCategory, EquipementTargets, WeaponBaseShape, WeaponBaseSize, + }, +}; /// The final equipement list /// @@ -46,29 +51,18 @@ pub(crate) fn filter_id_unique() } /// Create a new filter function mandating the object be of the right category +// TODO[5]: Testing this method should be a priority for refactoring pub(crate) fn filter_id_unique_and_right_category() -> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool { &|sel, lhs| { - // println!( - // "Trying to match {:?} with {:?}. {:?} {:?}", - // sel.name, lhs.name, sel.target, lhs.macro_category - // ); lhs.id.iter().all(|a| *a != sel.id[0]) - & match (&sel.target, &lhs.macro_category) { + & match (&sel.target_category, &lhs.category_base) { // There is a specific target and the part about to be added has a category - (Some(a), Some(b)) => { - // println!("{} {}", a, b); - a == b - } - // There is no target and the part about to be added is generic + (Some(a), Some(b)) => a.can_apply_onto(b), // TODO: Unsound to have a generic nature, this should be caught at serialisation - // TODO: Testing a generic anyway + // 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"), - // There is a specific target but the part about to be added is generic - // TODO: Impossible (Some(_), None) => panic!("The part about to be added unto cannot be generic"), - // // There is restriction on the target and the recipient - // (None, Some(_)) => true, } } } @@ -106,9 +100,17 @@ pub struct InnerEquipementStats { pub(super) parry: i8, pub(super) speed: i8, pub(super) stealth: i8, - /// The initial macro category, in turn combined with other stats it will describe a final category - pub macro_category: Option, // TODO : This initial macro category fill as a final stat feed the final category - pub(super) target: Option, // TODO: This might be incorrect, to check + /// The category as [WeaponBaseShape] representing what kind of equipement is used + /// + /// The categories are: Staves, Blunt, Slash, Ranged, Armors, Shields, Exotic, None, + pub category_base: Option, + /// The category size as [WeaponBaseSize] + /// + /// Categories are : (Light, Medium, Heavy and SuperHeavy) + pub category_size: Option, + /// The section of an equipement (Weapon, Shield, Armor) + /// The Section the target applies to + pub target_category: Option, pub(super) special: SpecialField, pub(super) action_cost: i8, pub(super) reload_cost: Option, // Shouldn't it be Option ? @@ -184,8 +186,8 @@ impl Default for DatabaseEquipementStats { meta_category: "EqShape".to_string(), name: String::new(), damage_type: serde_json::to_string(&None::).unwrap(), - category: serde_json::to_string(&None::).unwrap(), - target: serde_json::to_string(&None::).unwrap(), + category: serde_json::to_string(&None::).unwrap(), + target: serde_json::to_string(&None::).unwrap(), special: serde_json::to_string(&SpecialField::default()).unwrap(), reload_cost: serde_json::to_string(&None::).unwrap(), rarity: 0, diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 66d8417..c2280af 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -39,7 +39,8 @@ pub use crate::weaponry_structs::equipement_advanced_repr::RefinedEquipementList pub use equipement_advanced_repr::RefinedEquipement; pub use equipement_fields::PhysicalDamageType; pub use equipement_fields::{ - DamageMod, DamageType, NatureTarget, SpecialField, WeaponCategory, WeaponMacroCategory, + DamageMod, DamageType, EquipementSerializedCategory, NatureTarget, SpecialField, + WeaponBaseShape, }; // Likely ? Final Re-Exports pub use equipement_scenario::CrossRecipeScenario; -- 2.45.1 From 32ff0ef11550b7fdad51537ad421cfb3606617ac Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 25 Feb 2025 23:23:31 +0100 Subject: [PATCH 2/4] Adds a better sort (still miles from real custom cli) --- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/usage_scenario.rs | 2 +- .../equipement_advanced_repr.rs | 52 ++++++++++++++---- .../src/weaponry_structs/equipement_fields.rs | 6 +- 4 files changed, 47 insertions(+), 13 deletions(-) diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index e1924d36cf44cba642d2cc9b13c86e237650d0ec..6b5528b07512de047d84d29509c2d1205d2ff241 100644 GIT binary patch delta 1023 zcmZva%TE(Q9LGB|EuDcvZM0x1uw{{m2~`#ZN@4`sDoB7DNfgpFWNimpQ`%2dLyl+goiR z+qUKMgRgHAFGlA#kn^Rpzv+F`Vw1J;Rb#~Q%TaRNbfAWJ4Qma(^*`#j>oxYBl~^0y zrHl4M`(t}|-G{n)+oA25t;hP!x`v*ku;tLQVO7XSk|pi<6ONU3&3SvW~Qex33oMU=Ql z_(GBWow55!WJ7QFpWg7;L_D}7CR%&;KTi!~L4wVQiPm86EYbR;JQWVk8hQ2j8jZ=P zF{)Tv6bg$mnJ67b$mx_@#qFYQO6QV#jt8^Fcsj+6yop6$usLKM3Sd*6OQv`_kyjK#3^%o9flZ9Q6dEC&=E0c1Pk z%S;O=?9E@DqQ$ju@yo&AJVjdsRq-rmhk*vAKwFS62;vNs$&JkSxUES&Umygs@=sx{ wPpec_&{uhFQ%nKm&ca~X2($%rddjnK5ayuAt=RS|<<2$rF6U7&#^{_tBaBMu(TXSV_sTC^x^T zSSfmPx92kEOkMfO6H+B7i#YjDKI*)QF>kV?uoR>Gr>R6P_%rZINUv%;US&PXheEB9n ill6tDF_#O4Feb=_K^U*(av_Xp`5Xx2w7%)000jV3RCn(H diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index 7644c7e..42a3a5e 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -124,7 +124,7 @@ fn cmd_to_filter(og_entry: &str) -> Result for AdvancedStats { ) .map(|f| *f) .unwrap_or_default(), - avg_damage_single_huge_hit: BestDamageScenarios::from_action_constraints( + avg_damage_2a_huge_hit: BestDamageScenarios::from_action_constraints( value, Actions(2), Attacks(2), - Dices(8), + Dices(10), Precision(9), ) .map(|f| *f) @@ -290,7 +290,7 @@ macro_rules! sort_by { #[macro_export] /// A simple macro to sort the inner advanced field by a specific field // TODO[6] find a way to not have to import the refinedequipement -macro_rules! sort_by_cat_then { +macro_rules! sort_by_weapon_then { ($field:ident) => { |a, b| match a.inner.id[0].cmp(&b.inner.id[0]) { std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field), @@ -298,3 +298,35 @@ macro_rules! sort_by_cat_then { } }; } + +#[macro_export] +/// Sort by size first, then by the given field +macro_rules! sort_by_cat_then { + ($field:ident) => { + |a, b| { + if let (Some(c), Some(d)) = ( + a.inner.category_size.as_ref(), + b.inner.category_size.as_ref(), + ) { + match c.cmp(d) { + std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field), + ord => ord, + } + } else { + a.advanced.$field.total_cmp(&b.advanced.$field) + } + } + }; +} + +#[macro_export] +/// A simple macro to sort the inner advanced field by a specific field +// TODO[6] find a way to not have to import the refinedequipement +macro_rules! sort_by_size_then { + ($field:ident) => { + |a, b| match a.inner.category_size.cmp(&b.inner.category_size) { + std::cmp::Ordering::Equal => a.advanced.$field.total_cmp(&b.advanced.$field), + ord => ord, + } + }; +} diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 84679d9..4f436ac 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -266,8 +266,10 @@ impl EquipementTargets { // TODO[!] : This part is initialized by the natures subtable and might be better of being a new column in the database /// The Base Size of the weapon, used to infer the final category of the weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] -#[cfg_attr(test, derive(PartialEq))] +#[derive( + Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Display, Deserialize, Serialize, strum::EnumString, +)] +// #[cfg_attr(test, derive(PartialEq))] pub enum WeaponBaseSize { Light, Medium, -- 2.45.1 From b5fb986b5f63978a43a4e46205742ab212b6ddee Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 26 Feb 2025 01:07:29 +0100 Subject: [PATCH 3/4] Adds a new damage algorithm calculator, more precise way less optimized --- weaponry/src/export.rs | 27 ++ .../equipement_advanced_repr.rs | 4 +- .../equipement_advanced_tools.rs | 321 +++++++++++------- 3 files changed, 227 insertions(+), 125 deletions(-) diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs index 455d894..1bb8a72 100644 --- a/weaponry/src/export.rs +++ b/weaponry/src/export.rs @@ -112,3 +112,30 @@ pub fn initial_chart(chart_name: &str) -> charming::Chart { .y_axis(charming::component::Axis::new()) .grid(charming::component::Grid::new().contain_label(true)) } + +/// Generate a new plot chart +pub fn initial_plot_chart(chart_name: &str) -> charming::Chart { + charming::Chart::new() + .title( + charming::component::Title::new() + .text(chart_name) + .left("center"), + ) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) + .data_zoom( + charming::component::DataZoom::new() + .type_(charming::component::DataZoomType::Inside) + .start(0) + .end(100), + ) + .data_zoom(charming::component::DataZoom::new().start(0).end(100)) + .toolbox( + charming::component::Toolbox::new().feature( + charming::component::Feature::new() + .data_zoom(charming::component::ToolboxDataZoom::new().y_axis_index("none")) + .restore(charming::component::Restore::new()) + .save_as_image(charming::component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + ), + ) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) +} diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 3c60121..915d039 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -196,7 +196,7 @@ impl From<&InnerEquipementStats> for AdvancedStats { defensive: (value.parry as f64).max(value.dodge.into()), variance, variance_pct: variance / value.damage as f64, - avg_damage_2a_safe: BestDamageScenarios::from_action_constraints( + avg_damage_2a_safe: BestDamageScenarios::from_action_constraints_it( value, Actions(2), Attacks(2), @@ -205,7 +205,7 @@ impl From<&InnerEquipementStats> for AdvancedStats { ) .map(|f| *f) .unwrap_or_default(), - avg_damage_2a_huge_hit: BestDamageScenarios::from_action_constraints( + avg_damage_2a_huge_hit: BestDamageScenarios::from_action_constraints_it( value, Actions(2), Attacks(2), diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index a4e7cef..5a33f5f 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -156,8 +156,7 @@ fn damage_over_turns(value: &InnerEquipementStats, turn_info: &[TurnInfo]) -> f6 attacks_used: _, damage_done, reload_remaining, - depth: _, - }) = BestDamageScenarios::from_action_constraints( + }) = BestDamageScenarios::from_action_constraints_it( value, *actions - reloading_left, *attacks, @@ -183,9 +182,6 @@ pub struct BestDamageScenarios { damage_done: f64, /// Remaining actions that need to be used to finish reload reload_remaining: Actions, - /// A debug value, should be taken down in final builds - // TODO[6]: Remove debug once the tests are done - depth: u8, } impl Add for BestDamageScenarios { @@ -197,7 +193,6 @@ impl Add for BestDamageScenarios { attacks_used: self.attacks_used + rhs.attacks_used, damage_done: self.damage_done + rhs.damage_done, reload_remaining: self.reload_remaining + rhs.reload_remaining, - depth: self.depth + rhs.depth, } } } @@ -214,118 +209,198 @@ 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) - pub fn from_action_constraints( + // TODO[!]: Clean this cursed abomination + pub fn from_action_constraints_it( 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 - 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 - // ); + let full_attack_cost = + equipement_stats.action_cost + equipement_stats.reload_cost.unwrap_or_default(); + if full_attack_cost == 0 { 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 + let nb_max_attacks_reload = actions_allowed.div_euclid(full_attack_cost); + let remaining_actions = actions_allowed.rem_euclid(full_attack_cost); + let (remaining_reload, extra_attack) = if remaining_actions >= equipement_stats.action_cost { - // 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); - } - } - } + (-(remaining_actions - *attacks_allowed), Attacks(1)) + } else { + (0, Attacks(0)) + }; - // The alternative didn't exist or was worse - Some(one_attack) + // 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)) + .map(|attacks| { + ( + attacks, + { + if nb_max_attacks_reload + *extra_attack == attacks { + remaining_reload + } else { + 0 + } + }, + stack_binomials(equipement_stats, dices_allowed, precision, attacks), + ) + }) + .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), + damage_done: values[0].2, + 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 +fn stack_binomials( + equipement_stats: &InnerEquipementStats, + dices_allowed: Dices, + precision: Precision, + attacks: i8, +) -> f64 { + (binomial_dice_distribution( + equipement_stats, + precision, + Dices(dices_allowed.div_euclid(attacks.try_into().unwrap())), + ) * (attacks - 1) as f64) + + (binomial_dice_distribution( + equipement_stats, + precision, + Dices( + dices_allowed.div_euclid(attacks.try_into().unwrap()) + + dices_allowed.rem_euclid(attacks.try_into().unwrap()), + ), + )) } /// Calculate the binomial distribution and average the damage from there @@ -432,7 +507,7 @@ mod test { } #[test] - fn test_damage_optimisation() { + fn test_damage_optimisation_it() { let eq = InnerEquipementStats { damage: 10, p_damage: 2, @@ -460,7 +535,7 @@ mod test { }; let known_data = &[ ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq, Actions(2), Attacks(1), @@ -470,7 +545,7 @@ mod test { 14., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq, Actions(2), Attacks(2), @@ -480,7 +555,7 @@ mod test { 22., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq, Actions(3), Attacks(3), @@ -490,7 +565,7 @@ mod test { 30., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq, Actions(3), Attacks(3), @@ -500,7 +575,7 @@ mod test { 36., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq, Actions(3), Attacks(3), @@ -510,7 +585,7 @@ mod test { 36., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq2, Actions(1), Attacks(1), @@ -520,7 +595,7 @@ mod test { 0., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq2, Actions(2), Attacks(1), @@ -530,7 +605,7 @@ mod test { 14., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq2, Actions(4), Attacks(2), @@ -540,7 +615,7 @@ mod test { 22., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq2, Actions(5), Attacks(3), @@ -550,7 +625,7 @@ mod test { 28., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq2, Actions(6), Attacks(3), @@ -560,7 +635,7 @@ mod test { 36., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq3, Actions(2), Attacks(1), @@ -570,7 +645,7 @@ mod test { 14., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq3, Actions(4), Attacks(2), @@ -580,7 +655,7 @@ mod test { 14., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq3, Actions(6), Attacks(2), @@ -590,7 +665,7 @@ mod test { 22., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq3, Actions(6), Attacks(3), @@ -600,7 +675,7 @@ mod test { 28., ), ( - BestDamageScenarios::from_action_constraints( + BestDamageScenarios::from_action_constraints_it( &eq3, Actions(10), Attacks(3), -- 2.45.1 From 6526d164514899346f409e44ba452736a275306f Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 26 Feb 2025 05:26:12 +0100 Subject: [PATCH 4/4] Adds sub plots ? --- weaponry/benches/iter_creation.rs | 58 --------- weaponry/src/export.rs | 110 ++++++++++++------ .../equipement_advanced_repr.rs | 85 +++++++++++++- .../equipement_advanced_tools.rs | 13 +-- 4 files changed, 163 insertions(+), 103 deletions(-) diff --git a/weaponry/benches/iter_creation.rs b/weaponry/benches/iter_creation.rs index 7ca9b5b..801cb45 100644 --- a/weaponry/benches/iter_creation.rs +++ b/weaponry/benches/iter_creation.rs @@ -50,61 +50,3 @@ criterion_group! { targets= criterion_benchmark } criterion_main!(benches); - -// TODO: Add to a How to add new Lists - -// #[derive(Clone)] -// struct Equipo { -// stats: InnerStats, -// } - -// impl Equipo { -// fn newish(i: u8) -> Self { -// let mut stats = InnerStats::default(); -// stats.id = i; -// Equipo { stats } -// } -// } - -// struct ListStatic { -// inner: Vec, -// } -// struct ListParIter { -// inner: Vec, -// } - -// impl RecipeCollection for ListStatic { -// type Recipes = Equipo; - -// fn combine_all(&mut self, other: G) -// where -// G: RecipeCollection, -// { -// todo!() -// } - -// fn inner(&self) -> Vec { -// self.inner.clone() -// } - -// fn from_vectored(list: Vec) -> Self { -// Self { inner: list } -// } -// } - -// impl Combineable for Equipo { -// type Inner = InnerStats; - -// fn clone_combinable_part(&self) -> Self::Inner { -// self.stats.clone() -// } - -// fn add_to_self(&self, rhs: T) -> Self -// where -// T: Combineable, -// { -// Equipo { -// stats: self.clone_combinable_part() + rhs.clone_combinable_part(), -// } -// } -// } diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs index 1bb8a72..6b87b9f 100644 --- a/weaponry/src/export.rs +++ b/weaponry/src/export.rs @@ -4,6 +4,12 @@ //! //! Mostly graphs and csv auto conversion +use charming::{ + Chart, + component::{self, Axis, Grid, Title}, + element::{Tooltip, Trigger}, +}; + /// A very complex macro created to add criterias to the graph /// without repeating self explanatory parameter names in strings /// @@ -85,57 +91,93 @@ macro_rules! add_field_to_chart { } /// Generate a generic graph, ready to be filled with data -pub fn initial_chart(chart_name: &str) -> charming::Chart { - charming::Chart::new() - .title( - charming::component::Title::new() - .text(chart_name) - .left("center"), - ) +pub fn initial_chart(chart_name: &str) -> Chart { + Chart::new() + .title(component::Title::new().text(chart_name).left("center")) .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) .data_zoom( - charming::component::DataZoom::new() - .type_(charming::component::DataZoomType::Inside) + component::DataZoom::new() + .type_(component::DataZoomType::Inside) .start(0) .end(100), ) - .data_zoom(charming::component::DataZoom::new().start(0).end(100)) + .data_zoom(component::DataZoom::new().start(0).end(100)) .toolbox( - charming::component::Toolbox::new().feature( - charming::component::Feature::new() - .data_zoom(charming::component::ToolboxDataZoom::new().y_axis_index("none")) - .restore(charming::component::Restore::new()) - .save_as_image(charming::component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + component::Toolbox::new().feature( + component::Feature::new() + .data_zoom(component::ToolboxDataZoom::new().y_axis_index("none")) + .restore(component::Restore::new()) + .save_as_image(component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), ), ) .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) - .y_axis(charming::component::Axis::new()) - .grid(charming::component::Grid::new().contain_label(true)) + .y_axis(component::Axis::new()) + .grid(component::Grid::new().contain_label(true)) } /// Generate a new plot chart -pub fn initial_plot_chart(chart_name: &str) -> charming::Chart { - charming::Chart::new() - .title( - charming::component::Title::new() - .text(chart_name) - .left("center"), - ) - .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) +pub fn initial_plot_chart(chart_name: &str, sub_charts: &[&str]) -> Chart { + // charming::Chart::new() + Chart::new() + .title(Title::new().text(chart_name).left("center")) + .title(Title::new().text(sub_charts[0]).left("17%").top("5%")) + .title(Title::new().text(sub_charts[1]).left("17%").top("52%")) + .title(Title::new().text(sub_charts[2]).right("12%").top("5%")) + .title(Title::new().text(sub_charts[3]).right("12%").top("52%")) + .tooltip(Tooltip::new().trigger(Trigger::Axis)) .data_zoom( - charming::component::DataZoom::new() - .type_(charming::component::DataZoomType::Inside) + component::DataZoom::new() + .type_(component::DataZoomType::Inside) .start(0) .end(100), ) - .data_zoom(charming::component::DataZoom::new().start(0).end(100)) + .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) .toolbox( - charming::component::Toolbox::new().feature( - charming::component::Feature::new() - .data_zoom(charming::component::ToolboxDataZoom::new().y_axis_index("none")) - .restore(charming::component::Restore::new()) - .save_as_image(charming::component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), + component::Toolbox::new().feature( + component::Feature::new() + .data_zoom(component::ToolboxDataZoom::new().y_axis_index("none")) + .restore(component::Restore::new()) + .save_as_image(component::SaveAsImage::new()), // .brush(Brush::new().type_(vec![BrushType::LineX, BrushType::Clear])), ), ) - .tooltip(charming::element::Tooltip::new().trigger(charming::element::Trigger::Axis)) + .grid( + Grid::new() + .left("7%") + .top("7%") + .width("38%") + .height("38%") + .contain_label(true), + ) + .grid( + Grid::new() + .right("7%") + .top("7%") + .width("38%") + .height("38%") + .contain_label(true), + ) + .grid( + Grid::new() + .left("7%") + .bottom("7%") + .width("38%") + .height("38%") + .contain_label(true), + ) + .grid( + Grid::new() + .right("7%") + .bottom("7%") + .width("38%") + .height("38%") + .contain_label(true), + ) + .x_axis(Axis::new().grid_index(0).min(1)) + .x_axis(Axis::new().grid_index(1).min(1)) + .x_axis(Axis::new().grid_index(2).min(1)) + .x_axis(Axis::new().grid_index(3).min(1)) + .y_axis(Axis::new().grid_index(0).min(0)) + .y_axis(Axis::new().grid_index(1).min(0)) + .y_axis(Axis::new().grid_index(2).min(0)) + .y_axis(Axis::new().grid_index(3).min(0)) } diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 915d039..b9cfcf5 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -17,7 +17,7 @@ use super::{ use crate::{ add_field_to_chart, error::FatalEquipementError, - export::initial_chart, + export::{initial_chart, initial_plot_chart}, interfaces::{RecipeCollection, RefinedList, ToAnalysis, ToTex}, weaponry_structs::{ Equipement, InitialEquipementList, @@ -25,7 +25,7 @@ use crate::{ equipement_thin_types::{Dices, Precision}, }, }; -use charming::Chart; +use charming::{Chart, component::LegendSelectedMode}; use core::f64; use serde::Serialize; use std::cmp::Ordering; @@ -85,6 +85,49 @@ impl ToAnalysis for RefinedEquipementList { let mut renderer = charming::HtmlRenderer::new("Ravenous Balancing", 4000, 2000) .theme(charming::theme::Theme::Dark); + let initial_chart = self.make_regular_graph(); + renderer.save(&initial_chart, format!("{save_path}.html"))?; + + let plot_chart = self.make_cross_plots_graph(); + renderer.save(&plot_chart, format!("{save_path}_plots.html"))?; + Ok(()) + } +} + +impl RefinedEquipementList { + /// Make the cross graphs + fn make_cross_plots_graph(&self) -> Chart { + let mut plot_chart = initial_plot_chart( + "Damage Gradients Dice/Precision", + &["Damage 4+2A", "Damage 5+2A", "Damage 5+3A", "Damage 6+3A"], + ); + let mut names = Vec::with_capacity(self.inner.len()); + + for wpn in self.inner.iter() { + let data_4_a2: Vec> = custom_scenario(&wpn.inner, Actions(4), Attacks(2)); + let data_5_a2: Vec> = custom_scenario(&wpn.inner, Actions(5), Attacks(2)); + let data_5_a3: Vec> = custom_scenario(&wpn.inner, Actions(5), Attacks(3)); + let data_6_a3: Vec> = custom_scenario(&wpn.inner, Actions(6), Attacks(3)); + plot_chart = add_serie(plot_chart, 0, wpn, data_4_a2); + plot_chart = add_serie(plot_chart, 1, wpn, data_5_a2); + plot_chart = add_serie(plot_chart, 2, wpn, data_5_a3); + plot_chart = add_serie(plot_chart, 3, wpn, data_6_a3); + names.push(wpn.advanced.display_name.as_str()); + } + + plot_chart = plot_chart.legend( + charming::component::Legend::new() + .left(10) + .top("middle") + .orient(charming::element::Orient::Vertical) + .data(names) + .selected_mode(LegendSelectedMode::Multiple), + ); + plot_chart + } + + /// Max the regular balancing plots + fn make_regular_graph(&self) -> Chart { let initial_chart: Chart = initial_chart(&format!( "Damage for all cross-gen products ({} Elements)", self.inner.len() @@ -133,11 +176,45 @@ impl ToAnalysis for RefinedEquipementList { ) } ); - renderer.save(&initial_chart, format!("{save_path}.html"))?; - Ok(()) + initial_chart } } +/// Inner function to add a serie to a plot +fn add_serie(plot_chart: Chart, id: u8, wpn: &RefinedEquipement, serie: Vec>) -> Chart { + plot_chart.series( + charming::series::Line::new() + .x_axis_index(id) + .y_axis_index(id) + .data(serie) + .name(&wpn.advanced.display_name), + ) +} + +/// Custom scenario for creating scatter plot +fn custom_scenario( + equipement_stats: &InnerEquipementStats, + actions: Actions, + attacks: Attacks, +) -> Vec> { + (1..11) + .map(|dice| { + vec![ + dice as f64, + BestDamageScenarios::from_action_constraints_it( + equipement_stats, + actions, + attacks, + Dices(dice), + Precision(9), + ) + .unwrap_or_default() + .damage_done, + ] + }) + .collect() +} + /// The list of advanced stats infered from an Equipement #[derive(Serialize)] pub struct AdvancedStats { diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index 5a33f5f..ef81d9c 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -171,17 +171,17 @@ fn damage_over_turns(value: &InnerEquipementStats, turn_info: &[TurnInfo]) -> f6 } /// The best resulting attack pattern of a virtual scenrio where some conditions are given -#[derive(Debug)] -#[cfg_attr(test, derive(Default, Clone))] +#[derive(Debug, Default)] +#[cfg_attr(test, derive(Clone))] pub struct BestDamageScenarios { /// How many actions were used by the best attack - actions_used: Actions, + pub actions_used: Actions, /// Attacks actions used by the scenario - attacks_used: Attacks, + pub attacks_used: Attacks, /// Resulting damage - damage_done: f64, + pub damage_done: f64, /// Remaining actions that need to be used to finish reload - reload_remaining: Actions, + pub reload_remaining: Actions, } impl Add for BestDamageScenarios { @@ -204,7 +204,6 @@ impl Deref for BestDamageScenarios { } } -// TODO[!!]: Add a lot of testing impl BestDamageScenarios { /// Calculate the best alternative with a set of contraints /// -- 2.45.1