Adds a lot ot the advanced representation #34

Merged
Dandaedre merged 1 commits from weapons into project_weaponry 2025-02-13 20:09:19 +01:00
10 changed files with 197 additions and 81 deletions

View File

@ -5,10 +5,13 @@ edition = "2024"
[dependencies]
fastrand = "2.3.0"
iter-enum = "1.2.0"
pretty_assertions = "1.4.1"
probability = "0.20.3"
rayon = "1.10.0"
rusqlite = { version = "0.33.0", features = ["bundled"] }
struct-field-names-as-array = "0.3.0"
strum = { version = "0.27.0", features = ["derive"] }
[dev-dependencies]
criterion = { version = "0.5" }

View File

@ -2,18 +2,18 @@ use criterion::{Criterion, criterion_group, criterion_main};
use std::{hint::black_box, time::Duration};
use weaponry::{
interfaces::RecipeCollection,
weaponry_structs::{Equipement, FinalEquipementList},
weaponry_structs::{Equipement, InitialEquipementList},
};
fn criterion_benchmark(c: &mut Criterion) {
let blk_steps = [
FinalEquipementList::from_vectored(vec![Equipement::default(); 100]),
FinalEquipementList::from_vectored(vec![Equipement::default(); 100]),
FinalEquipementList::from_vectored(vec![Equipement::default(); 100]),
InitialEquipementList::from_vectored(vec![Equipement::default(); 100]),
InitialEquipementList::from_vectored(vec![Equipement::default(); 100]),
InitialEquipementList::from_vectored(vec![Equipement::default(); 100]),
];
c.bench_function("creating 100 Elements", |b| {
b.iter(|| {
FinalEquipementList::from_vectored(black_box(vec![
InitialEquipementList::from_vectored(black_box(vec![
black_box(Equipement::default());
100
]))

View File

@ -6,18 +6,18 @@ use std::time::Instant;
use weaponry::{
interfaces::RecipeCollection,
weaponry_structs::{Equipement, FinalEquipementList},
weaponry_structs::{Equipement, InitialEquipementList},
};
fn main() {
let blk_steps = [
FinalEquipementList::from_vectored(
InitialEquipementList::from_vectored(
[1; 100].iter().map(|_| Equipement::default()).collect(),
),
FinalEquipementList::from_vectored(
InitialEquipementList::from_vectored(
[1; 100].iter().map(|_| Equipement::default()).collect(),
),
FinalEquipementList::from_vectored(
InitialEquipementList::from_vectored(
[1; 100].iter().map(|_| Equipement::default()).collect(),
),
];

View File

@ -5,7 +5,7 @@
//! Should dump whole database in a vec of structs from weaponry_structs
#![allow(dead_code)]
use crate::weaponry_structs::equipement_structs::InnerStats;
use crate::weaponry_structs::equipement_structs::InnerEquipementStats;
use rusqlite::{self, Connection, Result};
/// Generate a SELECT query with fields generated from a struct. Returns a String
@ -35,7 +35,7 @@ fn initialize_database_conn(filename: Option<String>) -> Result<Connection> {
}
/// Public function to get data from db
pub fn get_data() -> Vec<InnerStats> {
pub fn get_data() -> Vec<InnerEquipementStats> {
/* let gen_query = generate_query(&InnerStats::FIELD_NAMES_AS_ARRAY, "InnerStats");
let db_conn = initialize_database_conn(Some("/tmp/data.sqlite3".to_owned())).unwrap();
let mut query_result = db_conn.prepare(&gen_query);*/

View File

@ -37,7 +37,10 @@ pub trait ViewTable {
/// While it is possible to enforce from_recipe_collection, doing so would require the viewtable
/// lock itseld to a particular recipe.
/// While it is the case as of now, matters are not yet set in stone
pub trait RefinedList {}
pub trait RefinedList {
// Must implement From<RecipeCollection>, is it worth adding as a prerequite type ?
// type OriginCollection: Into<Self>;
}
/// Trait implemented for the final collection of a recipe, allowing it to be combined with parts
///
@ -148,6 +151,19 @@ pub trait DbSerializable {
fn from_database() -> Self;
}
/// Trait implemented by any struct aiming to be a public recipe
pub trait FixedRecipe: DbSerializable {
/// Struct representing the database type, most likely a string
type Database;
/// Struct representing the keylist type, most likely a usize
type KeyList;
/// Get the list of elements corresponding to the recipe
///
/// These elements will either be iteratively fetched from the database or scoured through in the data depending on the scenario
fn get_elements() -> Vec<(Self::Database, Self::KeyList)>;
}
// /// 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

View File

@ -9,31 +9,62 @@
//! of all the fields even when the user will not be interested in them
#![allow(dead_code)]
use crate::interfaces::RefinedList;
use core::f64;
use super::equipement_structs::InnerStats;
use crate::interfaces::RefinedList;
use probability::prelude::{Binomial, Discrete};
use strum::{EnumIter, IntoEnumIterator};
use super::{Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats};
/// The final representation of the equipement inplementing all the fields needed for processing
pub struct RefinedEquipement {
/// The original inner stats
///
/// This structs takes ownership of the inner data
inner: InnerStats,
inner: InnerEquipementStats,
/// Advanced stats
advanced: AdvancedStats,
}
pub struct RefinedEquipementList(Vec<RefinedEquipement>);
impl From<Equipement> for RefinedEquipement {
fn from(value: Equipement) -> Self {
Self {
advanced: AdvancedStats::from(&value.stats),
inner: value.stats,
}
}
}
/// The complete equipement list, refined with all advanced stats
pub struct RefinedEquipementList {
/// Inner list of Refined Equipements
inner: Vec<RefinedEquipement>,
}
// Just a checkmark
impl RefinedList for RefinedEquipementList {}
impl From<InitialEquipementList> for RefinedEquipementList {
fn from(value: InitialEquipementList) -> Self {
Self {
inner: value
.inner
.into_iter()
.map(RefinedEquipement::from)
.collect(),
}
}
}
/// The list of advanced stats infered from an Equipement
#[allow(missing_docs, clippy::missing_docs_in_private_items)]
pub struct AdvancedStats {
damage_per_attack: f64,
damage_per_turn: f64,
damage_per_action: f64,
armor_break_per_attack: f64,
armor_break_per_turn: f64,
armor_break_per_action: f64,
damage_matrix: DamageMatrix,
@ -41,6 +72,26 @@ pub struct AdvancedStats {
expected_armor_break_per_turn: f64,
// All other criterias are already in the inner as raw criterias
}
impl From<&InnerEquipementStats> for AdvancedStats {
fn from(value: &InnerEquipementStats) -> Self {
let damage_per_attack = (value.damage + value.p_damage * (value.rmax - 1)) as f64;
let armor_break_per_attack = (value.armor_break as f64).min(damage_per_attack);
Self {
damage_per_attack,
damage_per_turn: damage_per_attack * 2.,
damage_per_action: damage_per_attack / (value.action_cost as f64),
armor_break_per_attack,
armor_break_per_turn: armor_break_per_attack * 2.,
armor_break_per_action: armor_break_per_attack / value.action_cost as f64,
// Adds the base strength, substracts the expected protection
expected_armor_break_per_turn: (damage_per_attack + 6. - 8.)
.min(armor_break_per_attack),
damage_matrix: value.into(),
// armor_break_matrix: ,
}
}
}
/// A damage matrix, crossing damage conditions (high dice to low dice) with precision (high precision to low precision)
///
@ -52,48 +103,92 @@ struct DamageMatrix {
impl DamageMatrix {
/// Get the damage value from given condition
pub fn get_damage(&self, precision: Precision, dices: DiceNumber) -> f64 {
self.damage_matrix[precision.index() + 3 * dices.index()]
self.damage_matrix[precision as usize + 3 * dices as usize]
}
/// Calculate the damage simulation from a given InnerStats
pub fn calculate_damage(inner: &InnerStats) -> Self {
let _ = inner;
todo!()
}
impl From<&InnerEquipementStats> for DamageMatrix {
fn from(value: &InnerEquipementStats) -> Self {
// let binomial_distribution = Binomial::new(dices, value.precision);
// binomial_distribution.mass(i) // -> The chance to have this number of success
DamageMatrix {
damage_matrix: (Precision::iter()
.flat_map(|precision| {
DiceNumber::iter()
.map(move |dices| {
binomial_dice_distribution(value, precision.value(), dices.value())
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>()),
}
}
}
/// Calculate the binomial distribution and average the damage from there
fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, dices: usize) -> f64 {
let binomial = Binomial::new(dices, (precision as u8 + value.precision) as f64);
(0..dices + 1)
.map(|target_dices| {
// TODO: This non rounding can be veird
let number_success = binomial.mass(target_dices); // Let's have weird half dices as usize;
if number_success >= 1. {
(value.damage + value.p_damage) as f64 * (number_success - 1.)
} else {
0.
}
})
.fold(0., |a, b| a + b)
/ dices as f64
}
/// The precision infered for a damage calculation event
#[derive(EnumIter, Clone, Copy)]
#[allow(clippy::missing_docs_in_private_items)]
pub enum Precision {
High = 9,
Medium = 6,
Low = 3,
High,
Medium,
Low,
}
/// The number of dices rolled for a damage simulation
#[derive(EnumIter, Clone, Copy)]
#[allow(clippy::missing_docs_in_private_items)]
pub enum DiceNumber {
High = 7,
Medium = 5,
Low = 3,
High,
Medium,
Low,
}
impl Precision {
#[inline]
/// Associate an index to the different values
fn index(&self) -> usize {
/// Associate a value to the different values
fn value(&self) -> usize {
match self {
Precision::High => 0,
Precision::Medium => 1,
Precision::Low => 2,
Precision::High => 9,
Precision::Medium => 6,
Precision::Low => 3,
}
}
}
impl DiceNumber {
#[inline]
/// Associate an index to the different values
fn index(&self) -> usize {
/// Associate a value to the different values
fn value(&self) -> usize {
match self {
DiceNumber::High => 0,
DiceNumber::Medium => 1,
DiceNumber::Low => 2,
DiceNumber::High => 7,
DiceNumber::Medium => 5,
DiceNumber::Low => 3,
}
}
}
#[cfg(test)]
mod test {
#[test]
fn test_binomial() {}
#[test]
fn test_creation() {}
}

View File

@ -4,10 +4,10 @@
use crate::interfaces::{Combinable, RecipeCollection};
use super::{Equipement, FinalEquipementList, equipement_structs::InnerStats};
use super::{Equipement, InitialEquipementList, equipement_structs::InnerEquipementStats};
impl Combinable for Equipement {
type Inner = InnerStats;
type Inner = InnerEquipementStats;
fn combinable_part(&self) -> &Self::Inner {
&self.stats
@ -31,7 +31,7 @@ impl Combinable for Equipement {
}
}
impl RecipeCollection for FinalEquipementList {
impl RecipeCollection for InitialEquipementList {
type Recipes = Equipement;
fn from_vectored(list: Vec<Self::Recipes>) -> Self {
@ -52,19 +52,19 @@ mod test {
use crate::{
interfaces::RecipeCollection,
weaponry_structs::{
DamageMod, DamageType, Equipement, FinalEquipementList, SpecialCategory,
WeaponCategory, equipement_fields::PhysicalDamageType, equipement_structs::InnerStats,
DamageMod, DamageType, Equipement, InitialEquipementList, SpecialCategory,
WeaponCategory, equipement_fields::PhysicalDamageType, equipement_structs::InnerEquipementStats,
},
};
use pretty_assertions::assert_eq;
#[test]
fn test_blanket_struct_generation() {
let mut f = FinalEquipementList::from_vectored(vec![
let mut f = InitialEquipementList::from_vectored(vec![
Equipement::newish(&["a"], 1),
Equipement::newish(&["b"], 2),
]);
let g = FinalEquipementList::from_vectored(vec![
let g = InitialEquipementList::from_vectored(vec![
Equipement::newish(&["c"], 4),
Equipement::newish(&["d"], 8),
]);
@ -77,7 +77,7 @@ mod test {
f.combine_all(&g);
assert_eq!(
f,
FinalEquipementList::from_vectored(vec![
InitialEquipementList::from_vectored(vec![
Equipement::newish(&["a", "c"], 5),
Equipement::newish(&["a", "d"], 9),
Equipement::newish(&["b", "c"], 6),
@ -88,7 +88,7 @@ mod test {
#[test]
fn test_base_operation() {
let i1 = InnerStats {
let i1 = InnerEquipementStats {
rarity: 1,
integrity: 2,
range: 3,
@ -100,7 +100,7 @@ mod test {
)])),
..Default::default()
};
let i2 = InnerStats {
let i2 = InnerEquipementStats {
integrity: 3,
agility_bonus: 5,
damage: 10,
@ -112,7 +112,7 @@ mod test {
};
assert_eq!(
&i1 + &i2,
InnerStats {
InnerEquipementStats {
rarity: 1,
integrity: 5,
agility_bonus: 9,
@ -128,14 +128,14 @@ mod test {
}
);
assert_eq!(
&InnerStats {
&InnerEquipementStats {
damage_type: Some(DamageType(vec![
DamageMod::Secondary(PhysicalDamageType::Slash,),
DamageMod::Primary(PhysicalDamageType::Blunt,),
])),
..Default::default()
} + &InnerStats::default(),
InnerStats {
} + &InnerEquipementStats::default(),
InnerEquipementStats {
damage_type: Some(DamageType(vec![
DamageMod::Secondary(PhysicalDamageType::Slash,),
DamageMod::Primary(PhysicalDamageType::Blunt,),
@ -144,15 +144,15 @@ mod test {
},
);
assert_eq!(
&InnerStats::default()
+ &InnerStats {
&InnerEquipementStats::default()
+ &InnerEquipementStats {
damage_type: Some(DamageType(vec![
DamageMod::Secondary(PhysicalDamageType::Slash,),
DamageMod::Primary(PhysicalDamageType::Blunt,),
])),
..Default::default()
},
InnerStats {
InnerEquipementStats {
damage_type: Some(DamageType(vec![
DamageMod::Secondary(PhysicalDamageType::Slash,),
DamageMod::Primary(PhysicalDamageType::Blunt,),
@ -173,7 +173,7 @@ mod test {
impl Equipement {
fn newish(name: &[&str], i: u8) -> Self {
Equipement {
stats: InnerStats {
stats: InnerEquipementStats {
name: name.iter().map(|s| s.to_string()).collect(),
rarity: i,
..Default::default()

View File

@ -3,7 +3,7 @@
//! Implements base math for each field
//!
use super::equipement_structs::InnerStats;
use super::equipement_structs::InnerEquipementStats;
use crate::weaponry_structs::SpecialCategory;
/// Add a new vector to a clone of a inner field
@ -30,11 +30,11 @@ macro_rules! add_two_options {
}};
}
impl std::ops::Add for &InnerStats {
type Output = InnerStats;
impl std::ops::Add for &InnerEquipementStats {
type Output = InnerEquipementStats;
fn add(self, rhs: Self) -> Self::Output {
InnerStats {
InnerEquipementStats {
// TODO: Decide the behaviour of ids, as uuid are useless but this is even more useless
id: add_to_vec!(self.id, rhs.id),
name: add_to_vec!(self.name, rhs.name),

View File

@ -15,7 +15,7 @@ use super::{DamageType, SpecialCategory, WeaponCategory};
/// This list is initialized with the base part and updated by succesive combinaisons
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct FinalEquipementList {
pub struct InitialEquipementList {
/// Inner List of final equipements
pub(super) inner: Vec<Equipement>,
}
@ -25,22 +25,23 @@ pub struct FinalEquipementList {
#[cfg_attr(test, derive(PartialEq))]
pub struct Equipement {
/// The inner stats used by the equipement
pub(super) stats: InnerStats,
pub(super) stats: InnerEquipementStats,
/// The filter, used to determine if adding is warranted
pub(super) filter_function: FilterFunction<InnerStats>,
pub(super) filter_function: FilterFunction<InnerEquipementStats>,
}
impl Default for Equipement {
fn default() -> Self {
Self {
filter_function: FilterFunction::new(default_filter()),
stats: InnerStats::random_new(),
stats: InnerEquipementStats::random_new(),
}
}
}
/// The default filter to use, usefull to implement a new filter function that also uses the default filter
pub(crate) fn default_filter() -> &'static impl Fn(&InnerStats, &InnerStats) -> bool {
pub(crate) fn default_filter()
-> &'static impl Fn(&InnerEquipementStats, &InnerEquipementStats) -> bool {
&|self_, lhs| !self_.id.iter().any(|a| *a == lhs.id[0])
}
@ -56,7 +57,7 @@ impl<T> FilterFunction<T> {
#[allow(clippy::missing_docs_in_private_items, missing_docs)]
#[derive(Clone, Default, FieldNamesAsArray, Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct InnerStats {
pub struct InnerEquipementStats {
pub id: Vec<u8>,
pub name: Vec<String>,
pub(super) rarity: u8,
@ -89,7 +90,7 @@ pub struct InnerStats {
}
// TODO: Make this a test requirement or hide it behind a profile
impl InnerStats {
impl InnerEquipementStats {
/// Testing function to fuzz data
pub fn random_new() -> Self {
Self {
@ -102,13 +103,13 @@ impl InnerStats {
/// Shape of the equipement, first mandatory part of an equipement
pub struct EqShape {
/// The inner stats of the part
pub(super) stats: InnerStats,
pub(super) stats: InnerEquipementStats,
}
/// Material used for the equipement, all equipements are crafted with 1-2 materials
pub struct EqMaterial {
/// The inner stats of the part
pub(super) stats: InnerStats,
pub(super) stats: InnerEquipementStats,
}
/// Nature of the equipement, some natures are reserved and some can be chained
@ -116,13 +117,13 @@ pub struct EqMaterial {
/// Deciding on the combinaison can be tricky an will need an extra field
pub struct EqNature {
/// The inner stats of the part
pub(super) stats: InnerStats,
pub(super) stats: InnerEquipementStats,
}
/// Finishing touches, since all of them have a cost, they are treated in a special fashion
pub struct EqFinishing {
/// The inner stats of the part
pub(super) stats: InnerStats,
pub(super) stats: InnerEquipementStats,
}
#[cfg(test)]
@ -132,7 +133,8 @@ mod test {
use crate::interfaces::RecipeCollection;
use super::{
EqFinishing, EqMaterial, EqNature, EqShape, Equipement, FinalEquipementList, InnerStats,
EqFinishing, EqMaterial, EqNature, EqShape, Equipement, InitialEquipementList,
InnerEquipementStats,
};
// use pretty_assertions::assert_eq;
@ -147,7 +149,7 @@ mod test {
#[test]
fn test_struct_creation() {
let _stats = InnerStats::default();
let _stats = InnerEquipementStats::default();
let _eq1 = Equipement {
..Default::default()
};
@ -159,33 +161,33 @@ mod test {
fn test_creating_all_equipements() {
let shape = vec![
EqShape {
stats: InnerStats::default(),
stats: InnerEquipementStats::default(),
}
.into(),
];
let nature = vec![
EqNature {
stats: InnerStats::default(),
stats: InnerEquipementStats::default(),
}
.into(),
];
let material = vec![
EqMaterial {
stats: InnerStats::default(),
stats: InnerEquipementStats::default(),
}
.into(),
];
let finishing = vec![
EqFinishing {
stats: InnerStats::default(),
stats: InnerEquipementStats::default(),
}
.into(),
];
let mut leq = FinalEquipementList::from_vectored(shape);
leq.combine_all(&FinalEquipementList::from_vectored(nature));
leq.combine_all(&FinalEquipementList::from_vectored(material));
leq.combine_all(&FinalEquipementList::from_vectored(finishing));
let mut leq = InitialEquipementList::from_vectored(shape);
leq.combine_all(&InitialEquipementList::from_vectored(nature));
leq.combine_all(&InitialEquipementList::from_vectored(material));
leq.combine_all(&InitialEquipementList::from_vectored(finishing));
}
#[ignore]

View File

@ -29,7 +29,7 @@ mod equipement_views;
// Republishes the most used symbols
// All generic structs
pub use equipement_structs::{Equipement, FinalEquipementList};
pub use equipement_structs::{Equipement, InitialEquipementList};
// All generic fields
#[allow(unused_imports)]