From b564cd094cd02a41f33b17a14e240a84604258d4 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 20 Feb 2023 23:45:01 +0100 Subject: [PATCH] Improvement(Bindings) - Adds more python binding and refactor code --- Cargo.toml | 5 +- python3.py | 7 +++ src/bin/ffcraft.rs | 19 +++++-- src/io.rs | 120 +++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 119 +++++++++++++++----------------------------- 5 files changed, 186 insertions(+), 84 deletions(-) create mode 100644 python3.py create mode 100644 src/io.rs diff --git a/Cargo.toml b/Cargo.toml index cc49e95..1e0596e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,9 @@ threadpool = "1.8.1" # For python bindings TODO: make it optionnal pyo3 = { version = "0.18.0", features = ["extension-module"] } +# [target.'cfg(not(no_python))'.dependencies] +# pyo3 = { version = "0.18.0", features = ["extension-module"] } + # [build] # target = ["x86_64-unknown-linux-gnu", "x86_64-unknown-windows-gnu"] @@ -24,11 +27,11 @@ pyo3 = { version = "0.18.0", features = ["extension-module"] } panic = 'abort' opt-level = 3 lto = true -vere0 = false [features] default = [] verbose = [] +no_python = [] [lib] name = "xiv_craft_solver" diff --git a/python3.py b/python3.py new file mode 100644 index 0000000..b09c6e8 --- /dev/null +++ b/python3.py @@ -0,0 +1,7 @@ +import xiv_craft_solver +import rich + +rich.inspect(xiv_craft_solver) +rich.inspect(xiv_craft_solver.pouet) +rich.inspect(xiv_craft_solver.pouet()) +rich.inspect(xiv_craft_solver.pouet()) diff --git a/src/bin/ffcraft.rs b/src/bin/ffcraft.rs index fe86edc..d0b8f7c 100644 --- a/src/bin/ffcraft.rs +++ b/src/bin/ffcraft.rs @@ -1,4 +1,6 @@ // #![warn(missing_docs,unsafe_code,unstable_features,)] +use xiv_craft_solver::print_routes; +use std::time::{Instant}; use clap::Parser; use xiv_craft_solver; @@ -6,15 +8,26 @@ use xiv_craft_solver; struct CustomError(String); fn main() { - let args = xiv_craft_solver::Args::parse(); - let params = xiv_craft_solver::Parameters{ + let args = xiv_craft_solver::io::Args::parse(); + let params = xiv_craft_solver::io::Parameters{ depth: args.depth, threads: args.threads, verbose: args.verbose, }; + // Start timer + let now = Instant::now(); + + // Solve from config let (recipe,stats) = xiv_craft_solver::load_from_config(&args.recipe_name, &args.file_name, &args.character_name); - xiv_craft_solver::solve_craft(recipe,stats,params); + let results = xiv_craft_solver::solve_craft(recipe,stats,params); + // Show results + let t_final = now.elapsed().as_millis(); + print_routes(results); + + // Wait for user input + println!("\nProgram finished successfully in {}ms\nPress enter to exit...", t_final); + let mut input = String::new(); std::io::stdin().read_line(&mut input).unwrap(); () } \ No newline at end of file diff --git a/src/io.rs b/src/io.rs new file mode 100644 index 0000000..3fc6c9c --- /dev/null +++ b/src/io.rs @@ -0,0 +1,120 @@ +use crate::Craft; +use core::fmt::Display; +use clap::Parser; + +#[cfg(not(feature="no_python"))] +use pyo3::prelude::*; + +#[derive(Debug, Clone, Copy)] +pub struct Parameters { + pub threads: usize, + pub verbose: u8, + pub depth: u32, +} + +#[derive(Parser, Debug, Clone)] +#[command(author, version, about, long_about = None)] +pub struct Args { + /// Name of the receipe + #[arg(short, long, default_value_t = String::from("default_recipe"))] + pub recipe_name: String, + + /// Name of the character + #[arg(short, long, default_value_t = String::from("default_character"))] + pub character_name: String, + + /// The ml file name + #[arg(short, long, default_value_t = String::from("craft.toml"))] + pub file_name: String, + + /// The verbose flag + #[arg(short, long, action = clap::ArgAction::Count)] + pub verbose: u8, + + /// The depth of the first pass + #[arg(short, long, default_value_t = 8)] + pub depth: u32, + + /// Thread counts, default is 4 (can you even run ff with less ?) + #[arg(short, long, default_value_t = 4)] + pub threads: usize, +} + + +/// A final stripped down version of a craft +/// used for final print and talking with python +#[derive(Debug)] +#[pyclass] +pub struct SolverResult{ + #[pyo3(get)] + pub steps: u32, + #[pyo3(get)] + pub quality: u32, + #[pyo3(get)] + pub progression: u32, + #[pyo3(get)] + pub durability: i32, + #[pyo3(get)] + pub actions: Vec, + #[pyo3(get)] + pub step1_solutions: u32, + #[pyo3(get)] + pub step2_solutions: u32, +} + +#[pyfunction] +pub fn pouet()-> SolverResult { + // return "pouet"; + SolverResult{ + steps:0, + progression: 0, + quality:0, + durability:0, + actions:vec!["BLLLL".to_string(),"WWWWW".to_string()], + step1_solutions:0, + step2_solutions:0, + + } +} + +/// Pretty display for SolverResult +impl Display for SolverResult{ + fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { + println!("{:?}",self.actions); + Ok(()) + } +} + + +impl SolverResult{ + pub fn from_craft(&self,craft: & Craft)->SolverResult{ + // Todo: recreate actions + // Where steps ? + SolverResult{ + steps:craft.step_count, + progression: craft.progression, + quality:craft.quality, + durability:craft.durability, + actions:vec!["BLLLL".to_string(),"WWWWW".to_string()], + step1_solutions:0, + step2_solutions:0, + } + + } + +} + + +/// Python Bindings + +/// A Python module implemented in Rust. +#[cfg(not(feature="no_python"))] +#[pymodule] +fn xiv_craft_solver(_py: Python, m: &PyModule) -> PyResult<()> { + m.add_function(wrap_pyfunction!(pouet, m)?)?; + Ok(()) +} + +pub fn e(){ + +} \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 536c3b6..495058a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,72 +1,34 @@ use crate::{ craft::Craft, specs::{Recipe,Stats}, + io::Parameters, }; -use std::time::{Instant}; use threadpool::ThreadPool; use std::sync::{Arc,Mutex}; -use clap::Parser; -use pyo3::prelude::*; mod solver; mod specs; pub mod action; pub mod craft; +pub mod io; -#[derive(Debug, Clone, Copy)] -pub struct Parameters { - pub threads: usize, - pub verbose: u8, - pub depth: u32, -} -#[derive(Parser, Debug, Clone)] -#[command(author, version, about, long_about = None)] -pub struct Args { - /// Name of the receipe - #[arg(short, long, default_value_t = String::from("default_recipe"))] - pub recipe_name: String, +/// Create stats - /// Name of the character - #[arg(short, long, default_value_t = String::from("default_character"))] - pub character_name: String, +/// Create recipe - /// The ml file name - #[arg(short, long, default_value_t = String::from("craft.toml"))] - pub file_name: String, - - /// The verbose flag - #[arg(short, long, action = clap::ArgAction::Count)] - pub verbose: u8, +/// Create parameters - /// The depth of the first pass - #[arg(short, long, default_value_t = 8)] - pub depth: u32, - /// Thread counts, default is 4 (can you even run ff with less ?) - #[arg(short, long, default_value_t = 4)] - pub threads: usize, -} +/// Create from config -#[pyfunction] -pub fn pouet()-> &'static str { - return "pouet"; -} -/// A Python module implemented in Rust. -#[pymodule] -fn xiv_craft_solver(_py: Python, m: &PyModule) -> PyResult<()> { - m.add_function(wrap_pyfunction!(pouet, m)?)?; - Ok(()) -} -/// Solve the craft with given arguments +/// Solve the craft with given arguments, this functions calls threads and must own it's values pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Option>>{ // Load the craft with given arguments let craft = Craft::new(recipe,stats,params); - // Start timer - let now = Instant::now(); // Start a threadpool let pool = ThreadPool::new(params.threads); @@ -76,23 +38,18 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti println!("Solving...\n"); println!("[P1] Starting phase 1..."); } + let phase1_routes = solver::generate_routes_phase1(craft); - + let nb_p1 = phase1_routes.len(); + #[cfg(feature = "verbose")] if params.verbose>0{ println!("[P1] Found {} routes, testing them all...",phase1_routes.len()); - if params.verbose>1{ - for r in &phase1_routes{ - println!("[P1] {:?} p:{}% q:{}% c:{} d:{}", - r.actions, - r.progression * 100 / r.recipe.progress, - r.quality * 100 / r.recipe.quality, - r.cp, - r.durability, - ); - }; - } + if params.verbose>1{ for r in &phase1_routes{ + println!("[P1] {:?} p:{}% q:{}% c:{} d:{}",r.actions,r.quality * 100 / r.recipe.quality,r.cp,r.durability); + }} } + // Core algorithm, fill all found routes with the best route (doesn't branch, just replace) let arc_phase2_routes = Arc::new(Mutex::new(Vec::::new())); @@ -109,36 +66,31 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti pool.join(); let phase2_routes = arc_phase2_routes.lock().unwrap(); - + let nb_p2 = phase2_routes.len(); + // Print the results if verbose #[cfg(feature = "verbose")] if params.verbose>0{ println!("[P2] Found {} solutions, sorting",phase2_routes.len()); - - if params.verbose>1{ - for r in phase2_routes.iter(){ - println!("[P2] {:?} p:{}% q:{}% d:{}", - r.actions, - r.progression * 100 / r.recipe.progress, - r.quality * 100 / r.recipe.quality, - r.durability); - }; - } + if params.verbose>1{ for r in phase2_routes.iter(){ + println!("[P2] {:?} p:{}% q:{}% d:{}", r.actions, r.progression * 100 / r.recipe.progress, r.quality * 100 / r.recipe.quality, r.durability); + }} } - // Copy the valid results for analysis, by default only the valid one are copied + // Prune the results for analysis let mut valid_routes : Vec = vec![]; for route in phase2_routes.iter(){ if route.quality>=route.recipe.quality{ valid_routes.push(route.clone()); } } - + // If no craft can make it to 100% HQ, fallback to base results if valid_routes.len()==0{ for route in phase2_routes.iter(){valid_routes.push(route.clone())} // Deep copy through the mutex guard } + //// Show best results // Select best route TODO: Seperate function let top_route = match valid_routes.iter().max_by_key(|route| route.quality) { Some(top) => top, @@ -157,6 +109,7 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti }) .collect::>(); + // Setting something to print, adding the missing actions TODO: Change this behaviour and move to separate function let arg = (top_route.recipe.progress as f32 - top_route.progression as f32) / top_route.get_base_progression() as f32; if 0.0 < arg && arg < 1.2 { content.push("\"basicSynth2\"".to_string()); } @@ -176,15 +129,8 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti println!("\t[{}]", content.join(", ")); } - // Wait for enter TODO: Remove - println!(); - println!("Program finished sucessfuly in {}ms and found {} solutions, [prog:{}]", - now.elapsed().as_millis(), - phase2_routes.len(), - top_route.recipe.progress); - println!("Press enter to exit..."); - let mut input = String::new(); - std::io::stdin().read_line(&mut input).unwrap(); + + Some(valid_routes) } @@ -256,4 +202,17 @@ pub fn load_from_config<'a>(recipe_name: &str, file_name: &str, character_name: // fn make_craft_from_values(){ -// } \ No newline at end of file +// } + +// /// Print results +// enum SHOW_TYPE{ +// BEST, +// SAFEST, +// SHORTEST, +// } +pub fn print_routes<'a>(routes: Option>>){ + match routes{ + Some(r) => println!("{:?}",r), + None => println!("Noooooooooooooo") + } +} \ No newline at end of file