auto-radar #72

Merged
Dandaedre merged 2 commits from auto-radar into main 2026-05-02 22:34:00 +02:00
2 changed files with 264 additions and 3 deletions

View File

@ -4,7 +4,8 @@
//!
use clap::Args;
use phf::phf_map;
use std::sync::LazyLock;
use serde::{Deserialize, Serialize};
use std::{ops::Add, sync::LazyLock};
#[derive(Args, Debug, Clone)]
/// The configuration struct for the Graph
@ -32,6 +33,7 @@ pub struct GraphConfig {
/// Link from user str input to the action to perform
static STR_TO_GRAPH_TARGET_TYPE: phf::Map<&'static str, GraphTargetType> = phf_map! {
"load" => GraphTargetType::Load,
"generate" => GraphTargetType::Generate,
"gen" => GraphTargetType::Generate,
"remove" => GraphTargetType::Remove,
@ -51,6 +53,8 @@ static HELP_STR_TO_GRAPH: LazyLock<String> = LazyLock::new(|| {
#[derive(Debug, Clone)]
/// All target type
pub enum GraphTargetType {
/// Load graph data from the classes
Load,
/// Make all graphs
Generate,
/// Clean all graphs
@ -70,3 +74,164 @@ impl From<&str> for GraphTargetType {
}
}
}
/// The named categories to save on file
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct FinalClassRadar {
/// A name to identify the categories
#[serde(rename = "Classe")]
pub name: String,
/// The values of the different radar categories
/// The ability to survive.
#[serde(rename = "Survivabilité")]
pub survivability: f64,
/// The ability to deal damage.
#[serde(rename = "Dégats")]
pub damage: f64,
/// The ability to move.
#[serde(rename = "Mobilité")]
pub mobility: f64,
/// The ability to inflict state alterations.
#[serde(rename = "Altérations")]
pub alterations: f64,
/// The ability to provide support.
#[serde(rename = "Support")]
pub support: f64,
/// The ability to inflict crowd control.
#[serde(rename = "C.C")]
pub cc: f64,
/// The ability to improve quality of life.
#[serde(rename = "QoL")]
pub qol: f64,
/// The armor break of the class
#[serde(rename = "Brise-Armure")]
pub armorbreak: f64,
// / The class complexity
}
/// All the categories to load from the tables
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct LoadedClassRadar {
/// The ability to survive.
pub survivability: f64,
/// The ability to deal damage.
pub damage: f64,
/// The ability to move.
pub mobility: f64,
/// The ability to inflict state alterations.
pub alterations: f64,
/// The ability to provide support.
pub support: f64,
/// The ability to inflict crowd control.
pub cc: f64,
/// The ability to improve quality of life.
pub qol: f64,
/// The ability to break armor.
pub armorbreak: f64,
}
/// All the categories to load from the tables
#[derive(Deserialize, Clone, Debug)]
pub struct RawRow {
/// The name of a technique.
pub technique: String,
/// The level or rank of a technique
pub niveau: String,
/// The type of technique, such as Actif or Exclusif.
pub technique_type: String,
/// The blood cost for this technique.
pub cout_blood: String,
/// The gauge cost for this technique.
pub cout_jauge: String,
/// A brief description of the effect or outcome of using this technique.
pub effet: String,
/// A indicative column for notes
pub indicative: String,
/// The ability to survive.
pub survivability: String,
/// The ability to deal damage.
pub damage: String,
/// The ability to move.
pub mobility: String,
/// The ability to inflict state alterations.
pub alterations: String,
/// The ability to provide support.
pub support: String,
/// The ability to inflict crowd control.
pub cc: String,
/// The ability to improve quality of life.
pub qol: String,
/// The ability to break armor.
pub armorbreak: String,
}
impl From<RawRow> for LoadedClassRadar {
fn from(value: RawRow) -> Self {
Self {
survivability: value.survivability.parse().unwrap_or(0.0),
damage: value.damage.parse().unwrap_or(0.0),
mobility: value.mobility.parse().unwrap_or(0.0),
alterations: value.alterations.parse().unwrap_or(0.0),
support: value.support.parse().unwrap_or(0.0),
cc: value.cc.parse().unwrap_or(0.0),
qol: value.qol.parse().unwrap_or(0.0),
armorbreak: value.armorbreak.parse().unwrap_or(0.0),
}
}
}
impl Add for LoadedClassRadar {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self {
survivability: self.survivability + rhs.survivability,
damage: self.damage + rhs.damage,
mobility: self.mobility + rhs.mobility,
alterations: self.alterations + rhs.alterations,
support: self.support + rhs.support,
cc: self.cc + rhs.cc,
qol: self.qol + rhs.qol,
armorbreak: self.armorbreak + rhs.armorbreak,
}
}
}
impl FinalClassRadar {
/// A very wastful (but simple) way to only add the max value
pub fn find_max(self, rhs: &Self) -> Self {
Self {
survivability: self.survivability.max(rhs.survivability),
damage: self.damage.max(rhs.damage),
mobility: self.mobility.max(rhs.mobility),
alterations: self.alterations.max(rhs.alterations),
support: self.support.max(rhs.support),
cc: self.cc.max(rhs.cc),
qol: self.qol.max(rhs.qol),
armorbreak: self.armorbreak.max(rhs.armorbreak),
name: self.name,
}
}
/// Create a class from a loaded categories
pub fn from_radar_with_name(name: String, categorie: LoadedClassRadar) -> Self {
Self {
name,
survivability: categorie.survivability,
damage: categorie.damage,
mobility: categorie.mobility,
alterations: categorie.alterations,
support: categorie.support,
cc: categorie.cc,
qol: categorie.qol,
armorbreak: categorie.armorbreak,
}
}
/// A default value for accumulation
pub fn default_for_acc() -> FinalClassRadar {
Self {
name: "Max".to_owned(),
..Default::default()
}
}
}

View File

@ -6,13 +6,14 @@
use charts_rs::{Box, Color, RadarChart, RadarIndicator, Series, get_or_try_init_fonts};
use cli_parser::Config;
use config::graph::{GraphConfig, GraphTargetType};
use config::graph::{FinalClassRadar, GraphConfig, GraphTargetType, LoadedClassRadar, RawRow};
use glob::glob;
use serde::{Deserialize, Serialize};
use std::{
fs::File,
io::{Read, Write},
iter,
path::{Path, PathBuf},
process::Command,
};
@ -22,6 +23,7 @@ use anyhow::{Context, Result};
pub fn make_graphs(args: &GraphConfig, _config: &Config) -> Result<()> {
// Choose action to do
match args.target {
GraphTargetType::Load => load_graph(args),
GraphTargetType::Generate => gen_graph(args),
GraphTargetType::Remove => del_graphs(args),
GraphTargetType::Init => init_graph_config(args),
@ -80,7 +82,14 @@ fn del_graphs(args: &GraphConfig) -> Result<()> {
Ok(())
}
/// Generate the graph and save it
/// Load graph data from classes
fn load_graph(args: &GraphConfig) -> Result<()> {
let _ = args;
// load_categories_from_tsv("./test.csv")?;
generate_csv()?;
Ok(())
}
///Generate the graph and save it
fn gen_graph(args: &GraphConfig) -> Result<()> {
// Import CSV
let data = include_bytes!("../../../data/lmroman8-regular.ttf") as &[u8];
@ -131,6 +140,81 @@ fn import_csv(args: &GraphConfig) -> Result<GraphValues> {
cleanup_csv(rdr)
}
/// Generate the csv from all the classes
fn generate_csv() -> Result<()> {
// Acquire the data from all classes
let list_class = list_dir("Tables/??? - *.tsv");
let mut final_class_list = Vec::with_capacity(list_class.len() + 1);
// Very ugly space reservation for the last operation, need to check if no way of skipping an element is possible
final_class_list.push(FinalClassRadar::default());
for single_class in list_class {
let class_name = &single_class
.file_name()
.context("Extracting old name")?
.to_str()
.context("Generating new name")?[12..]
.strip_suffix(".tsv")
.context("Stripping extention")?;
let categories =
load_categories_from_tsv(single_class.clone()).context("Loading from csv")?;
// final_class_list.push(ClassValues {
// name: class_name.to_string(),
// categories,
// });
final_class_list.push(FinalClassRadar::from_radar_with_name(
class_name.to_string(),
categories,
))
}
// Calculate all the max values
final_class_list[0] = final_class_list
.iter()
.fold(FinalClassRadar::default_for_acc(), |a, b| a.find_max(b));
let mut wtr = csv::WriterBuilder::new()
.has_headers(true)
.from_path("Images/Radar/radar.csv")
.context("Creating CSV output file")?;
// println!("{:?}", final_class_list);
for cv in &final_class_list {
wtr.serialize(cv).context("Writing CSV record")?;
}
wtr.flush().context("Flushing CSV writer")?;
Ok(())
}
/// Reads a TSV file that either has the header line shown above or
/// just raw data rows, and returns a `Vec<Categories>`.
pub fn load_categories_from_tsv<P: AsRef<Path>>(path: P) -> Result<LoadedClassRadar> {
// `has_headers(false)` tells the csv crate to *not* treat the first row as a header.
// We’ll do the header check ourselves.
let file = File::open(path)?;
let mut rdr = csv::ReaderBuilder::new()
.has_headers(false)
.delimiter(b'\t')
.double_quote(false)
.escape(Some(b'\\'))
.flexible(true)
.comment(Some(b'#'))
.from_reader(file);
let mut sum = LoadedClassRadar::default();
for result in rdr.deserialize() {
let result: RawRow = result?;
if result.technique.starts_with("Tier ") {
// Getto way of knowing we have a new tier, that we ignore
} else if (result.technique == "Technique") | result.technique.is_empty() {
// Skip this entry
} else {
sum = sum + result.into();
}
}
Ok(sum)
}
/// The data for all graphs
struct GraphValues {
/// The max values of a graph
@ -301,3 +385,15 @@ pub struct MiniTheme {
// pub table_body_colors: Vec<Color>,
// pub table_border_color: Color,
}
/// List all files matching a pattern in the given directory
#[inline]
fn list_dir(pattern: &str) -> Vec<PathBuf> {
// println!("{}", pattern);
// println!("{:?}", glob(pattern));
glob(pattern)
.expect("Failed to read glob pattern")
.flatten()
.collect()
}