From a7f4ceb0072ed18f78242fedc67cfa4c06703c02 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 12 Feb 2025 01:23:12 +0100 Subject: [PATCH 1/3] Clarifies the dependencies and cleanup the text --- README.md | 7 ++++++- weaponry/Cargo.toml | 2 +- weaponry/src/database.rs | 3 +++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5baf08d..0229a44 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,8 @@ # ravenous-tools -Set of tools to handle ravenous rulebook creation \ No newline at end of file +Set of tools to handle ravenous rulebook creation + +# Installation +Now depends on libsqlite3-dev and sqlite3 +A bundled implementation should be added + diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 1e5ee4e..981c9b1 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -6,7 +6,7 @@ edition = "2024" [dependencies] pretty_assertions = "1.4.1" rayon = "1.10.0" -rusqlite = "0.33.0" +rusqlite = { version = "0.33.0", features = ["bundled"] } struct-field-names-as-array = "0.3.0" [dev-dependencies] diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 6250efa..6aebc1e 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -66,16 +66,19 @@ mod test { ) } + #[ignore] #[test] fn test_initialize_database_conn() { todo!() } + #[ignore] #[test] fn test_generate_table_from_struct() { todo!() } + #[ignore] #[test] fn test_get_data() { todo!() -- 2.45.1 From 495607efb4b7e2002f49bc31b81d9d803bc982d1 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 12 Feb 2025 20:03:11 +0100 Subject: [PATCH 2/3] Adds a semi realistic example and more filtering --- .gitignore | 4 +- weaponry/Cargo.toml | 1 + weaponry/benches/iter_creation.rs | 4 +- weaponry/examples/typical_wl_recipe.rs | 40 +++++++++++ weaponry/src/database.rs | 4 ++ weaponry/src/interfaces.rs | 69 ++++++++++++++++--- .../src/weaponry_structs/equipement_fields.rs | 20 +++--- ...nto_impls.rs => equipement_impl_basics.rs} | 51 ++++++++++++-- .../weaponry_structs/equipement_impl_logic.rs | 21 ++++-- .../weaponry_structs/equipement_impl_math.rs | 17 +++-- .../weaponry_structs/equipement_structs.rs | 58 +++++++++++----- weaponry/src/weaponry_structs/mod.rs | 2 +- 12 files changed, 238 insertions(+), 53 deletions(-) create mode 100644 weaponry/examples/typical_wl_recipe.rs rename weaponry/src/weaponry_structs/{equipement_into_impls.rs => equipement_impl_basics.rs} (50%) diff --git a/.gitignore b/.gitignore index a47be09..7d12725 100644 --- a/.gitignore +++ b/.gitignore @@ -23,4 +23,6 @@ Cargo.lock /target .cargo/ -*.tar.gz +*.json.gz +callgrind* +cache.out diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 981c9b1..658d720 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -4,6 +4,7 @@ version = "0.1.0" edition = "2024" [dependencies] +fastrand = "2.3.0" pretty_assertions = "1.4.1" rayon = "1.10.0" rusqlite = { version = "0.33.0", features = ["bundled"] } diff --git a/weaponry/benches/iter_creation.rs b/weaponry/benches/iter_creation.rs index 75c07b9..8fa7981 100644 --- a/weaponry/benches/iter_creation.rs +++ b/weaponry/benches/iter_creation.rs @@ -22,8 +22,8 @@ fn criterion_benchmark(c: &mut Criterion) { c.bench_function("IterGenBlanket: 100x100x100", |b| { b.iter(|| { let mut s = blk_steps[0].clone(); - s.combine_all_by_blanket(black_box(&blk_steps[1])); - s.combine_all_by_blanket(black_box(&blk_steps[2])); + s.combine_all(black_box(&blk_steps[1])); + s.combine_all(black_box(&blk_steps[2])); }) }); // c.bench_function("IterGen: 100x100x100x100", |b| { diff --git a/weaponry/examples/typical_wl_recipe.rs b/weaponry/examples/typical_wl_recipe.rs new file mode 100644 index 0000000..ac1d0bb --- /dev/null +++ b/weaponry/examples/typical_wl_recipe.rs @@ -0,0 +1,40 @@ +// Workspace: weaponry +// File: examples/typical_wl_recipe.rs +//! Example of a typical workload + +use std::time::Instant; + +use weaponry::{ + interfaces::RecipeCollection, + weaponry_structs::{Equipement, FinalEquipementList}, +}; + +fn main() { + let blk_steps = [ + FinalEquipementList::from_vectored( + [1; 100].iter().map(|_| Equipement::default()).collect(), + ), + FinalEquipementList::from_vectored( + [1; 100].iter().map(|_| Equipement::default()).collect(), + ), + FinalEquipementList::from_vectored( + [1; 100].iter().map(|_| Equipement::default()).collect(), + ), + ]; + + // #[cfg(test)] + // println!("{:#?}", blk_steps); + let now = Instant::now(); + let mut s = blk_steps[0].clone(); + println!("First size {}", s.ref_inner().len()); + s.combine_all(&blk_steps[0]); + println!("Second size {}", s.ref_inner().len()); + s.combine_all(&blk_steps[0]); + println!("Third size {}", s.ref_inner().len()); + s.combine_all(&blk_steps[0]); + + // println!("{:#?}", blk_steps); + // println!("{:#?}", s); + println!("Final size {}", s.ref_inner().len()); + println!("Ellapsed: {:?}", Instant::now().duration_since(now)); +} diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index 6aebc1e..ecea348 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -5,6 +5,10 @@ //! Should dump whole database in a vec of structs from weaponry_structs #![allow(dead_code)] #![allow(unused_imports)] +#![allow(missing_docs)] +#![allow(clippy::missing_docs_in_private_items)] +#![allow(clippy::single_char_add_str)] +#![allow(clippy::explicit_auto_deref)] use std::ops::Deref; use crate::weaponry_structs::equipement_structs::InnerStats; diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index d72a4cc..c78d5e3 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -5,6 +5,9 @@ //! handling of the whole crafting process when the times comes #![allow(dead_code)] +// use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; +use std::rc::Rc; + /// This element can be converted to tex pub trait ToTex {} @@ -16,15 +19,15 @@ pub trait FromParts {} /// A recipe list will be combined with a part list to be updated and generate all combinaisons, so on and so forth pub trait RecipeCollection where - for<'a> &'a <::Recipes as Combineable>::Inner: std::ops::Add, + for<'a> &'a <::Recipes as Combinable>::Inner: std::ops::Add, { /// The type of the inner recipes, this type must be combinable - type Recipes: Combineable; + type Recipes: Combinable; /// A blanket implementation giving all combinaisons of recipes with another RecipeCollection /// /// This method doesn't make use of parallel iterators as the workload is way faster than would be the memory dispatch - fn combine_all_by_blanket(&mut self, other: &G) + fn combine_all(&mut self, other: &G) where G: RecipeCollection, { @@ -35,6 +38,7 @@ where other .ref_inner() .iter() + .filter(|&external_recipes| external_recipes.backward_filter(inner_recipes)) .map(|external_recipes: &Self::Recipes| { inner_recipes.add_ref_to_self(external_recipes) }) @@ -51,8 +55,11 @@ where /// /// This allows to only clone when needed fn ref_inner(&self) -> &Vec; - - // Optional filter ? + /// + /// Gives access to a reference of the inner list + /// + /// This allows to only clone when needed + fn owned_inner(&self) -> Vec; /// Create a collection from a vector fn from_vectored(list: Vec) -> Self; @@ -61,11 +68,11 @@ where /// Trait that ensure that two elements of a recipe are combinable, /// /// Being combinable means it can be coerced into elements that implement add -pub trait Combineable +pub trait Combinable where - for<'a> &'a ::Inner: std::ops::Add, + for<'a> &'a ::Inner: std::ops::Add, { - /// The inner type of the combined elements, this type must implement Add + /// The inner type of the combined elements, this type must implement Add<&Inner> // TODO : Make this help much more readable type Inner; @@ -80,5 +87,49 @@ where /// This pushes the actual requirement to &Inner : Add<&Inner> fn add_ref_to_self(&self, rhs: &T) -> Self where - T: Combineable; + T: Combinable; + + /// Filter to decide if the addition should be done + /// + /// + /// Please note that this comparison is done from the new element perspective, + /// asking it if it will allow itself to be added as There is as of now no forward filtering + /// Most filters will defer an internal FilterFunction into the Inner to do all inner working, + /// but the implementation specifics are left open + fn backward_filter(&self, lhs: &T) -> bool + where + T: Combinable; } + +/// Type alias represinting the inner function parameter +pub(super) type FilterFunctionType = dyn Fn(&T, &T) -> bool; +/// Type alias representing a filter +pub(super) type FilterType = Box>>; + +#[derive(Clone)] +/// A generic Filtering function +pub(crate) struct FilterFunction(pub(super) FilterType); + +// /// A blanket implementation giving all combinaisons of recipes with another RecipeCollection +// /// +// /// This method doesn't make use of parallel iterators as the workload is way faster than would be the memory dispatch +// fn combine_all_par(&mut self, other: &G) +// where +// G: RecipeCollection + std::marker::Sync, +// { +// self.assign_inner( +// self.owned_inner() +// .par_iter() +// .flat_map(|inner_recipes| { +// other +// .ref_inner() +// .iter() +// .filter(|&external_recipes| external_recipes.backward_filter(inner_recipes)) +// .map(|external_recipes: &Self::Recipes| { +// inner_recipes.add_ref_to_self(external_recipes) +// }) +// .collect::>() +// }) +// .collect::>(), +// ); +// } diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 2bbcb5d..847c1e0 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -2,8 +2,8 @@ // File: weaponry/src/weaponry_structs/equipement_fields.rs //! The inner fields used by the super structs -#[derive(Clone, Default)] -#[cfg_attr(test, derive(Debug, PartialEq))] +#[derive(Clone, Default, Debug)] +#[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only pub struct SpecialCategory(pub(super) Vec); @@ -19,8 +19,8 @@ pub enum NatureTarget { /// Enum of all different physical weapon damage types #[allow(clippy::missing_docs_in_private_items)] -#[derive(Clone)] -#[cfg_attr(test, derive(Debug, PartialEq))] +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] pub enum PhysicalDamageType { Blunt, Slash, @@ -38,8 +38,8 @@ impl From<&str> for PhysicalDamageType { /// /// Signifying wether the damage is pure or [secondary] or [[tertiary]] #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone)] -#[cfg_attr(test, derive(Debug, PartialEq))] +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] pub enum DamageMod { Primary(PhysicalDamageType), Secondary(PhysicalDamageType), @@ -57,8 +57,8 @@ impl From<&str> for DamageMod { /// Combined damage type, as a vector of all damage types /// /// Meant to be serialised to tex and deserialized directly from the table -#[derive(Clone)] -#[cfg_attr(test, derive(Debug, PartialEq))] +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] pub struct DamageType(pub(super) Vec); impl From<&str> for DamageType { @@ -71,8 +71,8 @@ impl From<&str> for DamageType { /// List all weapon categories #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone)] -#[cfg_attr(test, derive(Debug, PartialEq))] +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] pub enum WeaponCategory { Exotic, Dagger, diff --git a/weaponry/src/weaponry_structs/equipement_into_impls.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs similarity index 50% rename from weaponry/src/weaponry_structs/equipement_into_impls.rs rename to weaponry/src/weaponry_structs/equipement_impl_basics.rs index 5beefef..218b5f9 100644 --- a/weaponry/src/weaponry_structs/equipement_into_impls.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -8,6 +8,10 @@ //! Implementations to transform all Specialized equipement into a generic Equipement //! A specific implementation could be preferable, but this simplicity might allow for easier developpement +use crate::interfaces::FilterFunction; +use std::fmt::Debug; +use std::rc::Rc; + use super::{ Equipement, equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}, @@ -15,21 +19,60 @@ use super::{ impl From for Equipement { fn from(val: EqShape) -> Self { - Self { stats: val.stats } + Self { + stats: val.stats, + ..Default::default() + } } } impl From for Equipement { fn from(val: EqMaterial) -> Self { - Self { stats: val.stats } + Self { + stats: val.stats, + ..Default::default() + } } } impl From for Equipement { fn from(val: EqNature) -> Self { - Self { stats: val.stats } + Self { + stats: val.stats, + ..Default::default() + } } } impl From for Equipement { fn from(val: EqFinishing) -> Self { - Self { stats: val.stats } + Self { + stats: val.stats, + ..Default::default() + } } } + +impl Debug for FilterFunction { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "Filter:{}", + // std::any::type_name::(), + std::any::type_name::() + ) + } +} +impl Default for FilterFunction { + fn default() -> Self { + FilterFunction(Box::new(Rc::new(|_, _| true))) + } +} +impl PartialEq for FilterFunction { + fn eq(&self, _other: &Self) -> bool { + true + } +} +// impl FilterFunction { +// /// Generate a new filter +// pub fn new(filter: FilterFunctionType) -> Self { +// Self(Box::new(Rc::new(filter))) +// } +// } diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index e2fed62..21acb2e 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -2,11 +2,11 @@ // File: weaponry/src/weaponry_structs/equipement_impl_logic.rs //! Implementation of the logic traits, used for equipement generation -use crate::interfaces::{Combineable, RecipeCollection}; +use crate::interfaces::{Combinable, RecipeCollection}; use super::{Equipement, FinalEquipementList, equipement_structs::InnerStats}; -impl Combineable for Equipement { +impl Combinable for Equipement { type Inner = InnerStats; fn combinable_part(&self) -> &Self::Inner { @@ -15,12 +15,20 @@ impl Combineable for Equipement { fn add_ref_to_self(&self, rhs: &T) -> Self where - T: Combineable, + T: Combinable, { Self { stats: self.combinable_part() + rhs.combinable_part(), + ..Default::default() } } + + fn backward_filter(&self, lhs: &T) -> bool + where + T: Combinable, + { + self.filter_function.0(self.combinable_part(), lhs.combinable_part()) + } } impl RecipeCollection for FinalEquipementList { @@ -37,6 +45,10 @@ impl RecipeCollection for FinalEquipementList { fn assign_inner(&mut self, inner: Vec) { self.inner = inner; } + + fn owned_inner(&self) -> Vec { + self.inner.clone() + } } #[cfg(test)] @@ -66,7 +78,7 @@ mod test { &vec![Equipement::newish(&["a"], 1), Equipement::newish(&["b"], 2)] ); - f.combine_all_by_blanket(&g); + f.combine_all(&g); assert_eq!( f, FinalEquipementList::from_vectored(vec![ @@ -170,6 +182,7 @@ mod test { rarity: i, ..Default::default() }, + ..Default::default() } } } diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index 19d8235..0f49394 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -6,18 +6,23 @@ use super::equipement_structs::InnerStats; use crate::weaponry_structs::SpecialCategory; +/// Add a new vector to a clone of a inner field +macro_rules! add_to_vec { + ($self: expr, $rhs: expr) => {{ + let mut new = $self.clone(); + new.append(&mut $rhs.clone()); + new + }}; +} + impl std::ops::Add for &InnerStats { type Output = InnerStats; fn add(self, rhs: Self) -> Self::Output { InnerStats { // TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless - id: self.id, - name: { - let mut b = self.name.clone(); - b.append(&mut rhs.name.clone()); - b - }, + id: add_to_vec!(self.id, rhs.id), + name: add_to_vec!(self.name, rhs.name), rarity: self.rarity + rhs.rarity, cost: self.cost + rhs.cost, difficulty: self.difficulty + rhs.difficulty, diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 856ff94..c4ccdf8 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -2,34 +2,51 @@ // File: weaponry/src/weaponry_structs/equipement_structs.rs //! Base equipement structures +use std::rc::Rc; + use struct_field_names_as_array::FieldNamesAsArray; +use crate::interfaces::FilterFunction; + use super::{DamageType, NatureTarget, SpecialCategory, WeaponCategory}; /// The final equipement list /// /// This list is initialized with the base part and updated by succesive combinaisons -#[derive(Clone)] -#[cfg_attr(test, derive(PartialEq, Debug))] +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] pub struct FinalEquipementList { /// Inner List of final equipements pub(super) inner: Vec, } /// The final equipement, obtained by combining all parts -#[derive(Clone, Default)] -#[cfg_attr(test, derive(PartialEq, Debug))] +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] pub struct Equipement { /// The inner stats used by the equipement pub(super) stats: InnerStats, + /// The filter, used to determine if adding is warranted + pub(super) filter_function: FilterFunction, +} + +impl Default for Equipement { + fn default() -> Self { + Self { + filter_function: FilterFunction(Box::new(Rc::new(|self_, lhs| { + !self_.id.iter().any(|a| *a == lhs.id[0]) + }))), + stats: InnerStats::random_new(), + } + } } /// The inner statistics of the equipement, used across all parts and final weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Default, FieldNamesAsArray)] -#[cfg_attr(test, derive(Debug, PartialEq))] +#[derive(Clone, Default, FieldNamesAsArray, Debug)] +#[cfg_attr(test, derive(PartialEq))] pub struct InnerStats { - pub id: u8, + pub id: Vec, pub name: Vec, pub(super) rarity: u8, pub(super) cost: u8, @@ -59,6 +76,16 @@ pub struct InnerStats { pub(super) agility_bonus: u8, } +impl InnerStats { + /// Testing function to fuzz data + pub fn random_new() -> Self { + Self { + id: vec![fastrand::u8(..10)], + ..Default::default() + } + } +} + /// Shape of the equipement, first mandatory part of an equipement pub struct EqShape { /// The inner stats of the part @@ -99,6 +126,8 @@ mod test { EqFinishing, EqMaterial, EqNature, EqShape, Equipement, FinalEquipementList, InnerStats, }; + // use pretty_assertions::assert_eq; + fn list_equip() -> Vec { (0..10) .map(|_| Equipement { @@ -109,15 +138,12 @@ mod test { #[test] fn test_struct_creation() { - let stats = InnerStats::default(); - let eq1 = Equipement { + let _stats = InnerStats::default(); + let _eq1 = Equipement { ..Default::default() }; - let list_eq = list_equip(); - - assert_eq!(stats, eq1.stats); - assert_eq!(list_eq[0], eq1); + let _list_eq = list_equip(); } #[test] @@ -149,9 +175,9 @@ mod test { ]; let mut leq = FinalEquipementList::from_vectored(shape); - leq.combine_all_by_blanket(&FinalEquipementList::from_vectored(nature)); - leq.combine_all_by_blanket(&FinalEquipementList::from_vectored(material)); - leq.combine_all_by_blanket(&FinalEquipementList::from_vectored(finishing)); + leq.combine_all(&FinalEquipementList::from_vectored(nature)); + leq.combine_all(&FinalEquipementList::from_vectored(material)); + leq.combine_all(&FinalEquipementList::from_vectored(finishing)); } #[ignore] diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 6f34bd1..482bd6b 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -16,11 +16,11 @@ // static GLOBAL: Jemalloc = Jemalloc; mod equipement_fields; +mod equipement_impl_basics; mod equipement_impl_database; mod equipement_impl_io; mod equipement_impl_logic; mod equipement_impl_math; -mod equipement_into_impls; pub mod equipement_structs; // Republishes the most used symbols -- 2.45.1 From 91c5c4bb37016f6832decde5bd1b57a778c5752a Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 12 Feb 2025 21:29:15 +0100 Subject: [PATCH 3/3] Cleans up further database --- weaponry/src/database.rs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index ecea348..0f56fad 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -4,16 +4,9 @@ //! Implements the basics deserialisation from a database to the weaponry components //! Should dump whole database in a vec of structs from weaponry_structs #![allow(dead_code)] -#![allow(unused_imports)] -#![allow(missing_docs)] -#![allow(clippy::missing_docs_in_private_items)] -#![allow(clippy::single_char_add_str)] -#![allow(clippy::explicit_auto_deref)] -use std::ops::Deref; use crate::weaponry_structs::equipement_structs::InnerStats; -use rusqlite::{self, Connection, Result, params}; -use struct_field_names_as_array::FieldNamesAsArray; +use rusqlite::{self, Connection, Result}; /// Generate a SELECT query with fields generated from a struct. Returns a String fn generate_query(fields: &[&str], table_name: &str) -> String { @@ -51,9 +44,8 @@ pub fn get_data() -> Vec { #[cfg(test)] mod test { - use std::any::type_name; - use pretty_assertions::assert_eq; + use struct_field_names_as_array::FieldNamesAsArray; use super::*; #[derive(FieldNamesAsArray)] -- 2.45.1