From 9ca9e49a8eba9a185c7387d7c17129eaf15a8c32 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 25 Jul 2026 05:39:39 +0200 Subject: [PATCH] Balancing utility --- crates/monsters/src/monster_analysis.rs | 376 +++++++++++++++--- .../src/monster_analysis/attack_analysis.rs | 5 +- crates/monsters/src/monster_structs.rs | 21 +- ravenous_databases | 2 +- 4 files changed, 331 insertions(+), 73 deletions(-) diff --git a/crates/monsters/src/monster_analysis.rs b/crates/monsters/src/monster_analysis.rs index 00fee82..2025a6b 100644 --- a/crates/monsters/src/monster_analysis.rs +++ b/crates/monsters/src/monster_analysis.rs @@ -1,15 +1,18 @@ //! Monster export module #![allow(dead_code)] -use comfy_table::{Cell, ContentArrangement, Table, modifiers, presets}; +use comfy_table::{Cell, Color, modifiers}; use more_fields::FieldsAsSlice; use crate::{ Config, Connection, MonsterConfig, - monster_analysis::monster_analysis_structs::DefenseMode, + monster_analysis::{ + helpers::{binomial_dice_distribution, how_much_with_succeses}, + monster_analysis_structs::DefenseMode, + }, monster_database::{fetch_all_creature_data, fetch_all_player_data}, - monster_render::{ToCell, ToTable}, - monster_structs::{FullMonster, PlayerBalancing, ProfileHSE, ProfileStance}, + monster_render::{ToCell, ToRow, ToTable}, + monster_structs::{CreatureBodyPart, FullMonster, PlayerBalancing, ProfileHSE, ProfileStance}, }; pub mod attack_analysis; mod helpers; @@ -26,10 +29,24 @@ pub fn show_balancing_data( let data = fetch_all_creature_data(&connection, config)?; let player_data = fetch_all_player_data(&connection, config)?; - // let table = player_data.to_table(); - for creature in data { - println!("{}", creature.name); + // println!("{}", creature.name); + let mut table = comfy_table::Table::new(); + table + .load_preset(comfy_table::presets::UTF8_FULL_CONDENSED) + .apply_modifier(modifiers::UTF8_ROUND_CORNERS) + .set_content_arrangement(comfy_table::ContentArrangement::Dynamic); + table.add_row(vec![ + match creature.balancing.monster_groupsize { + 0 | 1 => creature.name.clone(), + n => format!("{} x {}", creature.name, n), + } + .to_cell() + .fg(Color::Blue), // .add_attribute(comfy_table::Attribute::Reverse), + ]); + + println!("{table}"); + let player_level = &creature.balancing.profile_hse; let available_profiles = player_data .clone() @@ -42,8 +59,8 @@ pub fn show_balancing_data( .map(|profile| (profile.profile_stance, profile)) .collect(); - display_player_attacks(args, &creature, &profiles); - display_monster_attacks(args, creature, &profiles); + display_player_attacks(args, &creature, &profiles, DefenseMode::Worst); + display_monster_attacks(args, creature, &profiles, DefenseMode::Best); } Ok(()) } @@ -52,74 +69,307 @@ fn display_player_attacks( args: &MonsterConfig, creature: &FullMonster, profiles: &HashMap, -) -> () { - let r = DefenseReport { - id: creature.balancing.creature_id, - name: creature.name.clone(), - profile_hse: creature.balancing.profile_hse.clone(), - time_to_p2: creature.balancing.time_to_p2, - time_to_armorbreak: creature.balancing.time_to_armorbreak, - time_to_first_kill: creature.balancing.time_to_first_kill, - monster_groupsize: creature.balancing.monster_groupsize, - player_groupsize: creature.balancing.player_groupsize, - }; - r.to_table(); + 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()); } -impl ToTable for DefenseReport { - fn to_table(&self) -> comfy_table::Table { - let mut table = Table::new(); - table - .load_preset(presets::UTF8_FULL_CONDENSED) - .apply_modifier(modifiers::UTF8_ROUND_CORNERS) - .set_content_arrangement(ContentArrangement::Dynamic) - .set_width(120) - .set_header( - DefenseReport::attributes_slice() - .iter() - .map(|(a, _b)| Cell::new(a)), - ); +/// 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(), - format!("{:?}", self.name).to_cell(), - format!("{:?}", self.profile_hse).to_cell(), - format!("{:?}", self.time_to_p2).to_cell(), - format!("{:?}", self.time_to_armorbreak).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, + ), ]; - table.add_row(row); - table + row.into() } } -#[derive(Debug, FieldsAsSlice)] -struct DefenseReport { - #[INTEGER] - pub id: i64, - pub name: String, - /// (Fixed) HSE profile of the monster (see `ProfileHSE`). - pub profile_hse: ProfileHSE, - #[INTEGER] - /// (Goal) Turns needed to reach phase 2. - pub time_to_p2: i64, - #[INTEGER] - /// (Goal) Turns until the monster’s armor breaks. - pub time_to_armorbreak: i64, - #[INTEGER] - /// (GOAL) Avg. turns to kill a single target. - pub time_to_first_kill: i64, - #[INTEGER] - /// (FIXED) Size of a single monster group (usually one). - pub monster_groupsize: i64, - #[INTEGER] - /// (FIXED) The number of players this fight was designed for - pub player_groupsize: i64, +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 { @@ -129,7 +379,7 @@ fn display_monster_attacks( let mut res = Vec::new(); for attack in attacks { - let mut report = attack_analysis::all_attacks(args, &attack, profiles, DefenseMode::Best); + 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/attack_analysis.rs b/crates/monsters/src/monster_analysis/attack_analysis.rs index 80e64b9..6806021 100644 --- a/crates/monsters/src/monster_analysis/attack_analysis.rs +++ b/crates/monsters/src/monster_analysis/attack_analysis.rs @@ -65,8 +65,9 @@ pub fn attack_player( let avg_successes_left: f64 = bin .iter() .map(|(dice, p)| (attack.successes - dice) as f64 * p) - .sum::() - / bin.len() as f64; + .sum::(); + // TODO : Pretty sure + // / bin.len() as f64; let avg_damage_incomming: f64 = bin .iter() .map(|(dices, p)| { diff --git a/crates/monsters/src/monster_structs.rs b/crates/monsters/src/monster_structs.rs index 7c2015c..565762f 100644 --- a/crates/monsters/src/monster_structs.rs +++ b/crates/monsters/src/monster_structs.rs @@ -294,12 +294,13 @@ pub struct CreatureBodyPart { 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); -/// ``` + +// / 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. @@ -423,11 +424,14 @@ pub struct CreatureBalancing { /// (Goal) Turns needed to reach phase 2. pub time_to_p2: i64, #[INTEGER] + /// (Goal) Turns needed to kill from phase 2. + pub time_to_kill: i64, + #[INTEGER] /// (Goal) Turns until the monster’s armor breaks. pub time_to_armorbreak: i64, #[INTEGER] /// (GOAL) Avg. turns to kill a single target. - pub time_to_first_kill: i64, + pub time_to_player_kill: i64, #[INTEGER] /// (FIXED) Size of a single monster group (usually one). pub monster_groupsize: i64, @@ -454,6 +458,9 @@ pub struct PlayerBalancing { /// Number of offensive successes per round. pub successes_off: i64, #[INTEGER] + /// Maximum number of offensive successes per round. + pub max_successes_off: i64, + #[INTEGER] /// Number of deffensive successes per round. pub successes_def: i64, #[INTEGER] diff --git a/ravenous_databases b/ravenous_databases index 1048cf2..cd34aa2 160000 --- a/ravenous_databases +++ b/ravenous_databases @@ -1 +1 @@ -Subproject commit 1048cf2617201894af650d88406ffa49578d7b11 +Subproject commit cd34aa21d07d0bf0bcda0f88e12279b791546a20