weapons #28

Merged
Dandaedre merged 2 commits from weapons into project_weaponry 2025-02-11 23:38:02 +01:00
8 changed files with 374 additions and 191 deletions

1
.gitignore vendored
View File

@ -23,3 +23,4 @@ Cargo.lock
/target
.cargo/
*.tar.gz

View File

@ -28,3 +28,5 @@ lto = false
codegen-units = 256
incremental = true
panic = "abort"

View File

@ -2,37 +2,28 @@ use criterion::{Criterion, criterion_group, criterion_main};
use std::{hint::black_box, time::Duration};
use weaponry::{
interfaces::RecipeCollection,
weaponry_structs::{
Equipement, FinalEquipementList, equipement_structs::FinalEquipementListPar,
},
weaponry_structs::{Equipement, FinalEquipementList},
};
fn criterion_benchmark(c: &mut Criterion) {
let steps = [
let blk_steps = [
FinalEquipementList::from_vectored(vec![Equipement::default(); 100]),
FinalEquipementList::from_vectored(vec![Equipement::default(); 100]),
FinalEquipementList::from_vectored(vec![Equipement::default(); 100]),
];
let par_steps = [
FinalEquipementListPar::from_vectored(vec![Equipement::default(); 100]),
FinalEquipementListPar::from_vectored(vec![Equipement::default(); 100]),
FinalEquipementListPar::from_vectored(vec![Equipement::default(); 100]),
];
c.bench_function("creating 100 Elements", |b| {
b.iter(|| FinalEquipementList::from_vectored(black_box(vec![Equipement::default(); 100])))
});
c.bench_function("IterGen: 100x100x100", |b| {
b.iter(|| {
let mut s = steps[0].clone();
s.combine_all(steps[1].clone());
s.combine_all(steps[2].clone());
FinalEquipementList::from_vectored(black_box(vec![
black_box(Equipement::default());
100
]))
})
});
c.bench_function("IterGen: 100x100x100", |b| {
c.bench_function("IterGenBlanket: 100x100x100", |b| {
b.iter(|| {
let mut s = par_steps[0].clone();
s.combine_all(par_steps[1].clone());
s.combine_all(par_steps[2].clone());
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]));
})
});
// c.bench_function("IterGen: 100x100x100x100", |b| {
@ -43,14 +34,14 @@ fn criterion_benchmark(c: &mut Criterion) {
// s.combine_all(steps[2].clone());
// })
// });
c.bench_function("IterGenPar: 100x100x100x100", |b| {
b.iter(|| {
let mut s = par_steps[0].clone();
s.combine_all(par_steps[1].clone());
s.combine_all(par_steps[2].clone());
s.combine_all(par_steps[2].clone());
})
});
// c.bench_function("IterGenPar: 100x100x100x100", |b| {
// b.iter(|| {
// let mut s = par_steps[0].clone();
// s.combine_all(par_steps[1].clone());
// s.combine_all(par_steps[2].clone());
// s.combine_all(par_steps[2].clone());
// })
// });
}
criterion_group! {

View File

@ -18,14 +18,63 @@ pub trait RecipeCollection {
/// The type of the inner recipes, this type must be combinable
type Recipes: Combineable;
/// Combine all current recipies with all the parts given
fn combine_all<G>(&mut self, other: G)
where
G: RecipeCollection<Recipes = Self::Recipes> + std::marker::Sync;
// /// Combine all current recipies with all the parts given
// #[deprecated]
// fn combine_all<G>(&mut self, other: G)
// where
// G: RecipeCollection<Recipes = Self::Recipes> + std::marker::Sync;
/// Do the parrallel combination all inside
fn combine_all_by_blanket<G>(&mut self, other: &G)
where
G: RecipeCollection<Recipes = Self::Recipes>,
{
// TODO: Test Add to Self instead
self.assign_inner(
self.ref_inner()
.iter()
.flat_map(|inner_recipes| {
other
.ref_inner()
.iter()
.map(|external_recipes: &Self::Recipes| {
inner_recipes.add_ref_to_self(external_recipes)
})
.collect::<Vec<_>>()
})
.collect::<Vec<Self::Recipes>>(),
);
}
// fn combine_all_by_ref<G>(&mut self, other: G)
// where
// G: RecipeCollection<Recipes = Self::Recipes> + std::marker::Sync,
// {
// let mut future_receipes = vec![self.ref_inner().clone(); other.ref_inner().len()];
// future_receipes
// .par_iter_mut()
// .zip(other.ref_inner())
// .for_each(move |(a, b)| {
// a.par_iter_mut().for_each(move |e| {
// e.add_to_self(b);
// });
// });
// self.inner = future_receipes.into_par_iter().flatten().collect();
// }
/// Assign the inner value from an owned value, used for blanket implementations
fn assign_inner(&mut self, inner: Vec<Self::Recipes>);
/// Gives access to a reference of the inner list
///
/// This allows to only clone when needed
fn ref_inner(&self) -> &Vec<Self::Recipes>;
// /// Gives access to a mutable reference of the inner list
// #[deprecated]
// fn refmut_inner(&mut self) -> &mut Vec<Self::Recipes>;
/// Access the inner list
// TODO: Use iterators ?
fn inner(&self) -> Vec<Self::Recipes>;
// Optional filter ?
/// Create a collection from a vector
@ -38,16 +87,32 @@ pub trait RecipeCollection {
pub trait Combineable {
/// The inner type of the combined elements, this type must implement Add
// TODO : Make this help much more readable
type Inner: std::ops::Add;
type Inner: std::ops::Add + std::ops::AddAssign;
/// Give access to an owned underlying type that can be combined
// TODO: the ownership part might not be needed
fn clone_combinable_part(&self) -> Self::Inner;
/// Add an element to self and return a new value
/// Give access to a reference of the underlying data to be combined
///
/// This method will clone it's own combinable part
fn add_to_self<T>(&self, rhs: T) -> Self
/// The designed combinaison method is std::ops::Add
fn combinable_part(&self) -> &Self::Inner;
// /// Add an element to self and return a new value
// ///
// /// This method will clone it's own combinable part
// #[deprecated]
// fn add_to_other<T>(&self, rhs: T) -> Self
// where
// T: Combineable<Inner = Self::Inner>;
/// Add an element to a mutable self
// #[deprecated(note = "Mutate in place")]
fn add_to_self<T>(&mut self, rhs: &T)
where
T: Combineable<Inner = Self::Inner>;
/// Add an element to self and generate a new Self
///
/// As the signature implies, it will not mutate self not rhs and will generate a new value from the operation
/// This pushes the actual requirement to &Inner : Add<&Inner>
fn add_ref_to_self<T>(&self, rhs: &T) -> Self
where
T: Combineable<Inner = Self::Inner>;
}

View File

@ -2,86 +2,30 @@
// File: weaponry/src/weaponry_structs/equipement_impl_logic.rs
//! Implementation of the logic traits, used for equipement generation
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use crate::interfaces::{Combineable, RecipeCollection};
use super::{
Equipement, FinalEquipementList, SpecialCategory,
equipement_structs::{FinalEquipementListPar, InnerStats},
};
impl std::ops::Add for InnerStats {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self {
// TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless
id: self.id,
name: [self.name, rhs.name].join("+"),
rarity: self.rarity + rhs.rarity,
cost: self.cost + rhs.cost,
difficulty: self.difficulty + rhs.difficulty,
tier: self.tier + rhs.tier,
damage: self.damage + rhs.damage,
p_damage: self.p_damage + rhs.p_damage,
precision: self.precision + rhs.precision,
rmax: self.rmax + rhs.rmax,
armor_break: self.armor_break + rhs.armor_break,
armor_pierce: self.armor_pierce + rhs.armor_pierce,
antimaterial: self.antimaterial + rhs.antimaterial,
damage_type: {
match (self.damage_type, rhs.damage_type) {
(None, None) => None,
(None, Some(a)) => Some(a),
(Some(a), None) => Some(a),
(Some(mut a), Some(mut b)) => {
a.0.append(&mut b.0);
Some(a)
}
}
},
protection: self.protection + rhs.protection,
integrity: self.integrity + rhs.integrity,
torque_two_handed: self.torque_two_handed + rhs.torque_two_handed,
torque_one_handed: self.torque_one_handed + rhs.torque_one_handed,
dodge: self.dodge + rhs.dodge,
parry: self.parry + rhs.parry,
speed: self.speed + rhs.speed,
stealth: self.stealth + rhs.stealth,
category: self.category.or(rhs.category),
special: self.special + rhs.special,
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,
}
}
}
impl std::ops::Add for SpecialCategory {
type Output = Self;
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
}
}
use super::{Equipement, FinalEquipementList, equipement_structs::InnerStats};
impl Combineable for Equipement {
type Inner = InnerStats;
fn clone_combinable_part(&self) -> InnerStats {
self.stats.clone()
fn combinable_part(&self) -> &Self::Inner {
&self.stats
}
fn add_to_self<T>(&self, rhs: T) -> Self
fn add_to_self<T>(&mut self, rhs: &T)
where
T: Combineable<Inner = Self::Inner>,
{
self.stats += rhs.combinable_part().clone()
}
fn add_ref_to_self<T>(&self, rhs: &T) -> Self
where
T: Combineable<Inner = Self::Inner>,
{
Self {
stats: self.clone_combinable_part() + rhs.clone_combinable_part(),
stats: self.combinable_part() + rhs.combinable_part(),
}
}
}
@ -89,58 +33,16 @@ impl Combineable for Equipement {
impl RecipeCollection for FinalEquipementList {
type Recipes = Equipement;
fn combine_all<G>(&mut self, other: G)
where
G: RecipeCollection<Recipes = Self::Recipes>,
{
self.inner = self
.inner()
.iter()
.flat_map(|e| {
other
.inner()
.iter()
.map(|f: &Self::Recipes| e.add_to_self(f.clone()))
.collect::<Vec<_>>()
})
.collect();
}
fn inner(&self) -> Vec<Self::Recipes> {
self.inner.clone()
}
fn from_vectored(list: Vec<Self::Recipes>) -> Self {
Self { inner: list }
}
}
impl RecipeCollection for FinalEquipementListPar {
type Recipes = Equipement;
fn combine_all<G>(&mut self, other: G)
where
G: RecipeCollection<Recipes = Self::Recipes> + std::marker::Sync,
{
self.inner = self
.inner()
.par_iter()
.flat_map(|e| {
other
.inner()
.par_iter()
.map(|f: &Self::Recipes| e.add_to_self(f.clone()))
.collect::<Vec<_>>()
})
.collect();
fn ref_inner(&self) -> &Vec<Self::Recipes> {
&self.inner
}
fn inner(&self) -> Vec<Self::Recipes> {
self.inner.clone()
}
fn from_vectored(list: Vec<Self::Recipes>) -> Self {
Self { inner: list }
fn assign_inner(&mut self, inner: Vec<Self::Recipes>) {
self.inner = inner;
}
}
@ -156,38 +58,35 @@ mod test {
use pretty_assertions::assert_eq;
#[test]
fn test_struct_generation() {
fn test_blanket_struct_generation() {
let mut f = FinalEquipementList::from_vectored(vec![
Equipement::newish("", 1),
Equipement::newish("", 2),
Equipement::newish(&["a"], 1),
Equipement::newish(&["b"], 2),
]);
let g = FinalEquipementList::from_vectored(vec![
Equipement::newish("", 4),
Equipement::newish("", 8),
Equipement::newish(&["c"], 4),
Equipement::newish(&["d"], 8),
]);
assert_eq!(
f.inner(),
vec![Equipement::newish("", 1), Equipement::newish("", 2)]
f.ref_inner(),
&vec![Equipement::newish(&["a"], 1), Equipement::newish(&["b"], 2)]
);
f.combine_all(g);
f.combine_all_by_blanket(&g);
assert_eq!(
f,
FinalEquipementList::from_vectored(vec![
Equipement::newish("+", 5),
Equipement::newish("+", 9),
Equipement::newish("+", 6),
Equipement::newish("+", 10)
Equipement::newish(&["a", "c"], 5),
Equipement::newish(&["a", "d"], 9),
Equipement::newish(&["b", "c"], 6),
Equipement::newish(&["b", "d"], 10)
])
);
}
#[test]
fn test_base_operation() {
// let inner = InnerStats::default();
// let inner2 = inner.clone() + inner.clone();
// assert_eq!(inner, inner2); // True because of the 0 initialisation
let i1 = InnerStats {
rarity: 1,
integrity: 2,
@ -213,7 +112,6 @@ mod test {
assert_eq!(
i1 + i2,
InnerStats {
name: "+".into(),
rarity: 1,
integrity: 5,
agility_bonus: 9,
@ -229,15 +127,14 @@ mod test {
}
);
assert_eq!(
InnerStats {
&InnerStats {
damage_type: Some(DamageType(vec![
DamageMod::Secondary(PhysicalDamageType::Slash,),
DamageMod::Primary(PhysicalDamageType::Blunt,),
])),
..Default::default()
} + InnerStats::default(),
} + &InnerStats::default(),
InnerStats {
name: "+".into(),
damage_type: Some(DamageType(vec![
DamageMod::Secondary(PhysicalDamageType::Slash,),
DamageMod::Primary(PhysicalDamageType::Blunt,),
@ -255,7 +152,6 @@ mod test {
..Default::default()
},
InnerStats {
name: "+".into(),
damage_type: Some(DamageType(vec![
DamageMod::Secondary(PhysicalDamageType::Slash,),
DamageMod::Primary(PhysicalDamageType::Blunt,),
@ -274,10 +170,10 @@ mod test {
fn test_basic_logic() {}
impl Equipement {
fn newish(name: &str, i: u8) -> Self {
fn newish(name: &[&str], i: u8) -> Self {
Equipement {
stats: InnerStats {
name: name.to_owned(),
name: name.iter().map(|s| s.to_string()).collect(),
rarity: i,
..Default::default()
},

View File

@ -0,0 +1,208 @@
// Workspace: weaponry
// File: weaponry/src/weaponry_structs/equipement_math.rs
//! Implements base math for each field
//!
use super::equipement_structs::InnerStats;
use crate::weaponry_structs::SpecialCategory;
impl std::ops::Add for InnerStats {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self {
// 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
},
rarity: self.rarity + rhs.rarity,
cost: self.cost + rhs.cost,
difficulty: self.difficulty + rhs.difficulty,
tier: self.tier + rhs.tier,
damage: self.damage + rhs.damage,
p_damage: self.p_damage + rhs.p_damage,
precision: self.precision + rhs.precision,
rmax: self.rmax + rhs.rmax,
armor_break: self.armor_break + rhs.armor_break,
armor_pierce: self.armor_pierce + rhs.armor_pierce,
antimaterial: self.antimaterial + rhs.antimaterial,
damage_type: {
match (self.damage_type, rhs.damage_type) {
(None, None) => None,
(None, Some(a)) => Some(a),
(Some(a), None) => Some(a),
(Some(mut a), Some(mut b)) => {
a.0.append(&mut b.0);
Some(a)
}
}
},
protection: self.protection + rhs.protection,
integrity: self.integrity + rhs.integrity,
torque_two_handed: self.torque_two_handed + rhs.torque_two_handed,
torque_one_handed: self.torque_one_handed + rhs.torque_one_handed,
dodge: self.dodge + rhs.dodge,
parry: self.parry + rhs.parry,
speed: self.speed + rhs.speed,
stealth: self.stealth + rhs.stealth,
category: self.category.or(rhs.category),
special: self.special + rhs.special,
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,
}
}
}
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
},
rarity: self.rarity + rhs.rarity,
cost: self.cost + rhs.cost,
difficulty: self.difficulty + rhs.difficulty,
tier: self.tier + rhs.tier,
damage: self.damage + rhs.damage,
p_damage: self.p_damage + rhs.p_damage,
precision: self.precision + rhs.precision,
rmax: self.rmax + rhs.rmax,
armor_break: self.armor_break + rhs.armor_break,
armor_pierce: self.armor_pierce + rhs.armor_pierce,
antimaterial: self.antimaterial + rhs.antimaterial,
damage_type: {
match (self.damage_type.clone(), rhs.damage_type.clone()) {
(None, None) => None,
(None, Some(a)) => Some(a),
(Some(a), None) => Some(a),
(Some(mut a), Some(mut b)) => {
a.0.append(&mut b.0);
Some(a)
}
}
},
protection: self.protection + rhs.protection,
integrity: self.integrity + rhs.integrity,
torque_two_handed: self.torque_two_handed + rhs.torque_two_handed,
torque_one_handed: self.torque_one_handed + rhs.torque_one_handed,
dodge: self.dodge + rhs.dodge,
parry: self.parry + rhs.parry,
speed: self.speed + rhs.speed,
stealth: self.stealth + rhs.stealth,
category: self.category.clone().or(rhs.category.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,
}
}
}
impl std::ops::AddAssign for InnerStats {
fn add_assign(&mut self, rhs: InnerStats) {
// self.id;
// self.name.push('+');
// self.name.push_str(&rhs.name);
self.rarity += rhs.rarity;
self.cost += rhs.cost;
self.difficulty += rhs.difficulty;
self.tier += rhs.tier;
self.damage += rhs.damage;
self.p_damage += rhs.p_damage;
self.precision += rhs.precision;
self.rmax += rhs.rmax;
self.armor_break += rhs.armor_break;
self.armor_pierce += rhs.armor_pierce;
self.antimaterial += rhs.antimaterial;
self.damage_type = {
match (self.damage_type.clone(), rhs.damage_type.clone()) {
(None, None) => None,
(None, Some(a)) => Some(a),
(Some(a), None) => Some(a),
(Some(mut a), Some(mut b)) => {
a.0.append(&mut b.0);
Some(a)
}
}
};
self.protection += rhs.protection;
self.integrity += rhs.integrity;
self.torque_two_handed += rhs.torque_two_handed;
self.torque_one_handed += rhs.torque_one_handed;
self.dodge += rhs.dodge;
self.parry += rhs.parry;
self.speed += rhs.speed;
self.stealth += rhs.stealth;
self.category.clone().or(rhs.category.clone()); // Can be further optimized
// self.special += rhs.special.clone(); // Can be further optimized
self.action_cost += rhs.action_cost;
self.reload_cost.or(rhs.reload_cost);
self.range += rhs.range;
self.agility_bonus += rhs.agility_bonus;
}
}
impl std::ops::Add for SpecialCategory {
type Output = Self;
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
}
}
// 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!()
// }
// }

View File

@ -16,16 +16,6 @@ pub struct FinalEquipementList {
pub(super) inner: Vec<Equipement>,
}
/// A parallel Implementation of the final equipement list
///
/// This list only serve for benchmark purposes
#[derive(Clone)]
#[cfg_attr(test, derive(PartialEq, Debug))]
pub struct FinalEquipementListPar {
/// Inner List of final equipements
pub(super) inner: Vec<Equipement>,
}
/// The final equipement, obtained by combining all parts
#[derive(Clone, Default)]
#[cfg_attr(test, derive(PartialEq, Debug))]
@ -40,7 +30,7 @@ pub struct Equipement {
#[cfg_attr(test, derive(Debug, PartialEq))]
pub struct InnerStats {
pub id: u8,
pub name: String,
pub name: Vec<String>,
pub(super) rarity: u8,
pub(super) cost: u8,
pub(super) difficulty: u8,
@ -69,6 +59,21 @@ pub struct InnerStats {
pub(super) agility_bonus: u8,
}
// /// A type representing a weapon reload potential
// #[derive(Clone, Default)]
// #[cfg_attr(test, derive(Debug, PartialEq))]
// pub struct OptionnalReloadType(Option<u8>);
// /// Optionnal Weapon
// #[derive(Clone, Default)]
// #[cfg_attr(test, derive(Debug, PartialEq))]
// pub struct OptionnalWeaponCategory(Option<WeaponCategory>);
// /// Optionnal damage type
// #[derive(Clone, Default)]
// #[cfg_attr(test, derive(Debug, PartialEq))]
// pub struct OptionnalDamageType(Option<DamageType>);
/// Shape of the equipement, first mandatory part of an equipement
pub struct EqShape {
/// The inner stats of the part
@ -124,6 +129,9 @@ mod test {
assert_eq!(list_eq[0], eq1);
}
#[test]
fn test_creating_all_equipements() {}
#[ignore]
#[test]
fn test_default_behaviour() {

View File

@ -2,12 +2,24 @@
// File: weaponry/src/weaponry_structs/mod.rs
//! All weaponry intermod structures
#![allow(dead_code)]
// #![allow(dead_code)]
// use mimalloc::MiMalloc;
// #[global_allocator]
// static GLOBAL: MiMalloc = MiMalloc;
// #[cfg(not(target_env = "msvc"))]
// use tikv_jemallocator::Jemalloc;
// #[cfg(not(target_env = "msvc"))]
// #[global_allocator]
// static GLOBAL: Jemalloc = Jemalloc;
mod equipement_fields;
mod equipement_impl_database;
mod equipement_impl_io;
mod equipement_impl_logic;
mod equipement_impl_math;
pub mod equipement_structs;
// Republishes the most used symbols