From a3b0f4a74487f2f7d8c7efb57dcd0f2883b6ea78 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 25 Jul 2026 06:06:31 +0200 Subject: [PATCH] Refactor --- crates/config/src/monsters.rs | 3 + crates/monsters/src/monster_analysis.rs | 344 +----------------- .../src/monster_analysis/defense_analysis.rs | 229 ++++++++++++ .../monsters/src/monster_analysis/helpers.rs | 40 ++ crates/monsters/src/monster_database.rs | 10 +- crates/monsters/src/monster_export.rs | 2 +- crates/monsters/src/monster_render.rs | 70 +++- 7 files changed, 355 insertions(+), 343 deletions(-) create mode 100644 crates/monsters/src/monster_analysis/defense_analysis.rs diff --git a/crates/config/src/monsters.rs b/crates/config/src/monsters.rs index 6f94eaa..4f0af23 100644 --- a/crates/config/src/monsters.rs +++ b/crates/config/src/monsters.rs @@ -44,6 +44,9 @@ pub struct MonsterConfig { /// Show extra balancing data #[arg(long, default_value_t = false)] pub show_profiles: bool, + /// Data filter + #[arg(long, default_value = "show_to_master = 1")] + pub filter: Option, // /// Defense profile // #[arg(long, default_value_t=DefenseMode::Best)] // pub defense_mode: DefenseMode, diff --git a/crates/monsters/src/monster_analysis.rs b/crates/monsters/src/monster_analysis.rs index 2025a6b..4de1d06 100644 --- a/crates/monsters/src/monster_analysis.rs +++ b/crates/monsters/src/monster_analysis.rs @@ -1,22 +1,19 @@ //! Monster export module #![allow(dead_code)] -use comfy_table::{Cell, Color, modifiers}; -use more_fields::FieldsAsSlice; +use comfy_table::modifiers; use crate::{ Config, Connection, MonsterConfig, - monster_analysis::{ - helpers::{binomial_dice_distribution, how_much_with_succeses}, - monster_analysis_structs::DefenseMode, - }, + monster_analysis::monster_analysis_structs::DefenseMode, monster_database::{fetch_all_creature_data, fetch_all_player_data}, - monster_render::{ToCell, ToRow, ToTable}, - monster_structs::{CreatureBodyPart, FullMonster, PlayerBalancing, ProfileHSE, ProfileStance}, + monster_render::ToCell, + monster_structs::{PlayerBalancing, ProfileStance}, }; pub mod attack_analysis; -mod helpers; +pub mod helpers; use std::collections::HashMap; +pub mod defense_analysis; pub mod monster_analysis_structs; /// Shows balancing information for monsters and players. @@ -26,7 +23,7 @@ pub fn show_balancing_data( connection: Connection, ) -> Result<(), anyhow::Error> { let _ = args; - let data = fetch_all_creature_data(&connection, config)?; + let data = fetch_all_creature_data(&connection, config, args.filter.as_deref())?; let player_data = fetch_all_player_data(&connection, config)?; for creature in data { @@ -42,11 +39,10 @@ pub fn show_balancing_data( n => format!("{} x {}", creature.name, n), } .to_cell() - .fg(Color::Blue), // .add_attribute(comfy_table::Attribute::Reverse), + .fg(comfy_table::Color::Blue), // .add_attribute(comfy_table::Attribute::Reverse), ]); println!("{table}"); - let player_level = &creature.balancing.profile_hse; let available_profiles = player_data .clone() @@ -59,328 +55,8 @@ pub fn show_balancing_data( .map(|profile| (profile.profile_stance, profile)) .collect(); - display_player_attacks(args, &creature, &profiles, DefenseMode::Worst); - display_monster_attacks(args, creature, &profiles, DefenseMode::Best); + defense_analysis::display_player_attacks(args, &creature, &profiles, DefenseMode::Worst); + defense_analysis::display_monster_attacks(args, creature, &profiles, DefenseMode::Best); } Ok(()) } - -fn display_player_attacks( - args: &MonsterConfig, - creature: &FullMonster, - profiles: &HashMap, - mode: DefenseMode, -) { - let _ = args; - let _ = mode; - let r = &creature - .body_parts - .body_parts - .iter() - .map(|body_part| { - let ratio = creature.balancing.monster_groupsize as f64 - / creature.balancing.player_groupsize as f64; - let damage_done_p1 = - damage_done_to_part(body_part, &profiles[&ProfileStance::Neutral], Phases::P1); - let damage_done_p2 = - damage_done_to_part(body_part, &profiles[&ProfileStance::Neutral], Phases::P2); - let time_to_p2 = ratio * body_part.integrity_p1.unwrap() as f64 / damage_done_p1.ab_t; - let time_to_kill = ratio - * (body_part.life_points_p1.unwrap() as f64 / damage_done_p1.hp_t - + body_part.life_points_p2.unwrap_or(0) as f64 / damage_done_p2.hp_t); - let time_to_armorbreak = - ratio * (body_part.integrity_p1.unwrap() as f64 / damage_done_p1.ab_t); - - DefenseReport { - id: creature.balancing.creature_id, - name: creature.name.clone(), - part_name: body_part.body_part_name.clone(), - profile_hse: creature.balancing.profile_hse.clone(), - time_to_p2, - time_to_p2_target: creature.balancing.time_to_p2, - time_to_armorbreak, - time_to_player_kill: creature.balancing.time_to_player_kill, - monster_groupsize: creature.balancing.monster_groupsize, - player_groupsize: creature.balancing.player_groupsize, - time_to_kill, - time_to_kill_target: creature.balancing.time_to_kill, - damage_per_turn_p1: damage_done_p1.hp_t, - damage_per_turn_p2: damage_done_p2.hp_t, - health_p1: body_part.life_points_p1.unwrap(), - health_p2: body_part.life_points_p2.unwrap_or(0), - time_to_armorbreak_target: creature.balancing.time_to_armorbreak, - armor_break_per_turn: damage_done_p1.ab_t, - integrity_p1: body_part.integrity_p1.unwrap(), - } - }) - .collect::>(); - println!("{}", r.to_table()); -} - -/// Shorten a string so that its final length (including the three‑dot marker) does not exceed `size`. -/// -/// If `size` is smaller than four the function simply truncates to that length -/// (there’s no room for “…”). -/// -/// # Parameters -/// * `s` – The string slice to shorten. -/// * `size` – Maximum length of the returned string, including the ellipsis. -pub fn shorten_string(s: &str, size: usize) -> String { - // If it already fits, just return a copy. - if s.len() <= size { - return s.to_owned(); - } - - // No room for "…" + at least one char each side → just cut off. - if size < 4 { - return s.chars().take(size).collect(); - } - - // How many chars we keep from the front / back? - let usable = size - 3; // length available for real characters - let half = usable / 2; // baseline number of chars per side - let extra = usable % 2; // if odd, give one more to the front - - let front_len = half + extra; - let back_len = half; - - // Grab the required portions. - let front: String = s.chars().take(front_len).collect(); - let back: String = s - .chars() - .rev() // reverse for an easy “take last N” - .take(back_len) - .collect::() - .chars() - .rev() // bring them back to normal order - .collect(); - - format!("{}...{}", front, back) -} -#[derive(Clone, Copy)] -pub enum Phases { - P1, - P2, -} -fn damage_done_to_part( - part: &CreatureBodyPart, - profile: &PlayerBalancing, - phase: Phases, -) -> DamageDealtByPlayer { - let threshold = match phase { - Phases::P1 => part.threshold_p1, - Phases::P2 => part.threshold_p2, - } - .unwrap() - + profile.precision; - let (_integrity, protection) = match phase { - Phases::P1 => (part.integrity_p1.unwrap(), part.protection_p1.unwrap()), - Phases::P2 => (part.integrity_p2.unwrap(), part.protection_p2.unwrap()), - }; - let damage_profile: Vec = (1..profile.max_successes_off) - .map(|v| (v as f64 * profile.damage_per_s) as i64) - .collect(); - // Pick the best damage out of all scenarios: - // Scenario A : One big hit - // Scenario B : Two half hits - let damage_a = damage_with_profile(&damage_profile, threshold, profile.successes_off); - let damage_b1 = damage_with_profile(&damage_profile, threshold, profile.successes_off / 2); - let damage_b2 = damage_with_profile( - &damage_profile, - threshold, - profile.successes_off - profile.successes_off / 2, - ); - let ab_a = (damage_a - protection as f64).max(0.); - let ab_b1 = (damage_b1 - protection as f64).max(0.); - let ab_b2 = (damage_b2 - protection as f64).max(0.); - let hp_t = damage_a.max(damage_b1 + damage_b2); - let ab_t = ab_a.max(ab_b1 + ab_b2); - - DamageDealtByPlayer { - damage_a, - damage_b1, - damage_b2, - ab_a, - ab_b1, - ab_b2, - hp_t, - ab_t, - } -} -pub(super) struct DamageDealtByPlayer { - damage_a: f64, - damage_b1: f64, - damage_b2: f64, - ab_a: f64, - ab_b1: f64, - ab_b2: f64, - hp_t: f64, - ab_t: f64, -} - -fn damage_with_profile(damage_profile: &[i64], threshold: i64, dices: i64) -> f64 { - let damage = binomial_dice_distribution(threshold, dices); - damage - .iter() - .map(|(d, p)| how_much_with_succeses(damage_profile, *d) as f64 * p) - .sum::() -} - -// 🠰 -impl ToRow for DefenseReport { - fn to_row(&self) -> comfy_table::Row { - let row: Vec = vec![ - format!("{:?}", self.id).to_cell(), - shorten_string(&self.part_name.to_string(), 18).to_cell(), - format!("{:.1?}/{}", self.damage_per_turn_p1, self.health_p1) - .to_cell() - .fg(Color::DarkGrey), - compare_vals("t", self.time_to_p2, self.time_to_p2_target as f64), - format!("{:.1?}/{}", self.damage_per_turn_p2, self.health_p2) - .to_cell() - .fg(Color::DarkGrey), - compare_vals("t", self.time_to_kill, self.time_to_kill_target as f64), - format!("{:.1?}/{}", self.armor_break_per_turn, self.integrity_p1) - .to_cell() - .fg(Color::DarkGrey), - compare_vals( - "t", - self.time_to_armorbreak, - self.time_to_armorbreak_target as f64, - ), - ]; - row.into() - } -} - -fn fmt_target(v: f64) -> String { - const TOO_MUCH: f64 = 1_000_000_000_000_000.0; - const TRILLION: f64 = 1_000_000_000_000.0; - const BILLION: f64 = 1_000_000_000.0; - const MILLION: f64 = 1_000_000.0; - const THOUSAND: f64 = 1_000.0; - - match v { - _ if v >= TOO_MUCH => "⇑⇑⇑⇑B".to_string(), - _ if v >= TRILLION => format!("⇑{:.1}T", v / TRILLION), - _ if v >= BILLION => format!("⇑{:.1}B", v / BILLION), - _ if v >= MILLION => format!("⇑{:.1}M", v / MILLION), - _ if v >= THOUSAND => format!("⇑{:.1}k", v / THOUSAND), - _ => format!("{:.1}", v), - } -} -fn compare_vals(unit: &str, actual: f64, target: f64) -> Cell { - let pct_diff = ((actual - target).abs() / target) * 100.0; // % diff - // let actual = 100000000000.; - let actual = if pct_diff > 1.0 { - fmt_target(actual) - } else { - format!("{:.1?}", actual) - }; - format!("{}/{:.0?}{}", actual, target, unit) - .to_cell() - .fg(pct_diff_to_colour(pct_diff)) -} - -/// Turn percent‑difference into one of four hard‑coded colours. -fn pct_diff_to_colour(pct_diff: f64) -> Color { - match pct_diff { - p if p < 20.0 => Color::Green, - p if p < 30.0 => Color::Blue, - p if p < 40.0 => Color::Red, - _ => Color::DarkRed, - } -} -/// A snapshot of all defensive metrics for a single monster encounter. -/// Each field has one of three semantic labels: -/// * **Fixed** – inherent properties that do not change during the fight. -/// * **Actual** – metrics computed from a simulation or run‑time analysis. -/// * **Goal** – target values you want to achieve in an optimal strategy. -#[derive(Debug, FieldsAsSlice)] -pub struct DefenseReport { - /// Unique identifier for the monster definition. - #[INTEGER] - pub id: i64, - /// Display name of the monster (human‑readable). - #[SKIP] - pub name: String, - /// The part of the monster’s body that is currently active - pub part_name: String, - /// (Fixed) HSE profile of the monster. - #[SKIP(name = "Profile")] - pub profile_hse: ProfileHSE, - /// Damage per turn while in phase 1. - /// Used when the monster changes behaviour between phases. - #[INTEGER(name = "DPT P1")] - pub damage_per_turn_p1: f64, - /// (Actual) Turns needed to reach phase 2. - /// Computed from the monster’s health and damage output or from simulation data. - #[INTEGER(name = "P1 🠲 P2")] - pub time_to_p2: f64, - /// (Goal) Desired turns to reach phase 2. - /// If the current `time_to_p2` exceeds this value, the fight is considered inefficient. - #[SKIP] - pub time_to_p2_target: i64, - /// Damage per turn while in phase 2. - #[INTEGER(name = "DPT P2")] - pub damage_per_turn_p2: f64, - /// (Actual) Turns needed to kill the monster. - /// Derived from its health and damage per turn or from a run‑time simulation. - #[INTEGER(name = "P2 ➜ 🕇")] - pub time_to_kill: f64, - /// (Goal) Desired turns to kill the monster. - /// If actual `time_to_kill` is larger, you may need to adjust attack power or strategy. - #[SKIP] - pub time_to_kill_target: i64, - /// (Actual) Armor‑breaking damage per turn. - /// This is the rate at which the monster’s armor is degraded during combat. - #[INTEGER(name = "AbPT P1")] - pub armor_break_per_turn: f64, - /// (Actual) Turns until this monster’s armor breaks, i.e. the point - /// at which it stops being able to mitigate incoming damage. - #[INTEGER(name = "TT AB")] - pub time_to_armorbreak: f64, - /// (Goal) Desired turns until the monster’s armor breaks. - /// A lower value indicates a more aggressive strategy. - #[SKIP(name = "ttAB")] - pub time_to_armorbreak_target: i64, - /// (Goal) Average turns to kill a single player - #[SKIP(name = "ttPK")] - pub time_to_player_kill: i64, - /// (Fixed) The number of monsters in a single group. - /// Usually `1`, but can be > 1 for bosses that spawn multiple instances. - #[SKIP] - pub monster_groupsize: i64, - /// (Fixed) Number of players this fight was designed for. - #[SKIP] - pub player_groupsize: i64, - /// (Fixed) Health points during phase 1. - #[SKIP] - pub health_p1: i64, - /// (Fixed) Health points during phase 2. - #[SKIP] - pub health_p2: i64, - /// (Fixed) Integrity points during phase 1, representing how many - /// damage points the monster can take before losing its first phase. - #[SKIP] - pub integrity_p1: i64, -} -fn display_monster_attacks( - args: &MonsterConfig, - creature: FullMonster, - profiles: &HashMap, - mode: DefenseMode, -) { - let attacks: Vec = creature.into(); - if args.show_profiles { - let table = attacks.to_table(); - println!("{table}"); - } - - let mut res = Vec::new(); - for attack in attacks { - let mut report = attack_analysis::all_attacks(args, &attack, profiles, mode); - res.append(&mut report); - } - println!("{}", res.to_table()); -} diff --git a/crates/monsters/src/monster_analysis/defense_analysis.rs b/crates/monsters/src/monster_analysis/defense_analysis.rs new file mode 100644 index 0000000..f3dc8d3 --- /dev/null +++ b/crates/monsters/src/monster_analysis/defense_analysis.rs @@ -0,0 +1,229 @@ +use crate::{ + MonsterConfig, + monster_analysis::{ + DefenseMode, attack_analysis, + helpers::{binomial_dice_distribution, how_much_with_succeses}, + monster_analysis_structs, + }, + monster_render::ToTable, + monster_structs::{CreatureBodyPart, FullMonster, PlayerBalancing, ProfileHSE, ProfileStance}, +}; +use more_fields::FieldsAsSlice; +use std::collections::HashMap; + +pub(crate) fn display_player_attacks( + args: &MonsterConfig, + creature: &FullMonster, + profiles: &HashMap, + mode: DefenseMode, +) { + let _ = args; + let _ = mode; + let r = &creature + .body_parts + .body_parts + .iter() + .map(|body_part| { + let ratio = creature.balancing.monster_groupsize as f64 + / creature.balancing.player_groupsize as f64; + let damage_done_p1 = + damage_done_to_part(body_part, &profiles[&ProfileStance::Neutral], Phases::P1); + let damage_done_p2 = + damage_done_to_part(body_part, &profiles[&ProfileStance::Neutral], Phases::P2); + let time_to_p2 = ratio * body_part.integrity_p1.unwrap() as f64 / damage_done_p1.ab_t; + let time_to_kill = ratio + * (body_part.life_points_p1.unwrap() as f64 / damage_done_p1.hp_t + + body_part.life_points_p2.unwrap_or(0) as f64 / damage_done_p2.hp_t); + let time_to_armorbreak = + ratio * (body_part.integrity_p1.unwrap() as f64 / damage_done_p1.ab_t); + + DefenseReport { + id: creature.balancing.creature_id, + name: creature.name.clone(), + part_name: body_part.body_part_name.clone(), + profile_hse: creature.balancing.profile_hse.clone(), + time_to_p2, + time_to_p2_target: creature.balancing.time_to_p2, + time_to_armorbreak, + time_to_player_kill: creature.balancing.time_to_player_kill, + monster_groupsize: creature.balancing.monster_groupsize, + player_groupsize: creature.balancing.player_groupsize, + time_to_kill, + time_to_kill_target: creature.balancing.time_to_kill, + damage_per_turn_p1: damage_done_p1.hp_t, + damage_per_turn_p2: damage_done_p2.hp_t, + health_p1: body_part.life_points_p1.unwrap(), + health_p2: body_part.life_points_p2.unwrap_or(0), + time_to_armorbreak_target: creature.balancing.time_to_armorbreak, + armor_break_per_turn: damage_done_p1.ab_t, + integrity_p1: body_part.integrity_p1.unwrap(), + } + }) + .collect::>(); + println!("{}", r.to_table()); +} + +pub(crate) fn damage_done_to_part( + part: &CreatureBodyPart, + profile: &PlayerBalancing, + phase: Phases, +) -> DamageDealtByPlayer { + let threshold = match phase { + Phases::P1 => part.threshold_p1, + Phases::P2 => part.threshold_p2, + } + .unwrap() + + profile.precision; + let (_integrity, protection) = match phase { + Phases::P1 => (part.integrity_p1.unwrap(), part.protection_p1.unwrap()), + Phases::P2 => (part.integrity_p2.unwrap(), part.protection_p2.unwrap()), + }; + let damage_profile: Vec = (1..profile.max_successes_off) + .map(|v| (v as f64 * profile.damage_per_s) as i64) + .collect(); + // Pick the best damage out of all scenarios: + // Scenario A : One big hit + // Scenario B : Two half hits + let damage_a = damage_with_profile(&damage_profile, threshold, profile.successes_off); + let damage_b1 = damage_with_profile(&damage_profile, threshold, profile.successes_off / 2); + let damage_b2 = damage_with_profile( + &damage_profile, + threshold, + profile.successes_off - profile.successes_off / 2, + ); + let ab_a = (damage_a - protection as f64).max(0.); + let ab_b1 = (damage_b1 - protection as f64).max(0.); + let ab_b2 = (damage_b2 - protection as f64).max(0.); + let hp_t = damage_a.max(damage_b1 + damage_b2); + let ab_t = ab_a.max(ab_b1 + ab_b2); + + DamageDealtByPlayer { + damage_a, + damage_b1, + damage_b2, + ab_a, + ab_b1, + ab_b2, + hp_t, + ab_t, + } +} +#[derive(Clone, Copy)] +pub enum Phases { + P1, + P2, +} + +pub struct DamageDealtByPlayer { + pub damage_a: f64, + pub damage_b1: f64, + pub damage_b2: f64, + pub ab_a: f64, + pub ab_b1: f64, + pub ab_b2: f64, + pub hp_t: f64, + pub ab_t: f64, +} + +pub(crate) fn damage_with_profile(damage_profile: &[i64], threshold: i64, dices: i64) -> f64 { + let damage = binomial_dice_distribution(threshold, dices); + damage + .iter() + .map(|(d, p)| how_much_with_succeses(damage_profile, *d) as f64 * p) + .sum::() +} + +/// A snapshot of all defensive metrics for a single monster encounter. +/// Each field has one of three semantic labels: +/// * **Fixed** – inherent properties that do not change during the fight. +/// * **Actual** – metrics computed from a simulation or run‑time analysis. +/// * **Goal** – target values you want to achieve in an optimal strategy. +#[derive(Debug, FieldsAsSlice)] +pub struct DefenseReport { + /// Unique identifier for the monster definition. + #[INTEGER] + pub id: i64, + /// Display name of the monster (human‑readable). + #[SKIP] + pub name: String, + /// The part of the monster’s body that is currently active + pub part_name: String, + /// (Fixed) HSE profile of the monster. + #[SKIP(name = "Profile")] + pub profile_hse: ProfileHSE, + /// Damage per turn while in phase 1. + /// Used when the monster changes behaviour between phases. + #[INTEGER(name = "DPT P1")] + pub damage_per_turn_p1: f64, + /// (Actual) Turns needed to reach phase 2. + /// Computed from the monster’s health and damage output or from simulation data. + #[INTEGER(name = "P1 🠲 P2")] + pub time_to_p2: f64, + /// (Goal) Desired turns to reach phase 2. + /// If the current `time_to_p2` exceeds this value, the fight is considered inefficient. + #[SKIP] + pub time_to_p2_target: i64, + /// Damage per turn while in phase 2. + #[INTEGER(name = "DPT P2")] + pub damage_per_turn_p2: f64, + /// (Actual) Turns needed to kill the monster. + /// Derived from its health and damage per turn or from a run‑time simulation. + #[INTEGER(name = "P2 ➜ 🕇")] + pub time_to_kill: f64, + /// (Goal) Desired turns to kill the monster. + /// If actual `time_to_kill` is larger, you may need to adjust attack power or strategy. + #[SKIP] + pub time_to_kill_target: i64, + /// (Actual) Armor‑breaking damage per turn. + /// This is the rate at which the monster’s armor is degraded during combat. + #[INTEGER(name = "AbPT P1")] + pub armor_break_per_turn: f64, + /// (Actual) Turns until this monster’s armor breaks, i.e. the point + /// at which it stops being able to mitigate incoming damage. + #[INTEGER(name = "TT AB")] + pub time_to_armorbreak: f64, + /// (Goal) Desired turns until the monster’s armor breaks. + /// A lower value indicates a more aggressive strategy. + #[SKIP(name = "ttAB")] + pub time_to_armorbreak_target: i64, + /// (Goal) Average turns to kill a single player + #[SKIP(name = "ttPK")] + pub time_to_player_kill: i64, + /// (Fixed) The number of monsters in a single group. + /// Usually `1`, but can be > 1 for bosses that spawn multiple instances. + #[SKIP] + pub monster_groupsize: i64, + /// (Fixed) Number of players this fight was designed for. + #[SKIP] + pub player_groupsize: i64, + /// (Fixed) Health points during phase 1. + #[SKIP] + pub health_p1: i64, + /// (Fixed) Health points during phase 2. + #[SKIP] + pub health_p2: i64, + /// (Fixed) Integrity points during phase 1, representing how many + /// damage points the monster can take before losing its first phase. + #[SKIP] + pub integrity_p1: i64, +} + +pub(crate) fn display_monster_attacks( + args: &MonsterConfig, + creature: FullMonster, + profiles: &HashMap, + mode: DefenseMode, +) { + let attacks: Vec = creature.into(); + if args.show_profiles { + let table = attacks.to_table(); + println!("{table}"); + } + + let mut res = Vec::new(); + for attack in attacks { + let mut report = attack_analysis::all_attacks(args, &attack, profiles, mode); + res.append(&mut report); + } + println!("{}", res.to_table()); +} diff --git a/crates/monsters/src/monster_analysis/helpers.rs b/crates/monsters/src/monster_analysis/helpers.rs index 5281fba..9d604af 100644 --- a/crates/monsters/src/monster_analysis/helpers.rs +++ b/crates/monsters/src/monster_analysis/helpers.rs @@ -31,3 +31,43 @@ pub fn how_much_with_succeses(damage: &[i64], succeses: i64) -> i64 { damage[(succeses - 1).clamp(0_i64, damage.len() as i64 - 1) as usize] } } +/// Shorten a string so that its final length (including the three‑dot marker) does not exceed `size`. +/// +/// If `size` is smaller than four the function simply truncates to that length +/// (there’s no room for “…”). +/// +/// # Parameters +/// * `s` – The string slice to shorten. +/// * `size` – Maximum length of the returned string, including the ellipsis. +pub fn shorten_string(s: &str, size: usize) -> String { + // If it already fits, just return a copy. + if s.len() <= size { + return s.to_owned(); + } + + // No room for "…" + at least one char each side → just cut off. + if size < 4 { + return s.chars().take(size).collect(); + } + + // How many chars we keep from the front / back? + let usable = size - 3; // length available for real characters + let half = usable / 2; // baseline number of chars per side + let extra = usable % 2; // if odd, give one more to the front + + let front_len = half + extra; + let back_len = half; + + // Grab the required portions. + let front: String = s.chars().take(front_len).collect(); + let back: String = s + .chars() + .rev() // reverse for an easy “take last N” + .take(back_len) + .collect::() + .chars() + .rev() // bring them back to normal order + .collect(); + + format!("{}...{}", front, back) +} diff --git a/crates/monsters/src/monster_database.rs b/crates/monsters/src/monster_database.rs index c7de0cd..0b0ba77 100644 --- a/crates/monsters/src/monster_database.rs +++ b/crates/monsters/src/monster_database.rs @@ -28,17 +28,13 @@ macro_rules! fetch_from { } /// Fetch all data from the database -// TODO: WARN the master filter is hardcoded here pub(crate) fn fetch_all_creature_data( connection: &Connection, config: &Config, + filter: Option<&str>, ) -> Result, anyhow::Error> { - let list_creatures = generic_deserialize::( - connection, - "creature", - Some("show_to_master=1 AND (id<5)"), - Some("id"), - )?; + let list_creatures = + generic_deserialize::(connection, "creature", filter, Some("id"))?; let mut finished_creatures = Vec::new(); for creature in list_creatures.iter() { // println!("Working on {}@{}", creature.id, creature.name); diff --git a/crates/monsters/src/monster_export.rs b/crates/monsters/src/monster_export.rs index 34010f0..83e40f0 100644 --- a/crates/monsters/src/monster_export.rs +++ b/crates/monsters/src/monster_export.rs @@ -44,7 +44,7 @@ pub fn generate_monsters_tex( config: &Config, connection: Connection, ) -> std::result::Result<(), anyhow::Error> { - let all_monsters = fetch_all_creature_data(&connection, config)?; + let all_monsters = fetch_all_creature_data(&connection, config, args.filter.as_deref())?; let templates = load_templates(config)?; println!("Processing"); let mut m_out = String::new(); diff --git a/crates/monsters/src/monster_render.rs b/crates/monsters/src/monster_render.rs index 83021f0..3f0e1ed 100644 --- a/crates/monsters/src/monster_render.rs +++ b/crates/monsters/src/monster_render.rs @@ -1,4 +1,6 @@ -use crate::monster_analysis::monster_analysis_structs::Showcase; +use crate::monster_analysis::{ + defense_analysis::DefenseReport, helpers, monster_analysis_structs::Showcase, +}; use comfy_table::{Color, Table, *}; use crate::{ @@ -231,3 +233,69 @@ impl ToCell for ProfileStance { } } } +// 🠰 +impl ToRow for DefenseReport { + fn to_row(&self) -> comfy_table::Row { + let row: Vec = vec![ + format!("{:?}", self.id).to_cell(), + helpers::shorten_string(&self.part_name.to_string(), 18).to_cell(), + format!("{:.1?}/{}", self.damage_per_turn_p1, self.health_p1) + .to_cell() + .fg(Color::DarkGrey), + compare_vals("t", self.time_to_p2, self.time_to_p2_target as f64), + format!("{:.1?}/{}", self.damage_per_turn_p2, self.health_p2) + .to_cell() + .fg(Color::DarkGrey), + compare_vals("t", self.time_to_kill, self.time_to_kill_target as f64), + format!("{:.1?}/{}", self.armor_break_per_turn, self.integrity_p1) + .to_cell() + .fg(Color::DarkGrey), + compare_vals( + "t", + self.time_to_armorbreak, + self.time_to_armorbreak_target as f64, + ), + ]; + row.into() + } +} + +pub(crate) fn fmt_target(v: f64) -> String { + const TOO_MUCH: f64 = 1_000_000_000_000_000.0; + const TRILLION: f64 = 1_000_000_000_000.0; + const BILLION: f64 = 1_000_000_000.0; + const MILLION: f64 = 1_000_000.0; + const THOUSAND: f64 = 1_000.0; + + match v { + _ if v >= TOO_MUCH => "⇑⇑⇑⇑B".to_string(), + _ if v >= TRILLION => format!("⇑{:.1}T", v / TRILLION), + _ if v >= BILLION => format!("⇑{:.1}B", v / BILLION), + _ if v >= MILLION => format!("⇑{:.1}M", v / MILLION), + _ if v >= THOUSAND => format!("⇑{:.1}k", v / THOUSAND), + _ => format!("{:.1}", v), + } +} + +pub(crate) fn compare_vals(unit: &str, actual: f64, target: f64) -> Cell { + let pct_diff = ((actual - target).abs() / target) * 100.0; // % diff + // let actual = 100000000000.; + let actual = if pct_diff > 1.0 { + fmt_target(actual) + } else { + format!("{:.1?}", actual) + }; + format!("{}/{:.0?}{}", actual, target, unit) + .to_cell() + .fg(pct_diff_to_colour(pct_diff)) +} + +/// Turn percent‑difference into one of four hard‑coded colours. +pub(crate) fn pct_diff_to_colour(pct_diff: f64) -> Color { + match pct_diff { + p if p < 20.0 => Color::Green, + p if p < 30.0 => Color::Blue, + p if p < 40.0 => Color::Red, + _ => Color::DarkRed, + } +}