diff --git a/Cargo.toml b/Cargo.toml index 7798d1a..98135cd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ resolver = "3" # edition = "2024" # license = "MIT OR Apache-2.0" [workspace.package] -version = "0.3.10" +version = "0.3.11" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -60,3 +60,4 @@ pretty_assertions = "^1.4" indexmap = {version= "2.14.0", features= ["serde"]} rusqlite = { version = "0.40.1" } # , features = ["bundled"] serde_rusqlite = "0.43.0" +handlebars = "6.4.3" diff --git a/crates/cli_parser/Cargo.toml b/crates/cli_parser/Cargo.toml index bd01c48..392b589 100644 --- a/crates/cli_parser/Cargo.toml +++ b/crates/cli_parser/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "cli_parser" -version = "0.1.7" +version.workspace = true edition = "2024" [dependencies] diff --git a/crates/cli_parser/src/lib.rs b/crates/cli_parser/src/lib.rs index 60266c7..88cd11e 100644 --- a/crates/cli_parser/src/lib.rs +++ b/crates/cli_parser/src/lib.rs @@ -4,12 +4,12 @@ use clap::{Args, Parser, Subcommand}; use config::{ - analysis::AnalysisConfig, + analysis::{AnalysisConfig, WeaponConfig}, fast_tables::FastTableConfig, formatter::FormatterConfig, graph::GraphConfig, make::{HELP_BLOCK_SELECTION, MakeTargets, VerboseLevel}, - monsters::{MonsterConfig, MonsterMarkup}, + monsters::{MonsterConfig, MonsterMarkup, WeaponExport}, statsolver::StatConfig, tablegen::{Craft, TableArgs}, }; @@ -47,6 +47,8 @@ pub enum Commands { Format(FormatterConfig), /// Generate analysis data Analysis(AnalysisConfig), + /// Export all weapon data + Weapons(WeaponConfig), /// Better Generation BetterGen(FastTableConfig), /// Monster database handling @@ -79,6 +81,8 @@ pub struct Config { pub craft: Craft, /// Config for monster exporting pub monster: MonsterMarkup, + /// The config for weapon exporting + pub weapons: WeaponExport, } #[derive(Deserialize)] diff --git a/crates/config/Cargo.toml b/crates/config/Cargo.toml index 95e276a..7046c80 100644 --- a/crates/config/Cargo.toml +++ b/crates/config/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "config" -version = "0.1.1" +version.workspace = true edition = "2024" [dependencies] diff --git a/crates/config/src/analysis.rs b/crates/config/src/analysis.rs index 8e5ca1f..0317c50 100644 --- a/crates/config/src/analysis.rs +++ b/crates/config/src/analysis.rs @@ -42,6 +42,21 @@ pub struct AnalysisConfig { // - average per category } +#[derive(Parser, Debug)] +/// Basic weapon generation +pub struct WeaponConfig { + #[arg(help = format!("The target to perform an analysis on [{:?}]", AnalysisTarget::value_variants()))] + /// The analysis target + pub target: ExportTarget, + + /// The path to export to + #[arg(short, long, default_value = "./Craft")] + pub export: String, + + #[arg(long, default_value_t = String::from("safe"))] + /// What function to sort by + pub sort: String, +} #[derive(ValueEnum, Clone, Debug)] /// The type of analysis to perform pub enum AnalysisTarget { @@ -52,3 +67,10 @@ pub enum AnalysisTarget { /// Analysis over shields Shields, } + +#[derive(ValueEnum, Clone, Debug)] +/// The type of generation to perform +pub enum ExportTarget { + /// Generate all + All, +} diff --git a/crates/config/src/monsters.rs b/crates/config/src/monsters.rs index 7f11205..7de93cf 100644 --- a/crates/config/src/monsters.rs +++ b/crates/config/src/monsters.rs @@ -70,6 +70,13 @@ pub struct MonsterMarkup { pub master_part: String, } +#[derive(Deserialize)] +/// The configuration for the weapon exporting +pub struct WeaponExport { + /// The template to use + pub template: String, +} + /// Ghetto color import pub struct MonsterColor { /// Inner color diff --git a/crates/fast_class/Cargo.toml b/crates/fast_class/Cargo.toml index 61a87d4..af295f2 100644 --- a/crates/fast_class/Cargo.toml +++ b/crates/fast_class/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fast_class" -version = "0.1.0" +version.workspace = true edition = "2024" [dependencies] diff --git a/crates/formatter/Cargo.toml b/crates/formatter/Cargo.toml index 6e13c48..c28fb78 100644 --- a/crates/formatter/Cargo.toml +++ b/crates/formatter/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formatter" -version = "0.1.1" +version.workspace = true edition = "2024" [dependencies] diff --git a/crates/graphs/Cargo.toml b/crates/graphs/Cargo.toml index b002d72..7553ff1 100644 --- a/crates/graphs/Cargo.toml +++ b/crates/graphs/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "graphs" -version = "0.1.4" +version.workspace = true edition = "2024" [dependencies] diff --git a/crates/make/Cargo.toml b/crates/make/Cargo.toml index 3308b2b..d171e8c 100644 --- a/crates/make/Cargo.toml +++ b/crates/make/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "make" -version = "0.1.2" +version.workspace = true edition = "2024" [dependencies] diff --git a/crates/monsters/Cargo.toml b/crates/monsters/Cargo.toml index a252d1c..0eaa6d7 100644 --- a/crates/monsters/Cargo.toml +++ b/crates/monsters/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "monsters" -version = "0.1.1" +version.workspace = true edition = "2024" [dependencies] @@ -13,8 +13,8 @@ serde = {workspace = true} rusqlite = {workspace = true} serde_rusqlite = {workspace = true} serde_json = {workspace = true} +handlebars = {workspace = true} strum = { version = "0.28.0", features = ["derive"] } -handlebars = "6.4.3" [dev-dependencies] regex = {workspace = true} diff --git a/crates/monsters/src/monster_export.rs b/crates/monsters/src/monster_export.rs index 687ce94..2846ead 100644 --- a/crates/monsters/src/monster_export.rs +++ b/crates/monsters/src/monster_export.rs @@ -28,10 +28,6 @@ macro_rules! template_load { }}; } -// pub trait ToTex { -// fn export_to_tex(self) -> String; -// } - handlebars_helper!(plus: |x:i64 ,y:Option| x+y.unwrap_or(0)); fn load_templates(config: &Config) -> Result> { diff --git a/crates/monsters/src/monster_structs.rs b/crates/monsters/src/monster_structs.rs index 5b96e3c..160ed62 100644 --- a/crates/monsters/src/monster_structs.rs +++ b/crates/monsters/src/monster_structs.rs @@ -69,6 +69,9 @@ pub struct CreatureData { /// The HSE danger level #[INTEGER] pub danger_level: i64, + /// The footprints and such + #[TEXT] + pub traces: Option, /// Type of habitat #[TEXT] pub habitat: Option, @@ -271,6 +274,81 @@ pub struct CreatureBodyPart { pub thunder: Option, } +/// Convenient wrapper to allow fetching easily resists to show +pub struct GroupedResists { + inner: IndexMap>>, +} +/// Counts how many items in `list` have a **Some** value for the given `field`. +/// +/// # Example +/// ``` +/// let pierced = count_present!(part_list, piercing); +/// ``` +// macro_rules! count_present { +// ($list:expr, $field:ident) => { +// // We keep everything inside its own block so that it behaves like a single expression. +// let $field = $list +// .body_parts +// .iter() +// .filter(|v| v.$field.is_some()) +// .count(); +// }; +// } +// impl GroupedResists { +// pub fn from_list_body_parts(part_list: CreatureListBodyParts) -> Self { +// let mut inner: IndexMap>> = IndexMap::new(); +// count_present!(part_list, slash); +// count_present!(part_list, blunt); +// count_present!(part_list, piercing); +// count_present!(part_list, celestial); +// count_present!(part_list, fire); +// count_present!(part_list, magma); +// count_present!(part_list, earth); +// count_present!(part_list, wood); +// count_present!(part_list, abyssal); +// count_present!(part_list, wind); +// count_present!(part_list, water); +// count_present!(part_list, ice); +// count_present!(part_list, thunder); +// if slash > 0 { +// for part in part_list.body_parts { +// let key = &part.body_part_name; +// if let Some(values) = inner.get_mut(key) { +// let value = part_list.get(key).to_owned(); +// values.push(value); +// } +// println!("{}", part.body_part_name); +// println!("{}", slash); +// } +// } +// // for elt in &[ +// // "slash", +// // "blunt", +// // "piercing", +// // "celestial", +// // "fire", +// // "magma", +// // "earth", +// // "wood", +// // "abyssal", +// // "wind", +// // "water", +// // "ice", +// // "thunder", +// // ] {} +// // if slash > 0 { // inner.insert( +// // "slash".to_string(), +// // part_list +// // .body_parts +// // .iter() +// // .map(|v| v.slash.clone()) +// // .collect(), +// // ); +// // } +// Self { inner } +// } +// } + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)] /// All creature stats pub struct CreatureStats { diff --git a/crates/ravenous-tools/src/main.rs b/crates/ravenous-tools/src/main.rs index 86d8bf1..de1d5e7 100644 --- a/crates/ravenous-tools/src/main.rs +++ b/crates/ravenous-tools/src/main.rs @@ -13,7 +13,7 @@ use make::make_pdf; use monsters::monsters_dispatch; use stats::stat_solver; use tablegen::table_gen; -use weaponry::analysis::launch_analysis; +use weaponry::{analysis::launch_analysis, export_tex::export_weapons}; // External imports use anyhow::{Context, Result}; @@ -37,6 +37,7 @@ fn main() -> Result<()> { Commands::Graphs(args) => make_graphs(&args, &config), Commands::Format(args) => format_file(&args, &config), Commands::Analysis(args) => Ok(launch_analysis(&args, &config)?), // Not using anyhow but a custom error + Commands::Weapons(args) => Ok(export_weapons(&args, &config)?), // Not using anyhow but a custom error Commands::BetterGen(args) => make_better_gen(&args, &config), Commands::Monsters(args) => monsters_dispatch(&args, &config), } diff --git a/crates/stats/Cargo.toml b/crates/stats/Cargo.toml index 7beae5a..f337877 100644 --- a/crates/stats/Cargo.toml +++ b/crates/stats/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "stats" -version = "0.1.1" +version.workspace = true edition = "2024" [dependencies] diff --git a/crates/tablegen/Cargo.toml b/crates/tablegen/Cargo.toml index 49a0329..6d4499c 100644 --- a/crates/tablegen/Cargo.toml +++ b/crates/tablegen/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tablegen" -version = "0.1.2" +version.workspace = true edition = "2024" [dependencies] diff --git a/crates/weaponry/Cargo.toml b/crates/weaponry/Cargo.toml index b94b176..19586ad 100644 --- a/crates/weaponry/Cargo.toml +++ b/crates/weaponry/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "weaponry" -version = "0.1.1" +version.workspace = true edition = "2024" [dependencies] @@ -15,6 +15,7 @@ probability = "0.20.3" rusqlite = {workspace = true} serde_rusqlite = {workspace = true} serde_json = {workspace = true} +handlebars = {workspace = true} strum = { version = "0.28.0", features = ["derive"] } thiserror = "2.0.18" charming = { version = "0.4.0", features = [] } diff --git a/crates/weaponry/examples/usage_scenario.rs b/crates/weaponry/examples/usage_scenario.rs index 42a3a5e..eb96039 100644 --- a/crates/weaponry/examples/usage_scenario.rs +++ b/crates/weaponry/examples/usage_scenario.rs @@ -103,7 +103,7 @@ fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) { type DynamicFilterType = Box Ordering>; -fn cmd_to_filter(og_entry: &str) -> Result { +pub fn cmd_to_filter(og_entry: &str) -> Result { let (category, entry) = if og_entry.starts_with("cat+") { (true, og_entry.split_at(4).1) } else { diff --git a/crates/weaponry/src/analysis.rs b/crates/weaponry/src/analysis.rs index 6760b84..7db9065 100644 --- a/crates/weaponry/src/analysis.rs +++ b/crates/weaponry/src/analysis.rs @@ -9,7 +9,7 @@ use config::analysis::AnalysisConfig; use crate::{ error::FatalEquipementError, - interfaces::{Reportable, Scenario, ToAnalysis, ToCSV, ToTex}, + interfaces::{Reportable, Scenario, ToAnalysis, ToCSV}, weaponry_structs::{ CrossRecipeScenario, RefinedEquipement, RefinedEquipementList, equipement_scenario::ConfigEquipementScenario, @@ -81,14 +81,7 @@ fn create_graphs(args: &AnalysisConfig, config: &Config, filter: DynamicFilterTy } Err(e) => panic!("{e}"), } - // if args.html_export{} refined_list.write_html(&save_path).unwrap(); - - // if args.csv_export{} - // export_as_csv(&refined_list, &save_path); - - // if args.tex_export{} - // export_as_tex(&refined_list, &save_path); } #[allow(dead_code)] @@ -103,20 +96,20 @@ fn export_as_csv(refined_list: &RefinedEquipementList, save_path: &str) { refined_list.write_csv(Path::new(&format!("{save_path}.csv"))) ); } -/// Export as a tex file in the given directory -/// -/// Generic function dispatching any specific demand to different functions -/// TODO: FINISH IMPLEMENTATION -#[allow(dead_code)] -fn export_as_tex(refined_list: &RefinedEquipementList, save_path: &str) { - let _ = save_path; - println!("{}", refined_list.to_tex()); // TexType - // println!( - // "Saved initial data as {}.html: {:?}", - // save_path, - // refined_list.write_csv(Path::new(&format!("{save_path}.csv"))) - // ); -} +// /// Export as a tex file in the given directory +// /// +// /// Generic function dispatching any specific demand to different functions +// /// TODO: FINISH IMPLEMENTATION +// #[allow(dead_code)] +// fn export_as_tex(refined_list: &RefinedEquipementList, config: &Config, save_path: &str) { +// let _ = save_path; +// println!("{}", refined_list.to_tex(config)); // TexType +// // println!( +// // "Saved initial data as {}.html: {:?}", +// // save_path, +// // refined_list.write_csv(Path::new(&format!("{save_path}.csv"))) +// // ); +// } /// A dynamic filtertype, as a boxed function over two equipement references // #[allow(dead_code)] @@ -129,7 +122,7 @@ type DynamicFilterType = Box bool>; /// /// This informal implementation function as a mini language, /// without any form of formalism, consistency or fixed API -fn cmd_to_filter(og_entry: &str) -> Result { +pub fn cmd_to_filter(og_entry: &str) -> Result { let (category, entry) = if og_entry.starts_with("cat+") { (true, og_entry.split_at(4).1) } else { diff --git a/crates/weaponry/src/error.rs b/crates/weaponry/src/error.rs index ffc4737..7a19384 100644 --- a/crates/weaponry/src/error.rs +++ b/crates/weaponry/src/error.rs @@ -21,6 +21,12 @@ pub enum FatalEquipementError { #[error("Deserialisation from json failed : {0}")] SerdeJSON(#[from] serde_json::Error), + #[error("Error making the template: {0}")] + TemplatingError(#[from] handlebars::TemplateError), + + #[error("Error rendering the template: {0}")] + RenderError(#[from] handlebars::RenderError), + #[error( "Deserialisation from json failed at line {line} on file {file} while trying to parse the value: {parsed_value}: {error}]" )] @@ -47,6 +53,13 @@ pub enum FatalEquipementError { SerdeRSQLite(#[from] serde_rusqlite::Error), } +#[derive(Error, Debug)] +/// Generic error handling +pub enum WeaponGenerationError { + #[error("An unexpected error occured")] + Unexpected, +} + // #[derive(Error, Debug)] // /// Recoverable error, all these error exist to signal a retry or another path that should be taken by the program // pub enum LocalEquipementError { diff --git a/crates/weaponry/src/export_tex.rs b/crates/weaponry/src/export_tex.rs new file mode 100644 index 0000000..b02acc6 --- /dev/null +++ b/crates/weaponry/src/export_tex.rs @@ -0,0 +1,54 @@ +// Workspace: weaponry +// File: weaponry/src/export_tex.rs +//! Module regrouping all generic function related to the exporting as tex +//! + +use std::fs; +use std::io::Write; + +use crate::interfaces::ToTex; +use crate::weaponry_structs::equipement_scenario::ConfigEquipementScenario; +use crate::{interfaces::Scenario, weaponry_structs::RefinedEquipementList}; +use cli_parser::Config; +use config::analysis::WeaponConfig; + +use crate::{error::WeaponGenerationError, weaponry_structs::CrossRecipeScenario}; + +/// Export as a tex file in the given directory +/// +/// Generic function dispatching any specific demand to different functions +/// TODO: FINISH IMPLEMENTATION +pub fn export_as_tex(refined_list: &RefinedEquipementList, config: &Config, save_path: &str) { + let _ = save_path; + println!("{}", refined_list.to_tex(config).unwrap()); // TexType + // println!( + // "Saved initial data as {}.html: {:?}", + // save_path, + // refined_list.write_csv(Path::new(&format!("{save_path}.csv"))) + // ); +} + +/// Export all weapon database as a tex data +pub fn export_weapons(args: &WeaponConfig, config: &Config) -> Result<(), WeaponGenerationError> { + let scenarios = CrossRecipeScenario::new_with_config(ConfigEquipementScenario { + table_name: "Equipements".into(), + db_path: config.data_generation.database.clone(), + shape: Some(()), + materials: None, + nature: Some(()), //(!args.no_natures).then_some(()), + finishing: None, //args.finishing.then_some(()), + }) + .unwrap(); + + // let filter = Box::new(|_: &RefinedEquipement| true); + let refined_list = scenarios.generate_refined_recipes().unwrap(); + // .inner_filter(filter); + + let tex = refined_list.to_tex(config).unwrap(); + + let name = format!("{}gen-forge-table.tex", args.export); + println!("Writing to file {name}"); + let mut f = fs::File::create(name).unwrap(); + writeln!(f, "{}", tex).unwrap(); + Ok(()) +} diff --git a/crates/weaponry/src/interfaces.rs b/crates/weaponry/src/interfaces.rs index 3831367..c838794 100644 --- a/crates/weaponry/src/interfaces.rs +++ b/crates/weaponry/src/interfaces.rs @@ -7,6 +7,7 @@ use std::{path::Path, rc::Rc}; +use cli_parser::Config; use more_fields::FieldsAsSlice; use rusqlite::Connection; use serde::{Serialize, de::DeserializeOwned}; @@ -162,7 +163,7 @@ pub(crate) struct FilterFunction(pub(super) FilterType); /// This element can be converted to tex pub trait ToTex { /// Export the object to a Tex string - fn to_tex(&self) -> String; + fn to_tex(&self, config: &Config) -> Result; } /// This element can be converted to a csv for further analysis diff --git a/crates/weaponry/src/lib.rs b/crates/weaponry/src/lib.rs index bbbdbfe..0942313 100644 --- a/crates/weaponry/src/lib.rs +++ b/crates/weaponry/src/lib.rs @@ -14,6 +14,7 @@ pub mod export; pub mod interfaces; #[macro_use] pub mod weaponry_structs; +pub mod export_tex; /// Signals the function running is unfinished #[macro_export] diff --git a/crates/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/crates/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index ba185c3..fbd2763 100644 --- a/crates/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/crates/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -20,7 +20,8 @@ use crate::{ export::{initial_chart, initial_plot_chart}, interfaces::{RecipeCollection, RefinedList, ToAnalysis}, weaponry_structs::{ - Equipement, InitialEquipementList, + Equipement, InitialEquipementList, WeaponBaseShape, + equipement_fields::WeaponBaseSize, equipement_structs::InnerEquipementStats, equipement_thin_types::{Dices, Precision}, }, @@ -49,6 +50,88 @@ pub struct RefinedEquipementList { pub inner: Vec, } +#[allow(clippy::missing_docs_in_private_items)] +/// The exportable equipement minimum precalculated stats +#[derive(Serialize)] +pub struct ExportableEquipement { + pub name: String, + pub category: Option, + pub maniement: String, + pub damage_base: i8, + pub damage_per: i8, + pub rmax: i8, + pub arbreak: i8, + pub protection: i8, + pub integrity: i8, + pub torque_one_handed: Option, + pub torque_two_handed: Option, + pub modes: String, + pub esquive: String, + pub parrade: String, + pub vitesse: String, + pub discretion: String, + pub difficulty: String, + pub special: String, + pub needs_break: bool, +} + +impl From<&RefinedEquipement> for ExportableEquipement { + fn from(value: &RefinedEquipement) -> Self { + let mut special = Vec::new(); + if value.inner.action_cost != 0 && value.inner.action_cost != 1 { + special.push(format!(r"{}A", value.inner.action_cost)); + } + if let Some(cost) = value.inner.reload_cost { + special.push(format!(r"{cost}\reload{{}}")); + }; + if value.inner.armor_pierce != 0 { + let mut parmure = value.inner.armor_pierce; + match (&value.inner.category_base, &value.inner.category_size) { + (&Some(WeaponBaseShape::Ranged), Some(WeaponBaseSize::Heavy)) => parmure += 1, + (&Some(WeaponBaseShape::Ranged), Some(WeaponBaseSize::SuperHeavy)) => parmure += 1, + _ => (), + } + special.push(format!(r"\Gls{{parmure}} {parmure}")); + } + if value.inner.range != 0 { + let mut range = value.inner.range; + match (&value.inner.category_base, &value.inner.category_size) { + (&Some(WeaponBaseShape::Ranged), Some(WeaponBaseSize::Heavy)) => range += 30, + (&Some(WeaponBaseShape::Ranged), Some(WeaponBaseSize::SuperHeavy)) => range += 60, + _ => (), + } + special.push(format!(r"{range}m")); + } + if value.inner.precision != 0 { + special.push(format!( + r"\glssymbol{{precision}} {:+}", + value.inner.precision + )); + } + Self { + name: value.advanced.display_name.clone(), + maniement: value.inner.get_maniement(), + damage_base: value.inner.damage, + damage_per: value.inner.p_damage, + rmax: value.inner.rmax, + arbreak: value.inner.armor_break, + protection: value.inner.protection, + integrity: value.inner.integrity, + torque_one_handed: value.inner.torque_one_handed, + torque_two_handed: value.inner.torque_two_handed, + modes: value.inner.get_modes(), + esquive: value.inner.dodge.to_string(), + parrade: value.inner.parry.to_string(), + vitesse: value.inner.speed.to_string(), + discretion: value.inner.stealth.to_string(), + difficulty: value.inner.difficulty.to_string(), + category: value.inner.category_base, + special: special.join(", "), + needs_break: false, + } + } +} + // DONE: The use of Deref could be a subtle gotcha impl Deref for RefinedEquipementList { type Target = Vec; @@ -255,7 +338,7 @@ pub struct AdvancedStats { } impl From<&InnerEquipementStats> for AdvancedStats { fn from(value: &InnerEquipementStats) -> Self { - let max_damage_per_attack = (value.damage + value.p_damage * (value.rmax)) as f64; + let max_damage_per_attack = (value.damage + value.p_damage * (value.rmax - 1)) as f64; let armor_break_per_attack = (value.armor_break as f64 + value.antimaterial as f64).min(max_damage_per_attack); let variance = (value.p_damage * value.rmax) as f64; diff --git a/crates/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/crates/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index 39d045b..9c3d2a3 100644 --- a/crates/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/crates/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -293,7 +293,8 @@ pub(super) fn binomial_dice_distribution( + equipement.p_damage as f64 * (target_dices .saturating_sub(1) - .clamp(0, equipement.rmax as usize)) as f64) + .clamp(0, (equipement.rmax - 1) as usize)) + as f64) * probability_success } else { 0. diff --git a/crates/weaponry/src/weaponry_structs/equipement_fields.rs b/crates/weaponry/src/weaponry_structs/equipement_fields.rs index e3924e7..46d497d 100644 --- a/crates/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/crates/weaponry/src/weaponry_structs/equipement_fields.rs @@ -48,26 +48,65 @@ 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(Copy, Clone, Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord)] +// #[cfg_attr(test, derive(PartialEq))] pub enum PhysicalDamageType { Blunt, Slash, Pierce, } +impl PhysicalDamageType { + /// Get a exportable representation + pub fn export(&self) -> String { + match self { + PhysicalDamageType::Blunt => "\\blunt".to_string(), + PhysicalDamageType::Slash => "\\slash".to_string(), + PhysicalDamageType::Pierce => "\\pierce".to_string(), + } + } +} + /// Weapon damage, combining the base weapon damage type and it's level /// /// Signifying wether the damage is pure or \[secondary\] or \[\[tertiary\]\] #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, Display, Deserialize, Serialize)] -#[cfg_attr(test, derive(PartialEq))] +#[derive(Clone, Debug, Display, Deserialize, Serialize, Eq, PartialEq, PartialOrd, Ord)] pub enum DamageMod { Primary(PhysicalDamageType), Secondary(PhysicalDamageType), Tertiary(PhysicalDamageType), } +impl DamageMod { + /// Get the underlying value of the mod + pub fn underlying(&self) -> PhysicalDamageType { + match self { + DamageMod::Primary(physical_damage_type) => *physical_damage_type, + DamageMod::Secondary(physical_damage_type) => *physical_damage_type, + DamageMod::Tertiary(physical_damage_type) => *physical_damage_type, + } + } + /// Get a exportable representation + pub fn export(&self) -> String { + match self { + DamageMod::Primary(phy) => phy.export(), + DamageMod::Secondary(phy) => format!(r"[{}]", phy.export()), + DamageMod::Tertiary(phy) => format!(r"[[{}]]", phy.export()), + } + } + + /// Does the damagemode contain this physical type + pub fn contains(&self, value: &PhysicalDamageType) -> bool { + self.underlying() == *value + } + + // /// Does the other mod have a better mod variant, only true if the underlying value is the same + // pub fn upgrade(&self, value: &DamageMod) -> bool { + // value > self + // } +} + /// Combined damage type, as a vector of all damage types /// /// Meant to be serialised to tex and deserialized directly from the table @@ -76,6 +115,20 @@ pub enum DamageMod { // TODO: avoid pub make an impl ? pub struct DamageType(Vec); +impl DamageType { + /// Get the best modes from self, stripping redundant ones + pub fn get_best_modes(&self) -> DamageType { + let mut best: Vec = Vec::new(); + for m in self.iter() { + if let Some(_v) = best.iter().find(|v| v.contains(&m.underlying())) { + } else { + best.push(m.clone()); + } + } + Self(best) + } +} + impl Deref for DamageType { type Target = Vec; @@ -229,8 +282,9 @@ pub enum EquipementSerializedCategory { // : This should replace the used MacroCategory /// The Base Shape of the weapon, used to infer the final category of the weapon #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, Display, Deserialize, Serialize, strum::EnumString)] -#[cfg_attr(test, derive(PartialEq))] +#[derive( + Copy, Clone, Debug, Display, Deserialize, Serialize, strum::EnumString, Default, PartialEq, +)] pub enum WeaponBaseShape { Staves, Blunt, @@ -239,6 +293,7 @@ pub enum WeaponBaseShape { Armors, Shields, Exotic, + #[default] None, } diff --git a/crates/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/crates/weaponry/src/weaponry_structs/equipement_impl_basics.rs index dddb801..8f0cc0f 100644 --- a/crates/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/crates/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -10,6 +10,7 @@ use super::equipement_structs::InnerEquipementStats; use crate::interfaces::{FilterFunction, Reportable}; +use crate::weaponry_structs::equipement_fields::WeaponBaseSize; use crate::weaponry_structs::{SpecialField, WeaponBaseShape}; use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; use std::{ @@ -228,13 +229,38 @@ macro_rules! first_correct_option { }; } +/// Fixing the french grammar in the worst way possible +fn stupid_adjective_fix(name_base: &str, adj: String) -> String { + let plur = || format!("{adj}s"); + let masc = || match adj.as_str() { + "moyenne" => "moyen".to_owned(), + "légère" => "léger".to_owned(), + _ => adj[..adj.len() - 1].to_string(), + }; + match name_base { + "Griffes" => plur(), + "Hast" => masc(), + "Marteau" => masc(), + "Arc" => masc(), + "Bouclier" => masc(), + _ => adj, + } +} impl std::ops::Add for &InnerEquipementStats { type Output = InnerEquipementStats; fn add(self, rhs: Self) -> Self::Output { InnerEquipementStats { id: add_to_vec!(self.id, rhs.id), - name: add_to_vec!(self.name, rhs.name), + name: add_to_vec!( + self.name, + if let Some(ad) = &rhs.adjective { + vec![stupid_adjective_fix(&self.name[0], ad.clone())] + } else { + rhs.name.clone() + } + ), + adjective: rhs.adjective.clone(), rarity: self.rarity + rhs.rarity, cost: self.cost + rhs.cost, difficulty: self.difficulty + rhs.difficulty, @@ -285,6 +311,45 @@ impl std::ops::Add for SpecialField { } } +impl InnerEquipementStats { + /// Get the maniement as a printable string + pub fn get_maniement(&self) -> String { + match &self.category_size { + Some(WeaponBaseSize::SuperHeavy) => match self.name[0].as_str() { + "Griffes" => "Frienzä", + "Marteau" => "Rhödarak", + "Épée" => "Haroth", + "Hache" => "Kahml", + "Hast" => "Paysagiste", + "Arc" => "Distance", + "Arbalète" => "Distance", + _ => "-", + } + .to_string(), + + _ => match &self.category_base { + Some(WeaponBaseShape::Staves) => "Hast".to_string(), + Some(WeaponBaseShape::Blunt) => "Contondante".to_string(), + Some(WeaponBaseShape::Slash) => "Tranchante".to_string(), + Some(WeaponBaseShape::Ranged) => "Distance".to_string(), + _ => "-".to_string(), + }, + } + } + /// Get the modes as a printable string + pub fn get_modes(&self) -> String { + match &self.damage_type { + Some(t) => t + .get_best_modes() + .iter() + .map(|v| v.export()) + .collect::>() + .join(","), + None => "-".to_string(), + } + } +} + #[cfg(test)] mod test { use crate::{ diff --git a/crates/weaponry/src/weaponry_structs/equipement_impl_database.rs b/crates/weaponry/src/weaponry_structs/equipement_impl_database.rs index 5a5c4c9..c9fdb5e 100644 --- a/crates/weaponry/src/weaponry_structs/equipement_impl_database.rs +++ b/crates/weaponry/src/weaponry_structs/equipement_impl_database.rs @@ -92,6 +92,7 @@ impl TryFrom for InnerEquipementStats { Ok(Self { id: vec![value.id], // Special case where manual is better than serde name: vec![value.name], + adjective: value.adjective, rarity: value.rarity, // Generic case, into(), serde or cast are equivalent cost: value.cost, difficulty: value.difficulty, diff --git a/crates/weaponry/src/weaponry_structs/equipement_impl_io.rs b/crates/weaponry/src/weaponry_structs/equipement_impl_io.rs index acafc60..23ea936 100644 --- a/crates/weaponry/src/weaponry_structs/equipement_impl_io.rs +++ b/crates/weaponry/src/weaponry_structs/equipement_impl_io.rs @@ -2,8 +2,15 @@ // File: weaponry/src/weaponry_structs/equipement_impl_io.rs //! All implementation IO specific (mainly export and serde) +use cli_parser::Config; +use handlebars::Handlebars; + use super::equipement_advanced_repr::RefinedEquipementList; -use crate::interfaces::{ToCSV, ToTex}; +use crate::{ + error::FatalEquipementError, + interfaces::{ToCSV, ToTex}, + weaponry_structs::equipement_advanced_repr::ExportableEquipement, +}; use std::path::Path; impl ToCSV for RefinedEquipementList { @@ -17,10 +24,24 @@ impl ToCSV for RefinedEquipementList { } impl ToTex for RefinedEquipementList { - // Nom & \rotbx{Rareté} & \rotbx{Dégâts} & + & \rotbx{R.Max} & \rotbx{Armr.B} & \rotbx{Protbx} & \rotbx{Int.} & \rotbx{Deux M} & \rotbx{Une M} & \rotbx{Esq.} & \rotbx{Parr.} & \rotbx{Vitesse} & \rotbx{Discr.} & \rotbx{Catégorie} & \rotbx{Modes} & \rotbx{Spécial} \\ - fn to_tex(&self) -> String { - self.inner.iter().for_each(|m| println!("{:?}", m.inner)); - todo!() + fn to_tex(&self, config: &Config) -> Result { + let mut template = Handlebars::new(); + template.register_template_string("weapons", &config.weapons.template)?; + let mut data = self + .iter() + .map(std::convert::Into::::into) + .collect::>(); + + for i in 0..data.len() - 1 { + if data[i].category != data[i + 1].category + && data[i + 1].category == Some(super::WeaponBaseShape::Shields) + { + data[i].needs_break = true; + } + } + let r = template.render("weapons", &data)?; + // println!("{}", r); + Ok(r) } } diff --git a/crates/weaponry/src/weaponry_structs/equipement_structs.rs b/crates/weaponry/src/weaponry_structs/equipement_structs.rs index 28891e6..4289952 100644 --- a/crates/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/crates/weaponry/src/weaponry_structs/equipement_structs.rs @@ -80,6 +80,7 @@ impl FilterFunction { pub struct InnerEquipementStats { pub id: Vec, pub name: Vec, + pub adjective: Option, pub(super) rarity: i8, pub(super) cost: i8, pub(super) difficulty: i8, @@ -130,6 +131,8 @@ pub struct DatabaseEquipementStats { pub id: u8, pub meta_category: String, pub name: String, + #[TEXT] + pub adjective: Option, #[INTEGER] pub rarity: i8, #[INTEGER] @@ -212,6 +215,7 @@ impl Default for DatabaseEquipementStats { range: 0, agility_bonus: 0., action_cost: 0, + adjective: None, } } } diff --git a/helper_config.toml b/helper_config.toml index e36b1c0..dd8d083 100644 --- a/helper_config.toml +++ b/helper_config.toml @@ -2,7 +2,6 @@ # This value should be overwriten by a relative path database = "./ravenous_databases/weapons.db" - [classes] header = '''\begin{}[ presep = 0pt, postsep = 0pt, @@ -156,7 +155,7 @@ common_part = ''' cell{1}{1}={c=2}{c}, } -{{#if image}}\includegraphics[height=5cm]{ {{{image}}} } & \\{{/if}} +{{#if image}}\includegraphics[height=5cm]{ {{{~image~}}} } & \\ {{/if}} & \\ Nom & {{{name}}} \\ {{#if denomination}}Dénomination & {{{denomination}}} \\ @@ -230,7 +229,7 @@ master_part = ''' \SetCell{c} Res & \slash & \pierce & \blunt & \symceleste & \symfire & \symearth & \symwood & \symmagma & \symabyss & \symwater & \symwind & \symice & \symthunder \\ \hline {{#each body_parts.body_parts}} -\SetCell{font=\footnotesize} {{{body_part_name}}} & ${{{slash}}} $ & ${{{pierce}}} $ & ${{{blunt}}} $ & ${{{celestial}}} $ & ${{{fire}}} $ & ${{{earth}}} $ & ${{{wood}}} $ & ${{{magma}}} $ & ${{{celeste}}} $ & ${{{water}}} $ & ${{{wind}}} $ & ${{{ice}}} $ & ${{{thunder}}} $ \\ +\SetCell{font=\footnotesize} {{{body_part_name}}} & ${{{slash}}} $ & ${{{pierce}}} $ & ${{{blunt}}} $ & ${{{celestial}}} $ & ${{{fire}}} $ & ${{{earth}}} $ & ${{{wood}}} $ & ${{{magma}}} $ & ${{{celeste}}} $ & ${{{water}}} $ & ${{{wind}}} $ & ${{{ice}}} $ & ${{{thunder}}} $ \\ {{/each}} \end{tblr} \end{center} @@ -263,16 +262,16 @@ master_part = ''' hspan=minimal, colsep=2pt, row{2}={font=\tiny}, - rowshead=2, + rowhead=2, } & & & & & \SetCell[c=2]{c} Coûts & & & \SetCell[c=2]{c} Dégâts & & & \SetCell[c=2]{c} Seuils & \\ \cline{6-7} \cline{9-10} \cline{12-13} {{#each all_attacks.phases as | phase |}} \SetHline{1}{0pt} {{#if @first}} - & {\scriptsize\SetCell{white} \textsc{ {{{@key}}} }} & {Type} & {Préquis} & \rb{Ciblage} & \rb{Fatigue} & \rb{Action} & \rb{Élément} & \rb{Fatigue} & \SetCell{c} \rb{Normaux} & {Effets} & \rb{Parade} & \rb{Esquive} \\ + & {\scriptsize\SetCell{white} \textsc{ {{{~@key~}}} }} & {Type} & {Préquis} & \rb{Ciblage} & \rb{Fatigue} & \rb{Action} & \rb{Élément} & \rb{Fatigue} & \SetCell{c} \rb{Normaux} & {Effets} & \rb{Parade} & \rb{Esquive} \\ {{else}} -\SetCell[c=13]{white} \textsc{ {{{@key}}} } & & & & & & & & & & \\ +\SetCell[c=13]{white} \textsc{ {{{~@key~}}} } & & & & & & & & & & \\ {{/if}} {{#each phase as | attack_group |}} \hline @@ -290,7 +289,7 @@ master_part = ''' {{#with data}} \pagebreak \begin{tblr}{ - colspec={X[7] {{#if intent_graph}}|X[3] {{/if}} }, + colspec={X[7] {{#if intent_graph}}|X[3] {{/if~}} }, rowspec={X[c] X[j,h,8cm]}, hline{2}, row{2}={font=\footnotesize}, @@ -331,3 +330,37 @@ BIS: ravredD BYP: ravredD ''' default_color='' + + +[weapons] +template=''' +\begin{landscape}\begin{center} +\begin{longtblr}[ + entry = none, + label = none, +]{ + colspec = {|QQQQQQQQQQQQQQQQQ|}, + cells = {font = \footnotesize\selectfont}, + row{1} = {bg=cobluel, fg=white}, + row{even} = {coblueL}, + hspan = minimal, vspan=minimal, + colsep = 2mm, abovesep=0px,belowsep=0px, leftsep=3px, rightsep=3px, + rowhead = 1, +} +\hline +{Forme} & {Maniement} & {\damagew} & + & {R.Max} & \arbreakw & \protection & \integrite & $\mathbb{T}$2 & $\mathbb{T}$1 & {Modes} & {Esq.} & {Par.} & {Vit.} & {Disc.} & {Spécial} & {Diff.} \\ +\hline +{{#each this}} +{{name}} & {{maniement}} & {{damage_base}} & {{damage_per}} & {{rmax}} & {{arbreak}} & {{protection}} & {{integrity}} & {{torque_two_handed}} & {{torque_one_handed}} & $\mathbf{ {{{~modes~}}} }$ & {{esquive}} & {{parrade}} & {{vitesse}} & {{discretion}} & {{{special}}} & \ddlvl{ {{~difficulty~}} } \\ +{{#if needs_break}} +\hline +\hline +{{/if}} +{{/each}} + \hline +\end{longtblr} +\end{center} +\end{landscape} + ''' + +# Nom & \rotbx{Rareté} & \rotbx{Dégâts} & + & \rotbx{R.Max} & \rotbx{Armr.B} & \rotbx{Protbx} & \rotbx{Int.} & \rotbx{Deux M} & \rotbx{Une M} & \rotbx{Esq.} & \rotbx{Parr.} & \rotbx{Vitesse} & \rotbx{Discr.} & \rotbx{Catégorie} & \rotbx{Modes} & \rotbx{Spécial} \\ diff --git a/ravenous_databases b/ravenous_databases index 5570da8..1493491 160000 --- a/ravenous_databases +++ b/ravenous_databases @@ -1 +1 @@ -Subproject commit 5570da8b814f0d3925d0369131ae9baad72a31e8 +Subproject commit 14934910a40cd5fdee09f9ef7df75e1e4d0f2288