From 5738f0fd74ff34d3916cfc37b67526c9cbfad51f Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 20 Feb 2025 02:20:05 +0100 Subject: [PATCH 1/4] Wip on the firt import fn --- more_fields/Cargo.toml | 2 + weaponry/Cargo.toml | 3 +- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/.rustfmt.toml | 1 + weaponry/examples/serde_loading.rs | 175 ++++++++++++++++++++++------- 5 files changed, 141 insertions(+), 40 deletions(-) create mode 100644 weaponry/examples/.rustfmt.toml diff --git a/more_fields/Cargo.toml b/more_fields/Cargo.toml index ba443ad..1c83567 100644 --- a/more_fields/Cargo.toml +++ b/more_fields/Cargo.toml @@ -5,6 +5,8 @@ version.workspace = true [dependencies] more_fields_macro = {path ="../more_fields_macro"} + +[dev-dependencies] pretty_assertions = "1.4.1" [features] diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 915b59d..56c961e 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -8,7 +8,6 @@ more_fields = {path ="../more_fields"} comfy-table = "7.1.4" csv = "1.3.1" fastrand = "2.3.0" -pretty_assertions = "1.4.1" probability = "0.20.3" rusqlite = { version = "0.33.0" } # , features = ["bundled"] serde = { version = "1.0.217", features = ["derive"] } @@ -19,6 +18,8 @@ thiserror = "2.0.11" [dev-dependencies] criterion = { version = "0.5" } +regex = "1.11.1" +pretty_assertions = "^1.4" [[bench]] name = "iter_creation" diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index f0862ffbb83007ef0f13f8c1e7db1b49184fdc40..5fea0f35eea85fe0ae67cd0919efb5579bfde3e7 100644 GIT binary patch delta 671 zcmZXRKTpCy7>9d*fIGA;Xb2&gpd^kYKwKS4qq3N|8xt!Yk))_;X>==&ZaOpRq;WEi zj(iCw!#D6N_+DE=@osq28{VhS?|0)l8qd*F70sTvY&82ke=#eXrg43uncwEUxo7+u zAI7DztN-Yeubsk!9$LJnm8&c{h_NDqAy2hbWF^K9Z@i(fykX!8pEO!HU$AkzjTTwkP$(S&luBg6Wv18!L{?0ukGIozK?rHmbyHzj z7#Q%3QK?IlMVdkKz+J~5Q7k?3s)vo1X&}#{5yV$Kj=Vv?FMLefm}H3}^16NU2Xaw} AWdHyG delta 483 zcmZp8z}WDBae_3X!9*EnMuUwB3;9L))-tg21u^j7=eOhE!C%K01cI9d6>RwGBO2@E z8F+a)fPj$^L~@ujfhi6SSy^=sK}HVlyy$ABfTGOY#G*8V9ZFgjW(FF#*NM=1$N#u^%_GB7YqgqjR7(i~y|+~jPA7xh@pHi8)mqtT3x1R8w< z)o7Tbd4a;bj2zw!AF-Hhrzp=L4e={Py=XnmNur{H9HLAdu7$xFi3O>83_tQpb8_N9 z1PDjRf=Gsw=8ep-&|-q<1nPkRumOx53|BqDO7Ej;Wm46LYlP?kIuZyBff(v!hKmeu ZjqT+bVCo>oa)6x+VuO`&a4b>?000xhVN?JB diff --git a/weaponry/examples/.rustfmt.toml b/weaponry/examples/.rustfmt.toml new file mode 100644 index 0000000..98b9e7f --- /dev/null +++ b/weaponry/examples/.rustfmt.toml @@ -0,0 +1 @@ +max_width = 278 diff --git a/weaponry/examples/serde_loading.rs b/weaponry/examples/serde_loading.rs index d9dde9f..c5de52f 100644 --- a/weaponry/examples/serde_loading.rs +++ b/weaponry/examples/serde_loading.rs @@ -4,31 +4,92 @@ //! use more_fields::FieldsAsSlice; +use serde::Serialize; use serde_rusqlite::to_params_named; use weaponry::interfaces::RecipeDatabase; +use weaponry::weaponry_structs::WeaponCategory; use weaponry::weaponry_structs::equipement_impl_database::EquipementDatabase; -use weaponry::weaponry_structs::equipement_structs::{ - DatabaseEquipementStats, InnerEquipementStats, -}; +use weaponry::weaponry_structs::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}; +// const BASE_DATA: &[[&str; 17]] = &[ +// // {Forme} & {Maniement} & {\damagew} & + & {R.Max} & \arbreakw & \protection & \integrite & $\mathbb{T}$2 & $\mathbb{T}$1 & {Modes} & {Esq.} & {Par.} & {Vit.} & {Disc.} & {Spécial} & {Diff.} \\ +// // % Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff +// ["Griffes", "Tranchantes", "2", "1", "4", "1", "1", "2", "3", "6", "slash", "2", "0", "3", "1", "-", "1"], +// ["Hast", "Hast", "4", "1", "2", "1", "4", "3", "10", "18", "pierce, [slash]", "-1", "-3", "1", "0", "-", "1"], +// ["Épée", "Tranchantes", "3", "1", "3", "1", "3", "4", "12", "15", "slash, [pierce]", "0", "1", "0", "0", "-", "1"], +// ["Marteau", "Contondantes", "5", "1", "1", "1", "4", "3", "11", "18", "blunt", "-1", "-1", "0", "-2", "-", "1"], +// ["Hache", "Tranchantes", "4", "2", "1", "3", "4", "3", "9", "14", "slash", "0", "-1", "1", "0", "-", "1"], +// ["Arbalète", "Distance", "4", "1", "3", "0", "3", "1", "8", "16", "pierce", "-1", "-1", "0", "-1", "2reload, Gls{parmure} 2, 80m", "1"], +// ["Arc", "Distance", "3", "1", "4", "0", "2", "1", "-", "7", "pierce", "0", "0", "0", "0", "1reload, Gls{parmure} 2, 120m", "1"], +// ["Biers", " -", "1", "1", "2", "0", "3", "2", "6", "8", "blunt", "-2", "0", "-1", "-2", "-", "1"], +// ["Armures", " -", " ", " ", " ", " ", "3", "2", "10", "-", "blunt", "-1", "0", "0", "-1", "-", "1"], +// // % "Explosive" , "Exotiques", "3", "1" , "3", "1", "2", "2", "20" , "10" , "slash", "0", "0", "0", "0" , "-" , "ddlvl{5}" +// // % "Flexible", "Exotiques", "3", "1" , "3", "1", "2", "2", "20" , "10" , "slash", "0", "0", "0", "0" , "-" , "ddlvl{2}" +// // % "Exotique", "Exotiques", "3", "1" , "3", "1", "2", "2", "20" , "10" , "slash", "0", "0", "0", "0" , - , "ddlvl{3}" +// ]; +// +const BASE_FORME: &[&str] = &[ + // "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ", + "Griffes & Tranchantes & 2 & 1 & 4 & 1 & 1 & 2 & 3 & 6 & slash & 2 & 0 & 3 & 1 & - & ddlvl{1} ", + "Hast & Hast & 4 & 1 & 2 & 1 & 4 & 3 & 10 & 18 & pierce, [slash] & -1 & -3 & 1 & 0 & - & ddlvl{1} ", + "Épée & Tranchantes & 3 & 1 & 3 & 1 & 3 & 4 & 12 & 15 & slash, [pierce] & 0 & 1 & 0 & 0 & - & ddlvl{1} ", + "Marteau & Contondantes & 5 & 1 & 1 & 1 & 4 & 3 & 11 & 18 & blunt & -1 & -1 & 0 & -2 & - & ddlvl{1} ", + "Hache & Tranchantes & 4 & 2 & 1 & 3 & 4 & 3 & 9 & 14 & slash & 0 & -1 & 1 & 0 & - & ddlvl{1} ", + "Arbalète & Distance & 4 & 1 & 3 & 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ", + "Arc & Distance & 3 & 1 & 4 & 0 & 2 & 1 & - & 7 & pierce & 0 & 0 & 0 & 0 & 1reload, Gls{parmure} 2, 120m & ddlvl{1} ", + "Boucliers & - & 1 & 1 & 2 & 0 & 3 & 2 & 6 & 8 & blunt & -2 & 0 & -1 & -2 & - & ddlvl{1} ", + "Armures & - & & & & & 3 & 2 & 10 & - & blunt & -1 & 0 & 0 & -1 & - & ddlvl{1} ", + // "% Explosive & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{5} ", + // "% Flexible & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{2} ", + // "% Exotique & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{3} ", +]; fn main() { - let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); - let mut data_eg = DatabaseEquipementStats::random_new(); - // data_eg.id = fastrand::u8(1..u8::MAX); - // data_eg.damage_type = serde_json::to_string(&Some(DamageType(vec![DamageMod::Primary( - // PhysicalDamageType::Blunt, - // )]))) - // .unwrap(); - // data_eg.category = serde_json::to_string(&Some(WeaponCategory::Dagger)).unwrap(); - // data_eg.target = serde_json::to_string(&Some(WeaponCategory::Dagger)).unwrap(); - // data_eg.special = - // serde_json::to_string(&SpecialCategory(vec!["noo".to_string(), "boo".to_string()])) - // .unwrap(); - // data_eg.reload_cost = serde_json::to_string(&Some(12)).unwrap(); - data_eg.id = fastrand::u8(1..u8::MAX); + let mut global_index = 0; + let b = load_base(&mut global_index); + // println!("{b:?}"); // Equipements - db.initialize_empty_table::("Equipements") - .unwrap(); + let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); + db.initialize_empty_table::("Equipements").unwrap(); + db.conn.execute("DELETE FROM Equipements", []).unwrap(); + println!("Processed {global_index} ids"); + b.iter().for_each(|v| database_shnn(&db, v)); + let v = db.serialize_vec_from_table::("Equipements", None); + println!("{:#?}", v); + + // Final deserialisation + let final_s = v.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::>(); + let v = final_s + .iter() + .scan(0, |status, eq| { + if eq.is_ok() { + *status += 1; + } + Some(*status) + }) + .sum::(); + println!("{:#?}, {:#?}", final_s, v); +} + +#[allow(dead_code)] +#[derive(Default)] +struct FoundFields { + reload: Option, + range: Option, + parmor: Option, +} +fn parse_special_field(fields: &str) -> FoundFields { + // "Arbalète & Distance & 4 & 1 & 3 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ", + let re = regex::Regex::new(r"((?\d)reload)?(, )?(Gls\{parmure\} (?\d))?(, )?(?(\d+)m)?").unwrap(); + re.captures(fields).map_or(FoundFields::default(), |f| FoundFields { + reload: f.name("reload").map(|n| n.as_str().parse().unwrap()), + range: f.name("range").map(|v| v.as_str().parse().unwrap()), + parmor: f.name("parmor").map(|v| v.as_str().parse().unwrap()), + }) +} + +#[allow(dead_code)] +fn database_shnn(db: &EquipementDatabase, row: T) { + // let mut row = DatabaseEquipementStats::random_new(); let sql = &format!( "INSERT INTO Equipements ({}) VALUES ({})", @@ -45,24 +106,60 @@ fn main() { .collect::>() .join(", ") ); - println!("{}", sql); - let r = db.conn.execute( - sql, - to_params_named(&data_eg).unwrap().to_slice().as_slice(), - ); - println!("{:?}", r); - - let v = db.serialize_vec_from_table::("Equipements", None); - // println!("{:#?}", v); - - println!( - "{:#?}", - v.unwrap() - .into_iter() - .map(InnerEquipementStats::try_from) - .collect::>() - ); - // let mut r = db.conn.prepare("SELECT * FROM InnerStats").unwrap(); - // let mut v = r.query([]).unwrap(); - // println!("{:?}:\n {:#?}", db, r); + // println!("{}", sql); + let r = db.conn.execute(sql, to_params_named(&row).unwrap().to_slice().as_slice()); + println!("Loaded {:?} entries into the database", r); +} + +fn load_base(index: &mut u8) -> Vec { + // data_eg.id = fastrand::u8(1..u8::MAX); + // data_eg.damage_type = serde_json::to_string(&Some(DamageType(vec![DamageMod::Primary( + // PhysicalDamageType::Blunt, + // )]))) + // .unwrap(); + // data_eg.category = serde_json::to_string(&Some(WeaponCategory::Dagger)).unwrap(); + // data_eg.target = serde_json::to_string(&Some(WeaponCategory::Dagger)).unwrap(); + // data_eg.special = + // serde_json::to_string(&SpecialCategory(vec!["noo".to_string(), "boo".to_string()])) + // .unwrap(); + // data_eg.reload_cost = serde_json::to_string(&Some(12)).unwrap(); + BASE_FORME + .iter() + .map(|row| { + let fields = row.split("&").map(|field| field.trim()).collect::>(); + let FoundFields { reload, range, parmor } = parse_special_field(fields[16]); + *index += 1; + DatabaseEquipementStats { + id: *index, + meta_category: "Forme".into(), + name: fields[0].to_string(), + category: format!("\"{}\"", fields[1]), + rarity: 0, + cost: 0, + difficulty: fields[16].parse().unwrap_or_default(), + tier: 0, + damage: fields[2].parse().unwrap_or_default(), + p_damage: fields[3].parse().unwrap_or_default(), + precision: fields[4].parse().unwrap_or_default(), + rmax: fields[5].parse().unwrap_or_default(), + armor_break: fields[6].parse().unwrap_or_default(), + protection: fields[7].parse().unwrap_or_default(), + integrity: fields[8].parse().unwrap_or_default(), + + torque_two_handed: fields[10].parse().unwrap_or_default(), + torque_one_handed: fields[9].parse().unwrap_or_default(), // The or default is a problem + damage_type: fields[11].parse().unwrap(), + + dodge: fields[12].parse().unwrap_or_default(), + parry: fields[13].parse().unwrap_or_default(), + speed: fields[14].parse().unwrap_or_default(), + stealth: fields[15].parse().unwrap_or_default(), + reload_cost: serde_json::to_string(&reload).unwrap(), + range: range.unwrap_or_default(), + + // target: fields[5].parse().unwrap(), // Armors ? + ..Default::default() + } + }) + .collect::>() } -- 2.45.1 From a2269ccb87f433f27f76c153cc41df5e9e3f185d Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 21 Feb 2025 01:22:54 +0100 Subject: [PATCH 2/4] A lot of shitcode to get the first import working --- weaponry/Cargo.toml | 2 + weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes .../{serde_loading.rs => first_import.rs} | 121 +++++++++++------- weaponry/src/database.rs | 9 +- weaponry/src/error.rs | 6 + .../src/weaponry_structs/equipement_fields.rs | 81 +++++++++++- .../equipement_impl_basics.rs | 2 +- .../equipement_impl_database.rs | 26 ++-- .../weaponry_structs/equipement_impl_logic.rs | 6 +- .../weaponry_structs/equipement_impl_math.rs | 7 +- .../weaponry_structs/equipement_structs.rs | 26 ++-- weaponry/src/weaponry_structs/mod.rs | 4 +- 12 files changed, 206 insertions(+), 84 deletions(-) rename weaponry/examples/{serde_loading.rs => first_import.rs} (62%) diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index 56c961e..ae487b4 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -15,11 +15,13 @@ serde_rusqlite = "0.37.0" serde_json = { version = "1.0.138", features = ["alloc"] } strum = { version = "0.27.0", features = ["derive"] } thiserror = "2.0.11" +regex = "1.11.1" [dev-dependencies] criterion = { version = "0.5" } regex = "1.11.1" pretty_assertions = "^1.4" +logos = "^0.15" [[bench]] name = "iter_creation" diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index 5fea0f35eea85fe0ae67cd0919efb5579bfde3e7..6d0843fc1fb807b939f132659d4bc921cab0bcda 100644 GIT binary patch delta 1002 zcmZ{iUu)A)7{+swv`yA#X(qL38J+2ECr#D1+m#(mcQYvK&}tbaOV4aEO}hLMWlAb| zp?B)=R?rL4t63`e0g88i1;@k>uq*FW7p{deo2!k@ zyrmnvHg4$}Zgpg>joSIqoZ`aIwU}=u+}c;`}W( zOQbW*n_KStE(4UT z3t?FX!3QWj@9wiHfk`pU4c+MB72Q_UE;dZ^Kj>0LtarLtZJWS$0{BJ@;OATz^5IK} z_2KgX=aCPu8VW^EacfXY!JwI3EQ=emb`Q5tBufwPL<7Mgrr_2%Wjdg^YHZ8u_@jks z>TEPskxJ9-V(oSW*lABMVpwp)H3QfzlL?uzCMz9GlhfR~Dw`cpOjApeb5-=W6Pp_} zkiB7nYH->m3!dsQd0jRvEZdPO#lie&N|L0?$v7uuodWU&PcwK7WQ-ga4S!+u_(gyG z2~%f^&hLqJtms#=Kb};AJ4=3!2kdN delta 899 zcmZ{iy>HV%7{>2>j&n|GJ4p$qR3cwOLV}n@FB9iT-wxd>E z(nuiDjgYY$6CV@G21}*<6D&j(J7r=;ymnHOV)dl=d}sUlJFlBmAt#xpFNZo3W$r2QFJVQ{M;Tz@ovBO$P!fVRfKMw6VwM8jG9)1?KoRT z(`7ZiLZPl`vz2@q!Q!CEa!c|#N?=GDwa+$f>0D*rc2obg4+kNut{9;(mWbppB zt8W@?hMTQIm8Vs0y_#Ov%8#q*?Ce1{eI+7hn=jY+u$s%^*XHnxRKtTq`txlpl#~vT z@>SVUZpy#pPjW-PERCguVLaWFx|*0m>N1@UOlcg$DrZ>~~6q&$fzVmd|mka#yidMwhxVJaCdaYP^! m::try_into(&lex.slice()[2..lex.slice().len()-2]).unwrap())] + Tertiary(PhysicalDamageType), + #[regex(r"\[\w+\]", |lex| std::convert::TryInto::::try_into(&lex.slice()[1..lex.slice().len()-1]).unwrap())] + Secondary(PhysicalDamageType), + #[regex(r"\w+", |lex| std::convert::TryInto::::try_into(lex.slice()).unwrap())] + Primary(PhysicalDamageType), +} +// let b = DamageMod::Primary() -// const BASE_DATA: &[[&str; 17]] = &[ -// // {Forme} & {Maniement} & {\damagew} & + & {R.Max} & \arbreakw & \protection & \integrite & $\mathbb{T}$2 & $\mathbb{T}$1 & {Modes} & {Esq.} & {Par.} & {Vit.} & {Disc.} & {Spécial} & {Diff.} \\ -// // % Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff -// ["Griffes", "Tranchantes", "2", "1", "4", "1", "1", "2", "3", "6", "slash", "2", "0", "3", "1", "-", "1"], -// ["Hast", "Hast", "4", "1", "2", "1", "4", "3", "10", "18", "pierce, [slash]", "-1", "-3", "1", "0", "-", "1"], -// ["Épée", "Tranchantes", "3", "1", "3", "1", "3", "4", "12", "15", "slash, [pierce]", "0", "1", "0", "0", "-", "1"], -// ["Marteau", "Contondantes", "5", "1", "1", "1", "4", "3", "11", "18", "blunt", "-1", "-1", "0", "-2", "-", "1"], -// ["Hache", "Tranchantes", "4", "2", "1", "3", "4", "3", "9", "14", "slash", "0", "-1", "1", "0", "-", "1"], -// ["Arbalète", "Distance", "4", "1", "3", "0", "3", "1", "8", "16", "pierce", "-1", "-1", "0", "-1", "2reload, Gls{parmure} 2, 80m", "1"], -// ["Arc", "Distance", "3", "1", "4", "0", "2", "1", "-", "7", "pierce", "0", "0", "0", "0", "1reload, Gls{parmure} 2, 120m", "1"], -// ["Biers", " -", "1", "1", "2", "0", "3", "2", "6", "8", "blunt", "-2", "0", "-1", "-2", "-", "1"], -// ["Armures", " -", " ", " ", " ", " ", "3", "2", "10", "-", "blunt", "-1", "0", "0", "-1", "-", "1"], -// // % "Explosive" , "Exotiques", "3", "1" , "3", "1", "2", "2", "20" , "10" , "slash", "0", "0", "0", "0" , "-" , "ddlvl{5}" -// // % "Flexible", "Exotiques", "3", "1" , "3", "1", "2", "2", "20" , "10" , "slash", "0", "0", "0", "0" , "-" , "ddlvl{2}" -// // % "Exotique", "Exotiques", "3", "1" , "3", "1", "2", "2", "20" , "10" , "slash", "0", "0", "0", "0" , - , "ddlvl{3}" -// ]; -// const BASE_FORME: &[&str] = &[ // "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ", + // "Name & Type & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & mode & 9 & 10 & 11 & 12 & 3reload, & ddlvl{13} ", "Griffes & Tranchantes & 2 & 1 & 4 & 1 & 1 & 2 & 3 & 6 & slash & 2 & 0 & 3 & 1 & - & ddlvl{1} ", "Hast & Hast & 4 & 1 & 2 & 1 & 4 & 3 & 10 & 18 & pierce, [slash] & -1 & -3 & 1 & 0 & - & ddlvl{1} ", "Épée & Tranchantes & 3 & 1 & 3 & 1 & 3 & 4 & 12 & 15 & slash, [pierce] & 0 & 1 & 0 & 0 & - & ddlvl{1} ", @@ -37,8 +33,8 @@ const BASE_FORME: &[&str] = &[ "Hache & Tranchantes & 4 & 2 & 1 & 3 & 4 & 3 & 9 & 14 & slash & 0 & -1 & 1 & 0 & - & ddlvl{1} ", "Arbalète & Distance & 4 & 1 & 3 & 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ", "Arc & Distance & 3 & 1 & 4 & 0 & 2 & 1 & - & 7 & pierce & 0 & 0 & 0 & 0 & 1reload, Gls{parmure} 2, 120m & ddlvl{1} ", - "Boucliers & - & 1 & 1 & 2 & 0 & 3 & 2 & 6 & 8 & blunt & -2 & 0 & -1 & -2 & - & ddlvl{1} ", - "Armures & - & & & & & 3 & 2 & 10 & - & blunt & -1 & 0 & 0 & -1 & - & ddlvl{1} ", + "Boucliers & Boucliers & 1 & 1 & 2 & 0 & 3 & 2 & 6 & 8 & blunt & -2 & 0 & -1 & -2 & - & ddlvl{1} ", + "Armures & Armures & & & & & 3 & 2 & 10 & - & blunt & -1 & 0 & 0 & -1 & - & ddlvl{1} ", // "% Explosive & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{5} ", // "% Flexible & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{2} ", // "% Exotique & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{3} ", @@ -51,23 +47,26 @@ fn main() { let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); db.initialize_empty_table::("Equipements").unwrap(); db.conn.execute("DELETE FROM Equipements", []).unwrap(); - println!("Processed {global_index} ids"); + println!("Added {global_index} ids to the new database"); b.iter().for_each(|v| database_shnn(&db, v)); let v = db.serialize_vec_from_table::("Equipements", None); - println!("{:#?}", v); - + // println!("Initial deserialisation in DatabaseEquipementStats: {:?}", v); + println!("First entry: {:?}", v.as_ref().unwrap()[0]); // Final deserialisation let final_s = v.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::>(); let v = final_s .iter() .scan(0, |status, eq| { if eq.is_ok() { - *status += 1; + *status = 1; + } else { + *status = 0; } Some(*status) }) .sum::(); - println!("{:#?}, {:#?}", final_s, v); + println!("Final data {:#?}", final_s); + println!("Succeded in parsing {:#?} over {}", v, global_index); } #[allow(dead_code)] @@ -79,7 +78,7 @@ struct FoundFields { } fn parse_special_field(fields: &str) -> FoundFields { // "Arbalète & Distance & 4 & 1 & 3 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ", - let re = regex::Regex::new(r"((?\d)reload)?(, )?(Gls\{parmure\} (?\d))?(, )?(?(\d+)m)?").unwrap(); + let re = regex::Regex::new(r"((?\d)reload)?(, )?(Gls\{parmure\} (?\d))?(, )?((?\d+)m)?").unwrap(); re.captures(fields).map_or(FoundFields::default(), |f| FoundFields { reload: f.name("reload").map(|n| n.as_str().parse().unwrap()), range: f.name("range").map(|v| v.as_str().parse().unwrap()), @@ -106,9 +105,14 @@ fn database_shnn(db: &EquipementDatabase, row: T) { .collect::>() .join(", ") ); - // println!("{}", sql); + // println!("Database Request {}", sql); let r = db.conn.execute(sql, to_params_named(&row).unwrap().to_slice().as_slice()); - println!("Loaded {:?} entries into the database", r); + match r { + Ok(_r) => { + // println!("Loaded {:?} entries into the database", _r); + } + Err(e) => println!("Error: {} while processing entry", e), + }; } fn load_base(index: &mut u8) -> Vec { @@ -127,35 +131,39 @@ fn load_base(index: &mut u8) -> Vec { .iter() .map(|row| { let fields = row.split("&").map(|field| field.trim()).collect::>(); - let FoundFields { reload, range, parmor } = parse_special_field(fields[16]); + let FoundFields { reload, range, parmor } = parse_special_field(fields[15]); *index += 1; + // "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ", + // 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 DatabaseEquipementStats { id: *index, meta_category: "Forme".into(), name: fields[0].to_string(), - category: format!("\"{}\"", fields[1]), + category: serde_json::to_string(&parse_to_type(fields[1]).unwrap()).unwrap(), rarity: 0, cost: 0, - difficulty: fields[16].parse().unwrap_or_default(), - tier: 0, + precision: 0, + difficulty: fields[16].parse().unwrap_or_default(), // NOT PARSED YET + // tier: , damage: fields[2].parse().unwrap_or_default(), p_damage: fields[3].parse().unwrap_or_default(), - precision: fields[4].parse().unwrap_or_default(), - rmax: fields[5].parse().unwrap_or_default(), - armor_break: fields[6].parse().unwrap_or_default(), - protection: fields[7].parse().unwrap_or_default(), - integrity: fields[8].parse().unwrap_or_default(), + rmax: fields[4].parse().unwrap_or_default(), + armor_break: fields[5].parse().unwrap_or_default(), + protection: fields[6].parse().unwrap_or_default(), + integrity: fields[7].parse().unwrap_or_default(), - torque_two_handed: fields[10].parse().unwrap_or_default(), + torque_two_handed: fields[8].parse().unwrap_or_default(), torque_one_handed: fields[9].parse().unwrap_or_default(), // The or default is a problem - damage_type: fields[11].parse().unwrap(), + damage_type: serde_json::to_string(&parse_to_damagetype(fields[10])).unwrap(), - dodge: fields[12].parse().unwrap_or_default(), - parry: fields[13].parse().unwrap_or_default(), - speed: fields[14].parse().unwrap_or_default(), - stealth: fields[15].parse().unwrap_or_default(), + dodge: fields[11].parse().unwrap_or_default(), + parry: fields[12].parse().unwrap_or_default(), + speed: fields[13].parse().unwrap_or_default(), + stealth: fields[14].parse().unwrap_or_default(), reload_cost: serde_json::to_string(&reload).unwrap(), range: range.unwrap_or_default(), + armor_pierce: parmor.unwrap_or_default(), + // meta_category: parse_to_type(fields[1]), // target: fields[5].parse().unwrap(), // Armors ? ..Default::default() @@ -163,3 +171,30 @@ fn load_base(index: &mut u8) -> Vec { }) .collect::>() } + +fn parse_to_damagetype(fields: &str) -> DamageType { + DamageType(fields.split(",").map(|v| ModeParser::lexer(v.trim()).next().unwrap().unwrap().into()).collect::>()) +} + +impl From for DamageMod { + fn from(value: ModeParser) -> Self { + match value { + ModeParser::Primary(v) => DamageMod::Primary(v), + ModeParser::Secondary(v) => DamageMod::Secondary(v), + ModeParser::Tertiary(v) => DamageMod::Tertiary(v), + } + } +} + +fn parse_to_type(text: &str) -> Option { + match text { + "Hast" => Some(WeaponMetaCategory::Staves), + "Tranchantes" => Some(WeaponMetaCategory::Slash), + "Contondantes" => Some(WeaponMetaCategory::Blunt), + "Distance" => Some(WeaponMetaCategory::Ranged), + "Boucliers" => Some(WeaponMetaCategory::Shields), + "Armures" => Some(WeaponMetaCategory::Armor), + "Exotiques" => Some(WeaponMetaCategory::Exotic), + _ => None, + } +} diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index a372c66..aec7348 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -16,10 +16,11 @@ pub fn get_data( where T: DeserializeOwned + more_fields::FieldsAsSlice, { - let mut query_result = conn.prepare(&generate_select_query::(table_name, filter))?; - Ok(serde_rusqlite::from_rows::(query_result.query([])?) - .filter_map(|s| s.ok()) - .collect()) + serde_rusqlite::from_rows::( + conn.prepare(&generate_select_query::(table_name, filter))? + .query([])?, + ) + .collect() } /// Generate a SELECT query with fields generated from a struct. Returns a SQL request as a String diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index a410c4d..ede0006 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -16,6 +16,12 @@ pub enum FatalEquipementError { #[error("Deserialisation from json failed : {0}")] SerdeJSON(#[from] serde_json::Error), + + #[error("Deserialisation from json failed at line {0} : {1}]")] + SerdeJSONAt(String, serde_json::Error), + + #[error("Couldn't convert into type {0} with data {1}")] + Conversion(String, String), } #[derive(Error, Debug)] diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index e1d9e1b..cf78892 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -2,11 +2,13 @@ // File: weaponry/src/weaponry_structs/equipement_fields.rs //! The inner fields used by the super structs -use std::fmt::Display; - use serde::{Deserialize, Serialize}; +use std::fmt::Display; +use std::ops::Add; use strum::Display; +use crate::error::FatalEquipementError; + #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only @@ -26,14 +28,30 @@ 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)] -#[cfg_attr(test, derive(PartialEq))] +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] +// #[cfg_attr(test, derive(PartialEq))] pub enum PhysicalDamageType { Blunt, Slash, Pierce, } +impl TryFrom<&str> for PhysicalDamageType { + type Error = FatalEquipementError; + + fn try_from(value: &str) -> Result { + match value.to_ascii_lowercase().as_str() { + "blunt" => Ok(Self::Blunt), + "slash" => Ok(Self::Slash), + "pierce" => Ok(Self::Pierce), + _ => Err(FatalEquipementError::Conversion( + std::any::type_name::().to_owned(), + value.to_string(), + )), + } + } +} + /// Weapon damage, combining the base weapon damage type and it's level /// /// Signifying wether the damage is pure or [secondary] or [[tertiary]] @@ -66,9 +84,46 @@ impl Display for DamageType { } } +// impl TryFrom<&str> for DamageType { +// type Error = FatalEquipementError; + +// fn try_from(value: &str) -> Result { +// let re = regex::Regex::new(r"(?\[\[\w+\]\])|(?\[\w+\])|(?\w+)") +// .unwrap(); +// let v = value +// .split(",") +// .map( +// |v| { +// let groups = re.captures(v).unwrap(); +// *groups +// }, // match v.trim() { +// // _ => Ok(DamageMod::Primary(PhysicalDamageType::Blunt)), +// // } +// ) +// .collect::, FatalEquipementError>>(); +// Ok(Self(v?)) +// } +// } +// impl FromSql for DamageType { +// fn column_result(value: rusqlite::types::ValueRef<'_>) -> rusqlite::types::FromSqlResult { +// Ok(DamageType(vec![DamageMod::Secondary( +// PhysicalDamageType::Pierce, +// )])) +// } +// } + +impl Add for DamageType { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self(self.0.iter().chain(rhs.0.iter()).cloned().collect()) + } +} + +// TODO: Convert into this category at the end, depending on all important factors /// List all weapon categories #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, PartialEq, Display, Deserialize, Serialize)] +#[derive(Clone, Debug, PartialEq, Display, Deserialize, Serialize, strum::EnumString)] // #[cfg_attr(test, derive(PartialEq))] pub enum WeaponCategory { Exotic, @@ -86,6 +141,22 @@ pub enum WeaponCategory { Bow, Crossbow, Cannon, + // Armor, + // Shield, +} + +// TODO: This is the real initial category +/// The list of initial weapon meta categories +#[allow(clippy::missing_docs_in_private_items, missing_docs)] +#[derive(Clone, Debug, PartialEq, Display, Deserialize, Serialize, strum::EnumString)] +pub enum WeaponMetaCategory { + Staves, + Blunt, + Slash, + Ranged, + Armor, + Shields, + Exotic, } #[cfg(test)] diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index 9b7cb66..3d27023 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -107,7 +107,7 @@ impl Display for InnerEquipementStats { vec![format!("Prot:{} Int:{}", self.protection, self.integrity)], ); table.add_row(vec![format!( - "T1/T2 {}/{} Dodge:{} Parry:{} Speed:{} Stealth:{} Agility: {}", + "T1/T2 {:?}/{:?} Dodge:{} Parry:{} Speed:{} Stealth:{} Agility: {}", self.torque_one_handed, self.torque_two_handed, self.dodge, diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index 47afd3f..f06a714 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -73,6 +73,15 @@ impl FixedRecipe for EquipementFixedRecipe { } } +/// Macro converting a value using serde and mapping an in house error +macro_rules! from_serde { + ($value: expr) => { + serde_json::from_str(&$value).map_err(|e| { + FatalEquipementError::SerdeJSONAt(format!("{} line {}", file!(), line!()), e) + }) + }; +} + // #[allow(clippy::useless_conversion)] impl TryFrom for InnerEquipementStats { type Error = FatalEquipementError; @@ -84,7 +93,8 @@ impl TryFrom for InnerEquipementStats { rarity: value.rarity, // Generic case, into(), serde or cast are equivalent cost: value.cost, difficulty: value.difficulty, - tier: value.tier, + // tier: value.tier, + tier: 0, damage: value.damage, p_damage: value.p_damage, precision: value.precision, @@ -92,20 +102,20 @@ impl TryFrom for InnerEquipementStats { armor_break: value.armor_break, armor_pierce: value.armor_pierce, antimaterial: value.antimaterial, - damage_type: serde_json::from_str(&value.damage_type)?, // Serde and derive are godsent + damage_type: from_serde!(&value.damage_type)?, // Serde and derive are godsent protection: value.protection, integrity: value.integrity, - torque_two_handed: value.torque_two_handed, - torque_one_handed: value.torque_one_handed, + torque_two_handed: from_serde!(&value.torque_two_handed)?, + torque_one_handed: from_serde!(&value.torque_one_handed)?, dodge: value.dodge, parry: value.parry, speed: value.speed, stealth: value.stealth, - category: serde_json::from_str(&value.category)?, - target: serde_json::from_str(&value.target)?, - special: serde_json::from_str(&value.special)?, + category: from_serde!(&value.category)?, + target: from_serde!(&value.target)?, + special: from_serde!(&value.special)?, action_cost: value.action_cost, - reload_cost: serde_json::from_str(&value.reload_cost)?, + reload_cost: from_serde!(&value.reload_cost)?, range: value.range, agility_bonus: value.agility_bonus, }) diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index 36cd772..a42b3f9 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, SpecialCategory, - WeaponCategory, equipement_fields::PhysicalDamageType, + equipement_fields::{PhysicalDamageType, WeaponMetaCategory}, equipement_structs::InnerEquipementStats, }, }; @@ -94,7 +94,7 @@ mod test { integrity: 2, range: 3, agility_bonus: 4, - category: Some(WeaponCategory::Dagger), + category: Some(WeaponMetaCategory::Staves), special: SpecialCategory(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, - category: Some(WeaponCategory::Dagger), + category: Some(WeaponMetaCategory::Staves), special: SpecialCategory(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 ac6c4a6..8da15c6 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -22,10 +22,7 @@ macro_rules! add_two_options { (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) - } + (Some(a), Some(b)) => Some(a + b), } }}; } @@ -53,7 +50,7 @@ impl std::ops::Add for &InnerEquipementStats { 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, + torque_one_handed: add_two_options!(self.torque_one_handed, rhs.torque_one_handed), dodge: self.dodge + rhs.dodge, parry: self.parry + rhs.parry, speed: self.speed + rhs.speed, diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 0fd7c2d..3f5b285 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -8,7 +8,7 @@ use crate::interfaces::{FilterFunction, FilterFunctionType}; use more_fields::FieldsAsSlice; use serde::{Deserialize, Serialize}; -use super::{DamageType, SpecialCategory, WeaponCategory}; +use super::{DamageType, SpecialCategory, WeaponCategory, equipement_fields::WeaponMetaCategory}; /// The final equipement list /// @@ -73,18 +73,18 @@ pub struct InnerEquipementStats { pub(super) damage_type: Option, pub(super) protection: u8, pub(super) integrity: u8, - pub(super) torque_two_handed: u8, - pub(super) torque_one_handed: u8, + pub(super) torque_two_handed: u8, // Might be option (single claw) + pub(super) torque_one_handed: Option, // Should be option (bows) pub(super) dodge: u8, pub(super) parry: u8, pub(super) speed: u8, pub(super) stealth: u8, - pub(super) category: Option, - pub(super) target: Option, + pub(super) category: Option, + pub(super) target: Option, // TODO: This might be incorrect, to check pub(super) special: SpecialCategory, pub(super) action_cost: u8, - pub(super) reload_cost: Option, - pub(super) range: u8, + pub(super) reload_cost: Option, // Shouldn't it be Option ? + pub(super) range: u8, // Shoudln't it be Option ? pub(super) agility_bonus: u8, } @@ -127,10 +127,8 @@ pub struct DatabaseEquipementStats { pub protection: u8, #[INTEGER] pub integrity: u8, - #[INTEGER] - pub torque_two_handed: u8, - #[INTEGER] - pub torque_one_handed: u8, + pub torque_two_handed: String, + pub torque_one_handed: String, #[INTEGER] pub dodge: u8, #[INTEGER] @@ -158,7 +156,7 @@ 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(), + category: serde_json::to_string(&None::).unwrap(), target: serde_json::to_string(&None::).unwrap(), special: serde_json::to_string(&SpecialCategory::default()).unwrap(), reload_cost: serde_json::to_string(&None::).unwrap(), @@ -175,8 +173,8 @@ impl Default for DatabaseEquipementStats { antimaterial: 0, protection: 0, integrity: 0, - torque_two_handed: 0, - torque_one_handed: 0, + torque_two_handed: serde_json::to_string(&0).unwrap(), + torque_one_handed: serde_json::to_string(&None::).unwrap(), dodge: 0, parry: 0, speed: 0, diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index d9203c8..cf3aab5 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -34,4 +34,6 @@ pub use equipement_structs::{Equipement, InitialEquipementList}; // All generic fields // #[allow(unused_imports)] pub use equipement_fields::PhysicalDamageType; -pub use equipement_fields::{DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory}; +pub use equipement_fields::{ + DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory, WeaponMetaCategory, +}; -- 2.45.1 From 22b46f6c07a28e07f0548b5717a119a04bd9bae2 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 21 Feb 2025 03:48:50 +0100 Subject: [PATCH 3/4] More work on the serialisation and the entry datatypes --- weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/first_import.rs | 371 +++++++++--------- weaponry/examples/test_serialisation_wl.rs | 31 ++ weaponry/src/database.rs | 17 +- weaponry/src/error.rs | 18 +- .../src/weaponry_structs/equipement_fields.rs | 8 +- .../equipement_impl_database.rs | 7 +- .../weaponry_structs/equipement_impl_logic.rs | 2 +- .../weaponry_structs/equipement_impl_math.rs | 2 +- .../weaponry_structs/equipement_structs.rs | 104 ++--- 10 files changed, 309 insertions(+), 251 deletions(-) create mode 100644 weaponry/examples/test_serialisation_wl.rs diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index 6d0843fc1fb807b939f132659d4bc921cab0bcda..d0343f193cd15f2ecd4c903207456e5b6c37d814 100644 GIT binary patch literal 28672 zcmeI3-*4O26~{@Dl1TrE>Uf@;d7e0>MP)cCqNI+KZdfOKs_i9CU0d1WxtVrFUE5qJ zQYNV+u93HHNcPZwp~W7C>Mz)UJ_>!^-uuu!7kwNC>|sN9E-C)F`r&oJP}JFBz=*t; z`kr$>_uO+y8rpgLw&782-*%eB)2<0G2%;$bSknYSS`q{y3ws833HCDVGVI|dh6kfR zLF3im7AGgJ2$K4~F#g$OQGGxAF#I?Ad)R{nkN^@u0!ZL_B=FvAv)S3XIq~Tm9;utO za#ZuE>-9detJ{@wwW3waE4M3JuTd)+4Q=C2wX#;(zGRUm)vA?y)k_X>4DUGV&~4X? zP8!DkzM;3xM89WHC+;UrazLZgR;|(3;85Lg4cm$?fqR6<(Ft*ywo|J+lsxEbYk?I# z7ABTwz|9493}QxC2DWP6ajO?e%dtJGdr5PK<sb6Z3Lg->mF|Lu@Y%Z4h$0}daZ6-Z8x%~ZEbICmbZ7cTb147D@NlLt$ero*2W!3kj=`S z>cYa7l$l*z6nFh>a*sfQ)?5lx$kJ)wsmx_nUuTh}&L#Nf0?e0xe6!}v*W=A^?xwR0 zf5=@w_sO{j=gv?5aq?G_@7Zp+I zZBvReGsBK&X5LWXU^BRBZa===w%EOd~`3F zskT@O3>|$7485!l4Q7`!v}L!QmP1{*zj5SY;gof~`;n`4KkPFVM;MsgpJK6bCP&1! z3J($R_|a}cXkQM7w%zRjKt8Sn!;N!bXI@d%Xq?o@&J-6~_nA%%)18yPloPe)JU;YnY{c@BK zV;x~L|NXBbv|~5x4$2Rg*Eq_&SSE_AH!om5bUT-c>(XW&ri4j@ zYE}YNxt*9&L^B_Vk4D)X6$Qae}x<7 zye~HXBjGkw`>1G*7E4z90pz~c+6&;=g(OuqqRJP~a-$h68^eX*UgW2+G(;=IXs6<( zVYpIx5?q2cKa!dfl_}uGZU%UlR@;UH3(V!E%S)kDP*S1(t&g$5lw@g-Qj=F%act{d z3Z;E;J@gS(CO~O6>CZ?+tgMeH>ZU0OtK*r24E^M>cL5-ep>G5tRbUBvI`RT&T)`{8u$fL3}TwJ&bk!gu;FHVsND^5Z{hR9@1nM z-4he&Sb)naWGF19YBInz2j2KoH^paCsGYiYJtYl9G6^M2o#+UI&;QTOa~1}I1dsp{ zKmter2_OL^fCP}hStEeY|M>h5FBb6m-+#gJKYjjBHV%9KCbeI(F<_90XNA0@u(Xm6|GL0Er5Tw7CWg#|Fn~5ey+Drz)a}z;Vg| zQW9WdqOw?#Sh}GC9vGSUFCZ#nrvof>;+zDfjfBKmKY#q*^ZC7ZzV-oZAHbK>QSLPW zfM+$qYK+z8-Ng%MS$D~PBTFg3g}NZrmEZ9@!^4}yM-$!-{{p(pp|>q5#VyYy=YpNb zj$Pf_qIQLDQ->BCj@>Lf#cD;Z*QuR%N={?VBx#Fa%T%*jV&YLE7BL&?b&Fvcq7gSaoPkt>DdT#3Z<0s!@Ce8(L<`zg-cDo_Q*q=6#9JjDf_m zO-uhJag=ymqN?YKX|?{Tv5#X_w~T?rgs*4;Z=|&X$>W4hHhUTuRz#t2BjZOiG>h}Z z!qp09UJ`j0##--*86NT5>KWG5>&!ZR)SvHo6eo~g8XX|>lT%Z$bH^#&+ot{W`e*L% z3Z+*yg5&*W94AB}UaiChW`+0*ryCa53z~)tx~kkPkVS_3GU9?oZdvXZH1Bpp76;q! zJ5ONXd2Y{9P%>FMy+6QP4T?~H?-w#LSk8)Y&rF~CHy^_vs2{ND r`rna)VBkC?51Z8ov_|VrL;P@+k0=4g8)xNT{e8eO@;BuDF7lB-pP$~> diff --git a/weaponry/examples/first_import.rs b/weaponry/examples/first_import.rs index a3294dc..73b7ca4 100644 --- a/weaponry/examples/first_import.rs +++ b/weaponry/examples/first_import.rs @@ -1,200 +1,215 @@ // Workspace: weaponry // File: examples/typical_wl_recipe.rs -//! Example of a typical workload -//! +//! Example of a first initialisation +//! All this work is cursed and rushed -use logos::Logos; -use more_fields::FieldsAsSlice; -use serde::Serialize; -use serde_rusqlite::to_params_named; +// use logos::Logos; +// use more_fields::FieldsAsSlice; +// use serde::Serialize; +// use serde_rusqlite::to_params_named; use weaponry::interfaces::RecipeDatabase; use weaponry::weaponry_structs::equipement_impl_database::EquipementDatabase; +// use weaponry::weaponry_structs::{DamageMod, DamageType, WeaponMetaCategory}; +// use weaponry::weaponry_structs::PhysicalDamageType; use weaponry::weaponry_structs::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}; -use weaponry::weaponry_structs::{DamageMod, DamageType, PhysicalDamageType, WeaponMetaCategory}; -#[derive(Logos, Debug, PartialEq)] -enum ModeParser { - #[regex(r"\[\[\w+\]\]", |lex| std::convert::TryInto::::try_into(&lex.slice()[2..lex.slice().len()-2]).unwrap())] - Tertiary(PhysicalDamageType), - #[regex(r"\[\w+\]", |lex| std::convert::TryInto::::try_into(&lex.slice()[1..lex.slice().len()-1]).unwrap())] - Secondary(PhysicalDamageType), - #[regex(r"\w+", |lex| std::convert::TryInto::::try_into(lex.slice()).unwrap())] - Primary(PhysicalDamageType), -} +// #[derive(Logos, Debug, PartialEq)] +// enum ModeParser { +// #[regex(r"\[\[\w+\]\]", |lex| std::convert::TryInto::::try_into(&lex.slice()[2..lex.slice().len()-2]).unwrap())] +// Tertiary(PhysicalDamageType), +// #[regex(r"\[\w+\]", |lex| std::convert::TryInto::::try_into(&lex.slice()[1..lex.slice().len()-1]).unwrap())] +// Secondary(PhysicalDamageType), +// #[regex(r"\w+", |lex| std::convert::TryInto::::try_into(lex.slice()).unwrap())] +// Primary(PhysicalDamageType), +// } // let b = DamageMod::Primary() -const BASE_FORME: &[&str] = &[ - // "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ", - // "Name & Type & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & mode & 9 & 10 & 11 & 12 & 3reload, & ddlvl{13} ", - "Griffes & Tranchantes & 2 & 1 & 4 & 1 & 1 & 2 & 3 & 6 & slash & 2 & 0 & 3 & 1 & - & ddlvl{1} ", - "Hast & Hast & 4 & 1 & 2 & 1 & 4 & 3 & 10 & 18 & pierce, [slash] & -1 & -3 & 1 & 0 & - & ddlvl{1} ", - "Épée & Tranchantes & 3 & 1 & 3 & 1 & 3 & 4 & 12 & 15 & slash, [pierce] & 0 & 1 & 0 & 0 & - & ddlvl{1} ", - "Marteau & Contondantes & 5 & 1 & 1 & 1 & 4 & 3 & 11 & 18 & blunt & -1 & -1 & 0 & -2 & - & ddlvl{1} ", - "Hache & Tranchantes & 4 & 2 & 1 & 3 & 4 & 3 & 9 & 14 & slash & 0 & -1 & 1 & 0 & - & ddlvl{1} ", - "Arbalète & Distance & 4 & 1 & 3 & 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ", - "Arc & Distance & 3 & 1 & 4 & 0 & 2 & 1 & - & 7 & pierce & 0 & 0 & 0 & 0 & 1reload, Gls{parmure} 2, 120m & ddlvl{1} ", - "Boucliers & Boucliers & 1 & 1 & 2 & 0 & 3 & 2 & 6 & 8 & blunt & -2 & 0 & -1 & -2 & - & ddlvl{1} ", - "Armures & Armures & & & & & 3 & 2 & 10 & - & blunt & -1 & 0 & 0 & -1 & - & ddlvl{1} ", - // "% Explosive & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{5} ", - // "% Flexible & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{2} ", - // "% Exotique & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{3} ", -]; fn main() { - let mut global_index = 0; - let b = load_base(&mut global_index); - // println!("{b:?}"); // Equipements - let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); - db.initialize_empty_table::("Equipements").unwrap(); - db.conn.execute("DELETE FROM Equipements", []).unwrap(); - println!("Added {global_index} ids to the new database"); - b.iter().for_each(|v| database_shnn(&db, v)); - let v = db.serialize_vec_from_table::("Equipements", None); - // println!("Initial deserialisation in DatabaseEquipementStats: {:?}", v); - println!("First entry: {:?}", v.as_ref().unwrap()[0]); - // Final deserialisation - let final_s = v.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::>(); - let v = final_s - .iter() - .scan(0, |status, eq| { - if eq.is_ok() { - *status = 1; - } else { - *status = 0; - } - Some(*status) - }) - .sum::(); - println!("Final data {:#?}", final_s); - println!("Succeded in parsing {:#?} over {}", v, global_index); + // init_db(&db); + let initial_deserialisation = db.serialize_vec_from_table::("Equipements", None); + // println!("Initial deserialisation in DatabaseEquipementStats: {:?}", initial_deserialisation); + // println!("First entry: {:?}", initial_deserialisation.as_ref().unwrap()[0]); + + let intermediate_deserialisation = initial_deserialisation.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::>(); + // let v = intermediate_deserialisation + // .iter() + // .scan(0, |status, eq| { + // if eq.is_ok() { + // *status = 1; + // } else { + // *status = 0; + // } + // Some(*status) + // }) + // .sum::(); + let f = intermediate_deserialisation.iter().fold((0, 0), |val, res| (val.0 + res.is_ok() as usize, val.1 + 1_usize)); + println!("Final data {:#?}", intermediate_deserialisation); + println!("Succeded in parsing {}/{}", f.0, f.1); } -#[allow(dead_code)] -#[derive(Default)] -struct FoundFields { - reload: Option, - range: Option, - parmor: Option, -} -fn parse_special_field(fields: &str) -> FoundFields { - // "Arbalète & Distance & 4 & 1 & 3 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ", - let re = regex::Regex::new(r"((?\d)reload)?(, )?(Gls\{parmure\} (?\d))?(, )?((?\d+)m)?").unwrap(); - re.captures(fields).map_or(FoundFields::default(), |f| FoundFields { - reload: f.name("reload").map(|n| n.as_str().parse().unwrap()), - range: f.name("range").map(|v| v.as_str().parse().unwrap()), - parmor: f.name("parmor").map(|v| v.as_str().parse().unwrap()), - }) -} +// #[derive(Default)] +// struct FoundFields { +// reload: Option, +// range: Option, +// parmor: Option, +// } +// fn init_db(db: &EquipementDatabase) { +// let mut global_index = 0; +// let b = load_base(&mut global_index); +// db.initialize_empty_table::("Equipements").unwrap(); -#[allow(dead_code)] -fn database_shnn(db: &EquipementDatabase, row: T) { - // let mut row = DatabaseEquipementStats::random_new(); +// db.conn.execute("DELETE FROM Equipements", []).unwrap(); +// println!("Added {global_index} ids to the new database"); - let sql = &format!( - "INSERT INTO Equipements ({}) VALUES ({})", - DatabaseEquipementStats::attributes_slice() - .iter() - // .filter_map(|(k, _v)| (*k != "id").then_some(*k)) - .map(|(k, _v)| *k) - .collect::>() - .join(", "), - DatabaseEquipementStats::attributes_slice() - .iter() - // .filter_map(|(k, _v)| (*k != "id").then_some(":".to_string() + *k)) - .map(|(k, _v)| ":".to_string() + *k) - .collect::>() - .join(", ") - ); - // println!("Database Request {}", sql); - let r = db.conn.execute(sql, to_params_named(&row).unwrap().to_slice().as_slice()); - match r { - Ok(_r) => { - // println!("Loaded {:?} entries into the database", _r); - } - Err(e) => println!("Error: {} while processing entry", e), - }; -} +// b.iter().for_each(|v| insert_into_db(db, v)); +// } +// fn parse_special_field(fields: &str) -> FoundFields { +// // "Arbalète & Distance & 4 & 1 & 3 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ", +// let re = regex::Regex::new(r"((?\d)reload)?(, )?(Gls\{parmure\} (?\d))?(, )?((?\d+)m)?").unwrap(); +// re.captures(fields).map_or(FoundFields::default(), |f| FoundFields { +// reload: f.name("reload").map(|n| n.as_str().parse().unwrap()), +// range: f.name("range").map(|v| v.as_str().parse().unwrap()), +// parmor: f.name("parmor").map(|v| v.as_str().parse().unwrap()), +// }) +// } -fn load_base(index: &mut u8) -> Vec { - // data_eg.id = fastrand::u8(1..u8::MAX); - // data_eg.damage_type = serde_json::to_string(&Some(DamageType(vec![DamageMod::Primary( - // PhysicalDamageType::Blunt, - // )]))) - // .unwrap(); - // data_eg.category = serde_json::to_string(&Some(WeaponCategory::Dagger)).unwrap(); - // data_eg.target = serde_json::to_string(&Some(WeaponCategory::Dagger)).unwrap(); - // data_eg.special = - // serde_json::to_string(&SpecialCategory(vec!["noo".to_string(), "boo".to_string()])) - // .unwrap(); - // data_eg.reload_cost = serde_json::to_string(&Some(12)).unwrap(); - BASE_FORME - .iter() - .map(|row| { - let fields = row.split("&").map(|field| field.trim()).collect::>(); - let FoundFields { reload, range, parmor } = parse_special_field(fields[15]); - *index += 1; - // "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ", - // 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 - DatabaseEquipementStats { - id: *index, - meta_category: "Forme".into(), - name: fields[0].to_string(), - category: serde_json::to_string(&parse_to_type(fields[1]).unwrap()).unwrap(), - rarity: 0, - cost: 0, - precision: 0, - difficulty: fields[16].parse().unwrap_or_default(), // NOT PARSED YET - // tier: , - damage: fields[2].parse().unwrap_or_default(), - p_damage: fields[3].parse().unwrap_or_default(), - rmax: fields[4].parse().unwrap_or_default(), - armor_break: fields[5].parse().unwrap_or_default(), - protection: fields[6].parse().unwrap_or_default(), - integrity: fields[7].parse().unwrap_or_default(), +// #[allow(dead_code)] +// fn insert_into_db(db: &EquipementDatabase, row: T) { +// let sql = &format!( +// "INSERT INTO Equipements ({}) VALUES ({})", +// DatabaseEquipementStats::attributes_slice() +// .iter() +// // .filter_map(|(k, _v)| (*k != "id").then_some(*k)) +// .map(|(k, _v)| *k) +// .collect::>() +// .join(", "), +// DatabaseEquipementStats::attributes_slice() +// .iter() +// // .filter_map(|(k, _v)| (*k != "id").then_some(":".to_string() + *k)) +// .map(|(k, _v)| ":".to_string() + *k) +// .collect::>() +// .join(", ") +// ); +// // println!("Database Request {}", sql); +// let r = db.conn.execute(sql, to_params_named(&row).unwrap().to_slice().as_slice()); +// match r { +// Ok(_r) => { +// // println!("Loaded {:?} entries into the database", _r); +// } +// Err(e) => println!("Error: {} while processing entry", e), +// }; +// } - torque_two_handed: fields[8].parse().unwrap_or_default(), - torque_one_handed: fields[9].parse().unwrap_or_default(), // The or default is a problem - damage_type: serde_json::to_string(&parse_to_damagetype(fields[10])).unwrap(), +// // fn load_base(index: &mut u8) -> Vec { +// // BASE_FORME +// // .iter() +// // .map(|row| { +// // let fields = row.split("&").map(|field| field.trim()).collect::>(); +// // let FoundFields { reload, range, parmor } = parse_special_field(fields[15]); +// // *index += 1; +// // // "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ", +// // // 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 +// // DatabaseEquipementStats { +// // id: *index, +// // meta_category: "Forme".into(), +// // name: fields[0].to_string(), +// // category: serde_json::to_string(&parse_to_type(fields[1]).unwrap()).unwrap(), +// // rarity: 0, +// // cost: 0, +// // precision: 0, +// // difficulty: fields[16].parse().unwrap_or_default(), // NOT PARSED YET +// // // tier: , +// // damage: fields[2].parse().unwrap_or_default(), +// // p_damage: fields[3].parse().unwrap_or_default(), +// // rmax: fields[4].parse().unwrap_or_default(), +// // armor_break: fields[5].parse().unwrap_or_default(), +// // protection: fields[6].parse().unwrap_or_default(), +// // integrity: fields[7].parse().unwrap_or_default(), - dodge: fields[11].parse().unwrap_or_default(), - parry: fields[12].parse().unwrap_or_default(), - speed: fields[13].parse().unwrap_or_default(), - stealth: fields[14].parse().unwrap_or_default(), - reload_cost: serde_json::to_string(&reload).unwrap(), - range: range.unwrap_or_default(), - armor_pierce: parmor.unwrap_or_default(), - // meta_category: parse_to_type(fields[1]), +// // torque_two_handed: serde_json::to_string(&match fields[8] { +// // "-" => None, +// // v => Some(v.parse::().unwrap()), +// // }) +// // .unwrap(), +// // torque_one_handed: serde_json::to_string(&match fields[9] { +// // "-" => None, +// // v => Some(v.parse::().unwrap()), +// // }) +// // .unwrap(), // The or default is a problem +// // damage_type: serde_json::to_string(&parse_to_damagetype(fields[10])).unwrap(), - // target: fields[5].parse().unwrap(), // Armors ? - ..Default::default() - } - }) - .collect::>() -} +// // dodge: fields[11].parse().unwrap_or_default(), +// // parry: fields[12].parse().unwrap_or_default(), +// // speed: fields[13].parse().unwrap_or_default(), +// // stealth: fields[14].parse().unwrap_or_default(), +// // reload_cost: serde_json::to_string(&reload).unwrap(), +// // range: range.unwrap_or_default(), +// // armor_pierce: parmor.unwrap_or_default(), +// // // meta_category: parse_to_type(fields[1]), -fn parse_to_damagetype(fields: &str) -> DamageType { - DamageType(fields.split(",").map(|v| ModeParser::lexer(v.trim()).next().unwrap().unwrap().into()).collect::>()) -} +// // // target: fields[5].parse().unwrap(), // Armors ? +// // ..Default::default() +// // } +// // }) +// // .collect::>() +// // } -impl From for DamageMod { - fn from(value: ModeParser) -> Self { - match value { - ModeParser::Primary(v) => DamageMod::Primary(v), - ModeParser::Secondary(v) => DamageMod::Secondary(v), - ModeParser::Tertiary(v) => DamageMod::Tertiary(v), - } - } -} +// fn parse_to_damagetype(fields: &str) -> DamageType { +// DamageType(fields.split(",").map(|v| ModeParser::lexer(v.trim()).next().unwrap().unwrap().into()).collect::>()) +// } -fn parse_to_type(text: &str) -> Option { - match text { - "Hast" => Some(WeaponMetaCategory::Staves), - "Tranchantes" => Some(WeaponMetaCategory::Slash), - "Contondantes" => Some(WeaponMetaCategory::Blunt), - "Distance" => Some(WeaponMetaCategory::Ranged), - "Boucliers" => Some(WeaponMetaCategory::Shields), - "Armures" => Some(WeaponMetaCategory::Armor), - "Exotiques" => Some(WeaponMetaCategory::Exotic), - _ => None, - } -} +// impl From for DamageMod { +// fn from(value: ModeParser) -> Self { +// match value { +// ModeParser::Primary(v) => DamageMod::Primary(v), +// ModeParser::Secondary(v) => DamageMod::Secondary(v), +// ModeParser::Tertiary(v) => DamageMod::Tertiary(v), +// } +// } +// } + +// fn parse_to_type(text: &str) -> Option { +// match text { +// "Hast" => Some(WeaponMetaCategory::Staves), +// "Tranchantes" => Some(WeaponMetaCategory::Slash), +// "Contondantes" => Some(WeaponMetaCategory::Blunt), +// "Distance" => Some(WeaponMetaCategory::Ranged), +// "Boucliers" => Some(WeaponMetaCategory::Shields), +// "Armures" => Some(WeaponMetaCategory::Armor), +// "Exotiques" => Some(WeaponMetaCategory::Exotic), +// _ => None, +// } +// } + +// const BASE_FORME: &[&str] = &[ +// // "% Nom & Type & Dé & + & RM & AB & Pr & In & T2 & T1 & Md & Esq. & Par. & Vit. & Disc. & Spc. & Diff ", +// // "Name & Type & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & mode & 9 & 10 & 11 & 12 & 3reload, & ddlvl{13} ", +// "Griffes & Tranchantes & 2 & 1 & 4 & 1 & 1 & 2 & 3 & 6 & slash & 2 & 0 & 3 & 1 & - & ddlvl{1} ", +// "Hast & Hast & 4 & 1 & 2 & 1 & 4 & 3 & 10 & 18 & pierce, [slash] & -1 & -3 & 1 & 0 & - & ddlvl{1} ", +// "Épée & Tranchantes & 3 & 1 & 3 & 1 & 3 & 4 & 12 & 15 & slash, [pierce] & 0 & 1 & 0 & 0 & - & ddlvl{1} ", +// "Marteau & Contondantes & 5 & 1 & 1 & 1 & 4 & 3 & 11 & 18 & blunt & -1 & -1 & 0 & -2 & - & ddlvl{1} ", +// "Hache & Tranchantes & 4 & 2 & 1 & 3 & 4 & 3 & 9 & 14 & slash & 0 & -1 & 1 & 0 & - & ddlvl{1} ", +// "Arbalète & Distance & 4 & 1 & 3 & 0 & 3 & 1 & 8 & 16 & pierce & -1 & -1 & 0 & -1 & 2reload, Gls{parmure} 2, 80m & ddlvl{1} ", +// "Arc & Distance & 3 & 1 & 4 & 0 & 2 & 1 & - & 7 & pierce & 0 & 0 & 0 & 0 & 1reload, Gls{parmure} 2, 120m & ddlvl{1} ", +// "Boucliers & Boucliers & 1 & 1 & 2 & 0 & 3 & 2 & 6 & 8 & blunt & -2 & 0 & -1 & -2 & - & ddlvl{1} ", +// "Armures & Armures & & & & & 3 & 2 & 10 & - & blunt & -1 & 0 & 0 & -1 & - & ddlvl{1} ", +// // "% Explosive & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{5} ", +// // "% Flexible & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{2} ", +// // "% Exotique & Exotiques & 3 & 1 & 3 & 1 & 2 & 2 & 20 & 10 & slash & 0 & 0 & 0 & 0 & - & ddlvl{3} ", +// ]; +// #[allow(dead_code)] +// const BASE_SHAPE: &[&str] = &[ +// // " Maniement & damagew & + & rmax & arbreakw & faShield* & faShieldVirus & $mathbb{T}2$ & $mathbb{T}$1 & Esq. & Par. & Vit. & Disc. & Spécial & Diff. " +// // " % Nom & Dg & + & RM & AB & Pr & In & T2 & T1 & Esq. & Par. & Vit. & Disc. & Sp & Diff", +// " Arme Légère & -1 & 0 & 2 & -1 & -1 & -1 & -5 & -6 & 2 & 2 & 0 & 0 & Ag+half, Esq.+half & ddlvl{1}", +// " Arme Moyenne & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & - & ddzero", +// " Arme Lourde & 2 & 1 & 1 & 0 & 1 & 0 & 8 & 11 & -2 & -2 & -1 & -1 & - & ddlvl{1}", +// " Arme Super-lourde & 3 & 2 & 1 & 1 & 2 & 1 & 23 & 23 & -3 & -3 & -3 & -3 & 2A, Ag-1, [[blunt]], Précision-1 & ddlvl{2}", +// // " Arme Combinée & - & - & - & - & - & -2 & - & - & - & - & - & - & - & ddlvl{3}", // We'll have to think about this one +// // " Arme Escamotable & - & - & - & - & - & - & - & - & - & - & - & - & - & ddlvl{3}", // We'll have to think about this one +// " Armure Légère & - & - & - & - & -1 & -1 & -1 & - & 1 & 0 & 0 & 1 & Ag+1 & ddlvl{1}", +// " Armure Moyenne & - & - & - & - & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & - & ddzero", +// " Armure Lourde & - & - & - & - & 1 & 1 & 13 & - & -3 & -3 & -2 & -3 & Ag-1, Précision -1 & ddlvl{1}", +// " Armure Super-lourde & - & - & - & - & 3 & 3 & 25 & - & -5 & -4 & -4 & -6 & Ag-1, Précision -1 & ddlvl{2}", +// ]; diff --git a/weaponry/examples/test_serialisation_wl.rs b/weaponry/examples/test_serialisation_wl.rs new file mode 100644 index 0000000..abd1d3f --- /dev/null +++ b/weaponry/examples/test_serialisation_wl.rs @@ -0,0 +1,31 @@ +// Workspace: weaponry +// File: examples/test_serialisation_wl.rs +//! Test of an initial serialisation and scenario wl +//! Doing this work on an example will help writing it as an integration test afterwards + +use weaponry::interfaces::RecipeDatabase; +use weaponry::weaponry_structs::equipement_impl_database::EquipementDatabase; +use weaponry::weaponry_structs::equipement_structs::{DatabaseEquipementStats, InnerEquipementStats}; + +fn main() { + let db = EquipementDatabase::new("./databases/weapons.db").unwrap(); + let initial_deserialisation = db.serialize_vec_from_table::("Equipements", None); + // println!("Initial deserialisation in DatabaseEquipementStats: {:?}", initial_deserialisation); + // println!("First entry: {:?}", initial_deserialisation.as_ref().unwrap()[0]); + + let intermediate_deserialisation = initial_deserialisation.unwrap().into_iter().map(InnerEquipementStats::try_from).collect::>(); + // let v = intermediate_deserialisation + // .iter() + // .scan(0, |status, eq| { + // if eq.is_ok() { + // *status = 1; + // } else { + // *status = 0; + // } + // Some(*status) + // }) + // .sum::(); + let f = intermediate_deserialisation.iter().fold((0, 0), |val, res| (val.0 + res.is_ok() as usize, val.1 + 1_usize)); + println!("Final data {:#?}", intermediate_deserialisation); + println!("Succeded in parsing {}/{}", f.0, f.1); +} diff --git a/weaponry/src/database.rs b/weaponry/src/database.rs index aec7348..b6fdc44 100644 --- a/weaponry/src/database.rs +++ b/weaponry/src/database.rs @@ -7,20 +7,25 @@ use rusqlite::{self}; use serde::de::DeserializeOwned; +use crate::error::FatalEquipementError; + /// Public function to get data from db. Returns the result as a vec with structs pub fn get_data( conn: &rusqlite::Connection, table_name: &str, filter: Option<&str>, -) -> Result, serde_rusqlite::Error> +) -> Result, FatalEquipementError> where T: DeserializeOwned + more_fields::FieldsAsSlice, { - serde_rusqlite::from_rows::( - conn.prepare(&generate_select_query::(table_name, filter))? - .query([])?, - ) - .collect() + let mut binding = conn.prepare(&generate_select_query::(table_name, filter))?; + let rows = binding.query([])?; + serde_rusqlite::from_rows::(rows) + .enumerate() + .map(|(row_id, result)| { + result.map_err(|error| FatalEquipementError::SerdeRusqlite { error, row_id }) + }) + .collect() } /// Generate a SELECT query with fields generated from a struct. Returns a SQL request as a String diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index ede0006..dff152a 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -11,17 +11,23 @@ pub enum FatalEquipementError { #[error("Rusqlite failed to connect to the given path {0}")] RusqliteConnection(#[from] rusqlite::Error), - #[error("Deserialization from object failed : {0}")] - SerdeRusqlite(#[from] serde_rusqlite::Error), + #[error("Deserialization from object failed : rowid {row_id} \n{error}")] + SerdeRusqlite { + error: serde_rusqlite::Error, + row_id: usize, + }, #[error("Deserialisation from json failed : {0}")] SerdeJSON(#[from] serde_json::Error), - #[error("Deserialisation from json failed at line {0} : {1}]")] - SerdeJSONAt(String, serde_json::Error), + #[error("Deserialisation from json failed at line {line} : {error}]")] + SerdeJSONAt { + line: String, + error: serde_json::Error, + }, - #[error("Couldn't convert into type {0} with data {1}")] - Conversion(String, String), + #[error("Couldn't convert into type {origin_type} with data {data}")] + Conversion { origin_type: String, data: String }, } #[derive(Error, Debug)] diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index cf78892..dd6efeb 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -44,10 +44,10 @@ impl TryFrom<&str> for PhysicalDamageType { "blunt" => Ok(Self::Blunt), "slash" => Ok(Self::Slash), "pierce" => Ok(Self::Pierce), - _ => Err(FatalEquipementError::Conversion( - std::any::type_name::().to_owned(), - value.to_string(), - )), + _ => Err(FatalEquipementError::Conversion { + origin_type: std::any::type_name::().to_owned(), + data: value.to_string(), + }), } } } diff --git a/weaponry/src/weaponry_structs/equipement_impl_database.rs b/weaponry/src/weaponry_structs/equipement_impl_database.rs index f06a714..9541279 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -27,7 +27,7 @@ impl RecipeDatabase for EquipementDatabase { table: &str, filter: Option<&str>, ) -> Result, crate::error::FatalEquipementError> { - Ok(get_data(&self.conn, table, filter)?) + get_data(&self.conn, table, filter) } /// Checks if database exists, and returns a rusqlite::Connection. If not, opens database in memory. @@ -76,8 +76,9 @@ impl FixedRecipe for EquipementFixedRecipe { /// Macro converting a value using serde and mapping an in house error macro_rules! from_serde { ($value: expr) => { - serde_json::from_str(&$value).map_err(|e| { - FatalEquipementError::SerdeJSONAt(format!("{} line {}", file!(), line!()), e) + serde_json::from_str(&$value).map_err(|error| FatalEquipementError::SerdeJSONAt { + line: format!("{} line {}", file!(), line!()), + error, }) }; } diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index a42b3f9..a7f5d6a 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_logic.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_logic.rs @@ -172,7 +172,7 @@ mod test { fn test_basic_logic() {} impl Equipement { - fn newish(name: &[&str], i: u8) -> Self { + fn newish(name: &[&str], i: i8) -> Self { Equipement { stats: InnerEquipementStats { name: name.iter().map(|s| s.to_string()).collect(), diff --git a/weaponry/src/weaponry_structs/equipement_impl_math.rs b/weaponry/src/weaponry_structs/equipement_impl_math.rs index 8da15c6..8a677e8 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -49,7 +49,7 @@ impl std::ops::Add for &InnerEquipementStats { damage_type: add_two_options!(self.damage_type, rhs.damage_type), protection: self.protection + rhs.protection, integrity: self.integrity + rhs.integrity, - torque_two_handed: self.torque_two_handed + rhs.torque_two_handed, + torque_two_handed: add_two_options!(self.torque_two_handed, rhs.torque_two_handed), torque_one_handed: add_two_options!(self.torque_one_handed, rhs.torque_one_handed), dodge: self.dodge + rhs.dodge, parry: self.parry + rhs.parry, diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index 3f5b285..d74ddfd 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -59,33 +59,33 @@ impl FilterFunction { pub struct InnerEquipementStats { pub id: Vec, pub name: Vec, - pub(super) rarity: u8, - pub(super) cost: u8, - pub(super) difficulty: u8, - pub(super) tier: u8, - pub(super) damage: u8, - pub(super) p_damage: u8, + pub(super) rarity: i8, + pub(super) cost: i8, + pub(super) difficulty: i8, + pub(super) tier: i8, + pub(super) damage: i8, + pub(super) p_damage: i8, pub(super) precision: i8, - pub(super) rmax: u8, - pub(super) armor_break: u8, - pub(super) armor_pierce: u8, - pub(super) antimaterial: u8, + pub(super) rmax: i8, + pub(super) armor_break: i8, + pub(super) armor_pierce: i8, + pub(super) antimaterial: i8, pub(super) damage_type: Option, - pub(super) protection: u8, - pub(super) integrity: u8, - pub(super) torque_two_handed: u8, // Might be option (single claw) - pub(super) torque_one_handed: Option, // Should be option (bows) - pub(super) dodge: u8, - pub(super) parry: u8, - pub(super) speed: u8, - pub(super) stealth: u8, + pub(super) protection: i8, + pub(super) integrity: i8, + pub(super) torque_two_handed: Option, // Might be option (single claw) + pub(super) torque_one_handed: Option, // Should be option (bows) + pub(super) dodge: i8, + pub(super) parry: i8, + pub(super) speed: i8, + pub(super) stealth: i8, pub(super) category: Option, pub(super) target: Option, // TODO: This might be incorrect, to check pub(super) special: SpecialCategory, - pub(super) action_cost: u8, - pub(super) reload_cost: Option, // Shouldn't it be Option ? - pub(super) range: u8, // Shoudln't it be Option ? - pub(super) agility_bonus: u8, + pub(super) action_cost: i8, + pub(super) reload_cost: Option, // Shouldn't it be Option ? + pub(super) range: i8, // Shoudln't it be Option ? + pub(super) agility_bonus: i8, } // TODO: This implementation of default is painfull @@ -101,52 +101,52 @@ pub struct DatabaseEquipementStats { pub meta_category: String, pub name: String, #[INTEGER] - pub rarity: u8, + pub rarity: i8, #[INTEGER] - pub cost: u8, + pub cost: i8, #[INTEGER] - pub difficulty: u8, + pub difficulty: i8, #[INTEGER] - pub tier: u8, + pub tier: i8, #[INTEGER] - pub damage: u8, + pub damage: i8, #[INTEGER] - pub p_damage: u8, + pub p_damage: i8, #[INTEGER] pub precision: i8, #[INTEGER] - pub rmax: u8, + pub rmax: i8, #[INTEGER] - pub armor_break: u8, + pub armor_break: i8, #[INTEGER] - pub armor_pierce: u8, + pub armor_pierce: i8, #[INTEGER] - pub antimaterial: u8, + pub antimaterial: i8, pub damage_type: String, #[INTEGER] - pub protection: u8, + pub protection: i8, #[INTEGER] - pub integrity: u8, + pub integrity: i8, pub torque_two_handed: String, pub torque_one_handed: String, #[INTEGER] - pub dodge: u8, + pub dodge: i8, #[INTEGER] - pub parry: u8, + pub parry: i8, #[INTEGER] - pub speed: u8, + pub speed: i8, #[INTEGER] - pub stealth: u8, + pub stealth: i8, pub category: String, pub target: String, pub special: String, #[INTEGER] - pub action_cost: u8, + pub action_cost: i8, pub reload_cost: String, #[INTEGER] - pub range: u8, + pub range: i8, #[INTEGER] - pub agility_bonus: u8, + pub agility_bonus: i8, } impl Default for DatabaseEquipementStats { @@ -191,7 +191,7 @@ impl Default for DatabaseEquipementStats { #[doc(hidden)] macro_rules! r { () => { - fastrand::u8(1..u8::MAX) + fastrand::i8(1..i8::MAX) }; } // TODO: Make this a test requirement or hide it behind a profile @@ -199,11 +199,11 @@ impl InnerEquipementStats { /// Testing function to fuzz data pub fn random_new() -> Self { Self { - id: vec![r!()], - range: r!(), - damage: r!(), - p_damage: r!(), - protection: r!(), + id: vec![r!() as u8], + range: r!() - 10, + damage: r!() - 10, + p_damage: r!() - 10, + protection: r!() - 10, ..Default::default() } } @@ -213,11 +213,11 @@ impl DatabaseEquipementStats { /// Testing function to fuzz data pub fn random_new() -> Self { Self { - id: r!(), - range: r!(), - damage: r!(), - p_damage: r!(), - protection: r!(), + id: r!() as u8, + range: r!() - 19, + damage: r!() - 10, + p_damage: r!() - 10, + protection: r!() - 10, ..Default::default() } } -- 2.45.1 From 06b8fa7979dd983f7c5dc68b1ed045660ab1059d Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 21 Feb 2025 05:42:43 +0100 Subject: [PATCH 4/4] Sucessfully imports data on napkin example --- .ignore | 1 + weaponry/databases/weapons.db | Bin 28672 -> 28672 bytes weaponry/examples/test_serialisation_wl.rs | 3 +- weaponry/src/error.rs | 6 ++- .../src/weaponry_structs/equipement_fields.rs | 35 +++++++++--------- .../equipement_impl_basics.rs | 7 +++- .../equipement_impl_database.rs | 6 ++- .../weaponry_structs/equipement_impl_logic.rs | 12 +++--- .../weaponry_structs/equipement_impl_math.rs | 6 +-- .../weaponry_structs/equipement_structs.rs | 25 +++++++------ weaponry/src/weaponry_structs/mod.rs | 2 +- 11 files changed, 58 insertions(+), 45 deletions(-) create mode 100644 .ignore diff --git a/.ignore b/.ignore new file mode 100644 index 0000000..8e062ad --- /dev/null +++ b/.ignore @@ -0,0 +1 @@ +*.drawio diff --git a/weaponry/databases/weapons.db b/weaponry/databases/weapons.db index d0343f193cd15f2ecd4c903207456e5b6c37d814..7e68296556a73157c15701a56fda77c29bc0a713 100644 GIT binary patch literal 28672 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 delta 675 zcmY*WOH30{6n$^rOy|>fhEk^Obc$073k)Wrq$P@Cgb+T8!RV$zA{~4rBSUL{64MZI zhdan!xP*l<)|E{cYFM+qTs@}Ig+ZXX}3cW&B`N{7o zH;#to(&%@e-AtKr_3t1M1?_*t@egOtUr#0$k?0dyx zWj)^4KXAMc9*1){59bXNry*@jhT8SSLbmL>%YnuQ8EWBP$VW$E%)A6g(HYru4vko0 zEJ<)x55gNm4P19Jd`Utyn*(uP|Is_|F16oRa=52PIM#^E#{d$SsQ&;7erUAA+aGj_e&pmze{& ztyCE=IE=$#Y8wjRS@ep`K5@qCmgII5xTXT1^#E*|Q;?3$!h3Vl=OQ%jWpqL5uWxWM zW^%4uub!AEbw2*pO2mU48Nd_yvU7*7(rl@CGfUTGKche$2x|)?p2zB4wk;b8pde7VkZF?*68<#P% A3;+NC diff --git a/weaponry/examples/test_serialisation_wl.rs b/weaponry/examples/test_serialisation_wl.rs index abd1d3f..d5d9ad0 100644 --- a/weaponry/examples/test_serialisation_wl.rs +++ b/weaponry/examples/test_serialisation_wl.rs @@ -26,6 +26,7 @@ fn main() { // }) // .sum::(); let f = intermediate_deserialisation.iter().fold((0, 0), |val, res| (val.0 + res.is_ok() as usize, val.1 + 1_usize)); - println!("Final data {:#?}", intermediate_deserialisation); + // println!("Final data {:#?}", intermediate_deserialisation); + println!("Failed to parse: {:#?}", intermediate_deserialisation.into_iter().filter_map(|v| v.err()).collect::>()); println!("Succeded in parsing {}/{}", f.0, f.1); } diff --git a/weaponry/src/error.rs b/weaponry/src/error.rs index dff152a..808b9d8 100644 --- a/weaponry/src/error.rs +++ b/weaponry/src/error.rs @@ -20,10 +20,14 @@ pub enum FatalEquipementError { #[error("Deserialisation from json failed : {0}")] SerdeJSON(#[from] serde_json::Error), - #[error("Deserialisation from json failed at line {line} : {error}]")] + #[error( + "Deserialisation from json failed at line {line} on file {file} while trying to parse the value: {parsed_value}: {error}]" + )] SerdeJSONAt { line: String, + file: String, error: serde_json::Error, + parsed_value: String, }, #[error("Couldn't convert into type {origin_type} with data {data}")] diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index dd6efeb..cd52da0 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -7,8 +7,6 @@ use std::fmt::Display; use std::ops::Add; use strum::Display; -use crate::error::FatalEquipementError; - #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only @@ -36,21 +34,21 @@ pub enum PhysicalDamageType { Pierce, } -impl TryFrom<&str> for PhysicalDamageType { - type Error = FatalEquipementError; +// impl TryFrom<&str> for PhysicalDamageType { +// type Error = FatalEquipementError; - fn try_from(value: &str) -> Result { - match value.to_ascii_lowercase().as_str() { - "blunt" => Ok(Self::Blunt), - "slash" => Ok(Self::Slash), - "pierce" => Ok(Self::Pierce), - _ => Err(FatalEquipementError::Conversion { - origin_type: std::any::type_name::().to_owned(), - data: value.to_string(), - }), - } - } -} +// fn try_from(value: &str) -> Result { +// match value.to_ascii_lowercase().as_str() { +// "blunt" => Ok(Self::Blunt), +// "slash" => Ok(Self::Slash), +// "pierce" => Ok(Self::Pierce), +// _ => Err(FatalEquipementError::Conversion { +// origin_type: std::any::type_name::().to_owned(), +// data: value.to_string(), +// }), +// } +// } +// } /// Weapon damage, combining the base weapon damage type and it's level /// @@ -149,7 +147,7 @@ pub enum WeaponCategory { /// The list of initial weapon meta categories #[allow(clippy::missing_docs_in_private_items, missing_docs)] #[derive(Clone, Debug, PartialEq, Display, Deserialize, Serialize, strum::EnumString)] -pub enum WeaponMetaCategory { +pub enum WeaponMacroCategory { Staves, Blunt, Slash, @@ -157,6 +155,9 @@ pub enum WeaponMetaCategory { Armor, Shields, Exotic, + /// A custom none category, used to forbid a part to be cast upon of from + // TODO: Check the soundness of this implementation + None, } #[cfg(test)] diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index 3d27023..509ea8e 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -42,7 +42,10 @@ impl From for Equipement { // TODO : Checks that this is exactly desired behavious // :Also check for Cross Weapon/Armor contamination // Checks that the nature is compatible with the previous iteration - filter_function: FilterFunction::new(&|sel, lhs| match (&sel.target, &lhs.category) { + filter_function: FilterFunction::new(&|sel, lhs| match ( + &sel.target, + &lhs.macro_category, + ) { (Some(a), Some(b)) => a == b, (None, None) => true, _ => false, @@ -83,7 +86,7 @@ impl Display for InnerEquipementStats { self.cost, self.difficulty, self.tier, - self.category + self.macro_category .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 9541279..58611ac 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -77,7 +77,9 @@ impl FixedRecipe for EquipementFixedRecipe { macro_rules! from_serde { ($value: expr) => { serde_json::from_str(&$value).map_err(|error| FatalEquipementError::SerdeJSONAt { - line: format!("{} line {}", file!(), line!()), + line: line!().to_string(), + file: file!().to_string(), + parsed_value: $value.to_string(), error, }) }; @@ -112,7 +114,7 @@ impl TryFrom for InnerEquipementStats { parry: value.parry, speed: value.speed, stealth: value.stealth, - category: from_serde!(&value.category)?, + macro_category: from_serde!(&value.category)?, target: from_serde!(&value.target)?, special: from_serde!(&value.special)?, action_cost: value.action_cost, diff --git a/weaponry/src/weaponry_structs/equipement_impl_logic.rs b/weaponry/src/weaponry_structs/equipement_impl_logic.rs index a7f5d6a..ae5370c 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, SpecialCategory, - equipement_fields::{PhysicalDamageType, WeaponMetaCategory}, + equipement_fields::{PhysicalDamageType, WeaponMacroCategory}, equipement_structs::InnerEquipementStats, }, }; @@ -93,8 +93,8 @@ mod test { rarity: 1, integrity: 2, range: 3, - agility_bonus: 4, - category: Some(WeaponMetaCategory::Staves), + agility_bonus: 4., + macro_category: Some(WeaponMacroCategory::Staves), special: SpecialCategory(vec!["zero".into()]), damage_type: Some(DamageType(vec![DamageMod::Secondary( PhysicalDamageType::Slash, @@ -103,7 +103,7 @@ mod test { }; let i2 = InnerEquipementStats { integrity: 3, - agility_bonus: 5, + agility_bonus: 5., damage: 10, damage_type: Some(DamageType(vec![DamageMod::Primary( PhysicalDamageType::Blunt, @@ -116,10 +116,10 @@ mod test { InnerEquipementStats { rarity: 1, integrity: 5, - agility_bonus: 9, + agility_bonus: 9., damage: 10, range: 3, - category: Some(WeaponMetaCategory::Staves), + macro_category: Some(WeaponMacroCategory::Staves), special: SpecialCategory(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 8a677e8..e6e376d 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_math.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_math.rs @@ -55,9 +55,9 @@ impl std::ops::Add for &InnerEquipementStats { 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 - target: self.target.clone().or(rhs.target.clone()), // Can be further optimized - special: self.special.clone() + rhs.special.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, diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index d74ddfd..e0899ef 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -8,7 +8,7 @@ use crate::interfaces::{FilterFunction, FilterFunctionType}; use more_fields::FieldsAsSlice; use serde::{Deserialize, Serialize}; -use super::{DamageType, SpecialCategory, WeaponCategory, equipement_fields::WeaponMetaCategory}; +use super::{DamageType, SpecialCategory, WeaponCategory, equipement_fields::WeaponMacroCategory}; /// The final equipement list /// @@ -75,17 +75,18 @@ pub struct InnerEquipementStats { pub(super) integrity: i8, pub(super) torque_two_handed: Option, // Might be option (single claw) pub(super) torque_one_handed: Option, // Should be option (bows) - pub(super) dodge: i8, + pub(super) dodge: f32, // I could also use a custom HalfValue pub(super) parry: i8, pub(super) speed: i8, pub(super) stealth: i8, - pub(super) category: Option, - pub(super) target: Option, // TODO: This might be incorrect, to check + /// The initial macro category, in turn combined with other stats it will describe a final category + pub(super) 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 pub(super) special: SpecialCategory, pub(super) action_cost: i8, pub(super) reload_cost: Option, // Shouldn't it be Option ? pub(super) range: i8, // Shoudln't it be Option ? - pub(super) agility_bonus: i8, + pub(super) agility_bonus: f32, // Also convert this one to HalfValue } // TODO: This implementation of default is painfull @@ -129,8 +130,8 @@ pub struct DatabaseEquipementStats { pub integrity: i8, pub torque_two_handed: String, pub torque_one_handed: String, - #[INTEGER] - pub dodge: i8, + #[REAL] + pub dodge: f32, #[INTEGER] pub parry: i8, #[INTEGER] @@ -145,8 +146,8 @@ pub struct DatabaseEquipementStats { pub reload_cost: String, #[INTEGER] pub range: i8, - #[INTEGER] - pub agility_bonus: i8, + #[REAL] + pub agility_bonus: f32, } impl Default for DatabaseEquipementStats { @@ -156,7 +157,7 @@ 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(), + category: serde_json::to_string(&None::).unwrap(), target: serde_json::to_string(&None::).unwrap(), special: serde_json::to_string(&SpecialCategory::default()).unwrap(), reload_cost: serde_json::to_string(&None::).unwrap(), @@ -175,12 +176,12 @@ impl Default for DatabaseEquipementStats { integrity: 0, torque_two_handed: serde_json::to_string(&0).unwrap(), torque_one_handed: serde_json::to_string(&None::).unwrap(), - dodge: 0, + dodge: 0., parry: 0, speed: 0, stealth: 0, range: 0, - agility_bonus: 0, + agility_bonus: 0., action_cost: 0, } } diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index cf3aab5..e4ab206 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -35,5 +35,5 @@ pub use equipement_structs::{Equipement, InitialEquipementList}; // #[allow(unused_imports)] pub use equipement_fields::PhysicalDamageType; pub use equipement_fields::{ - DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory, WeaponMetaCategory, + DamageMod, DamageType, NatureTarget, SpecialCategory, WeaponCategory, WeaponMacroCategory, }; -- 2.45.1