Merge branch 'vky' of dandaedre.com:Dandaedre/rcraft_solver into vky

This commit is contained in:
vicky 2023-02-22 09:57:38 +01:00
commit 7a8dca2f06
27 changed files with 657 additions and 185 deletions

1
.gitignore vendored
View File

@ -3,6 +3,7 @@
*.iml *.iml
/bin.py /bin.py
python/dontlook.py python/dontlook.py
expected_values.md
# Byte-compiled / optimized / DLL files # Byte-compiled / optimized / DLL files
__pycache__/ __pycache__/

View File

@ -2,7 +2,7 @@
name = "xiv_craft_solver" name = "xiv_craft_solver"
version = "0.1.2" version = "0.1.2"
edition = "2021" edition = "2021"
authors = ["谭俊健","Dandaedre"] authors = ["谭俊健","Dandaedre","Vkyfox"]
description = "Small XIV solver library in rust, with python and rust bindings" description = "Small XIV solver library in rust, with python and rust bindings"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -17,6 +17,9 @@ threadpool = "1.8.1"
# For python bindings TODO: make it optionnal # For python bindings TODO: make it optionnal
pyo3 = { version = "0.18.0", features = ["extension-module"] } pyo3 = { version = "0.18.0", features = ["extension-module"] }
# [target.'cfg(not(no_python))'.dependencies]
# pyo3 = { version = "0.18.0", features = ["extension-module"] }
# [build] # [build]
# target = ["x86_64-unknown-linux-gnu", "x86_64-unknown-windows-gnu"] # target = ["x86_64-unknown-linux-gnu", "x86_64-unknown-windows-gnu"]
@ -24,11 +27,12 @@ pyo3 = { version = "0.18.0", features = ["extension-module"] }
panic = 'abort' panic = 'abort'
opt-level = 3 opt-level = 3
lto = true lto = true
vere0 = false
[features] [features]
default = [] default = []
verbose = [] verbose = []
no_python = [] # Removes the python bindings
fast = [] # Remove some under optimisations that try to find other routes
[lib] [lib]
name = "xiv_craft_solver" name = "xiv_craft_solver"

View File

@ -1,17 +1,71 @@
# xiv_craft_solver # xiv_craft_solver
A rust program for solving FFXIV craft recipe. **Only normal lv90 recipes with stars and 70/80 dur works.** A rust program for solving FFXIV craft recipe.
## Usage Originaly written by [RikaKagurasaka](https://github.com/RikaKagurasaka/xiv_craft_solver),
it now is widely improved and provides python bindings for a GUI (or anything else really)
### Basic RUST CLI Usage
Everything is done through the regular cargo interface
1. Download the latest release. 1. Download the latest release.
2. Unzip the file. 2. Unzip the file.
3. Edit the `craft.toml` file. 3. Edit the `craft.toml` file.
4. Run the program. 4. Run the program.
5. Wait for about 1 minute. 5. Wait for about 1-3 seconds.
6. Copy the output. 6. Copy the output.
7. Import to other simulators. 7. Import to other simulators.
#### Example ## CLI
Note: The recipe data can be retrieved from [FFXIV Crafting Optimizer](https://yyyy.games/crafter/#/simulator) When building the CLI invocation is done with the following parameters
```
Small XIV solver library in rust, with python and rust bindings
Usage: ffcraft [OPTIONS]
Options:
-r, --recipe-name <RECIPE_NAME>
Name of the receipe [default: default_recipe]
-c, --character-name <CHARACTER_NAME>
Name of the character [default: default_character]
-f, --file-name <FILE_NAME>
The ml file name [default: craft.toml]
-v, --verbose...
The verbose flag
-d, --depth <DEPTH>
The depth of the first pass [default: 8]
-t, --threads <THREADS>
Thread counts, default is 4 [default: 4]
-D, --desperate
Desperate mode, will try to finish the craft above all
-l, --long
Long mode, will try to find more solutions, at the expense of time
-h, --help
Print help
-V, --version
Print version
```
## Developpement
### Rust
Everything is located in the root & src.
You can build the program (CLI) with cargo build the following features are available
``cargo build --features=["fast","no_python","verbose"]``
- The ``no_python`` will not build the lib (WIP, not fully implemented)
- The ``fast`` feature will not allow some under-optimisation to run (saving global run-time)
- The ``verbose`` feature will allow even more debug messages (They might not be shown depending on the verbosity level hoever)
#### Maturin
To build the python module, run ``maturin develop`` or ``maturin build`` then ``maturin install``
### Python
#### Developping the GUI
0. Activate the venv ``source .venv/bin/activate``
1. Go to the ``python`` directory
2. Install the dev dependencies ``pip install -r requirements_dev.txt``
3. Install the project (in editable mode) ``pip install -e .``
4. Invoke the project (from anywhere) ``python -m ffcraft_solver``
5. Edit the project and re-invoke it (no need to install / compile again)
#### Rust CLI Example
Note: The recipe data can be retrieved from a [FFXIV Crafting Optimizer](https://yyyy.games/crafter/#/simulator)
with checking of **Custom Recipe** after selecting the recipe. with checking of **Custom Recipe** after selecting the recipe.
![img.png](img.png) ![img.png](img.png)
```toml ```toml
@ -43,9 +97,19 @@ max_cp = 602
``` ```
Solving... Solving...
Quality: 11126/12628 > SOLUTION [Least steps] <
["muscleMemory", "manipulation", "veneration", "groundwork2", "basicSynth2", "prudentSynthesis", "prudentSynthesis", "prudentSynthesis", "prudentTouch", "prudentTouch", "manipulation", "innovation", "prudentTouch", "basicTouch", "standardTouch", "advancedTouch", "innovation", "prudentTouch", "basicTouch", "standardTouch", "advancedTouch", "innovation", "trainedFinesse", "trainedFinesse", "greatStrides", "byregotsBlessing", "basicSynth2"] Quality: [10941/10920] | Durability: [0/70] | Cp : [14/602] | Steps : 18
["muscleMemory", "manipulation", "veneration", "wasteNot2", "groundwork", "delicateSynthesis", "basicSynth", "innovation", "preparatoryTouch", "preparatoryTouch", "preparatoryTouch", "preparatoryTouch", "greatStrides", "innovation", "basicTouch", "standardTouch", "greatStrides", "byregotsBlessing", "basicSynth2"]
> SOLUTION [Most durability] <
Quality: [10923/10920] | Durability: [15/70] | Cp : [4/602] | Steps : 22
["muscleMemory", "manipulation", "veneration", "groundwork", "carefulSynthesis", "prudentTouch", "innovation", "prudentTouch", "prudentTouch", "prudentTouch", "prudentTouch", "manipulation", "innovation", "prudentTouch", "basicTouch", "standardTouch", "advancedTouch", "innovation", "prudentTouch", "basicTouch", "greatStrides", "byregotsBlessing", "basicSynth2"]
> SOLUTION [Most quality] <
Quality: [12142/10920] | Durability: [-5/70] | Cp : [1/602] | Steps : 22
["muscleMemory", "manipulation", "veneration", "wasteNot2", "groundwork", "carefulSynthesis", "basicTouch", "innovation", "preparatoryTouch", "basicTouch", "standardTouch", "advancedTouch", "innovation", "prudentTouch", "basicTouch", "standardTouch", "advancedTouch", "innovation", "prudentTouch", "trainedFinesse", "greatStrides", "byregotsBlessing", "basicSynth2"]
Program finished successfully in 954ms
Press enter to exit... Press enter to exit...
``` ```

View File

@ -2,13 +2,12 @@
requires = ["maturin>=0.14,<0.15"] requires = ["maturin>=0.14,<0.15"]
build-backend = "maturin" build-backend = "maturin"
[project] [project] # The rust bindings
name = "xiv_craft_solver" name = "xiv_craft_solver"
requires-python = ">=3.7" requires-python = ">=3.7"
version = "0.0.4"
classifiers = [ classifiers = [
"Programming Language :: Rust", "Programming Language :: Rust",
"Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy", "Programming Language :: Python :: Implementation :: PyPy",
] ]

39
python/__ignore_setup.cfg Normal file
View File

@ -0,0 +1,39 @@
[metadata]
platforms = unix, linux, cygwin, win32
classifiers =
Programming Language :: Python :: 3
Programming Language :: Python :: 3 :: Only
Programming Language :: Python :: 3.10
Programming Language :: Python :: 3.9
[options]
packages =
ffcraft_solver
ffcraft_solver.modules
install_requires =
pyyaml>=6.0
python_requires = >=3.9
package_dir =
=src
zip_safe = no
[options.packages.find]
where =
= src
= src/ffcraft_solver
[options.extras_require]
testing =
flake8>=4.0.1
tox>=3.24.3
pytest>=6.2.5
pytest-cov>=2.12.1
mypy>=0.910
pyyaml>=6.0
[options.package_data]
slapping = py.typed
[flake8]
max-line-length = 160

38
python/pyproject.toml Normal file
View File

@ -0,0 +1,38 @@
[build-system]
requires = ["setuptools>=42.0", "wheel"]
build-backend = "setuptools.build_meta"
[project] # The Python GUI
name = "ffcraft_solver"
authors = [
{name="Vkyfox"},
{name="Dandaedre"},
]
requires-python = ">=3.7"
version = "0.0.4"
license = {text="Mozilla Public License Version 2.0"}
classifiers = [
"Programming Language :: Rust",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]
[tool.pytest.ini_options]
addopts = "--cov=ffcraft_solver"
testpaths = [
"tests",
]
[tool.mypy]
mypy_path = "python"
check_untyped_defs = true
disallow_any_generics = true
ignore_missing_imports = true
no_implicit_optional = true
show_error_codes = true
strict_equality = true
warn_redundant_casts = true
warn_return_any = true
warn_unreachable = true
warn_unused_configs = true
no_implicit_reexport = true

3
python/requirements.txt Normal file
View File

@ -0,0 +1,3 @@
dearpygui==1.8.0
PyYAML==6.0
rich==13.3.1

View File

@ -0,0 +1,8 @@
flake8==4.0.1
tox==3.24.5
pytest==7.1.1
pytest-cov==3.0.0
mypy==0.941
dearpygui==1.8.0
PyYAML==6.0
rich==13.3.1

View File

@ -0,0 +1,4 @@
"""
A rust program for solving FFXIV craft recipe.
- ffcraft_solver
"""

View File

@ -1,13 +1,12 @@
import dearpygui.dearpygui as dpg import dearpygui.dearpygui as dpg
import loader
import rich
import xiv_craft_solver as xcs import xiv_craft_solver as xcs
from ffcraft_solver.modules import loader
import rich
dpg.create_context() dpg.create_context()
dpg.configure_app(manual_callback_management=True) dpg.configure_app(manual_callback_management=True)
dpg.create_viewport(title='XIV Solver', width=500, height=700) dpg.create_viewport(title='XIV Solver', width=500, height=700)
class User: class User:
name = 'NEW' name = 'NEW'
food = '' food = ''

View File

@ -0,0 +1,32 @@
import xiv_craft_solver
import rich
rich.inspect(xiv_craft_solver)
rich.inspect(xiv_craft_solver.test_result)
rich.inspect(xiv_craft_solver.test_result())
rich.inspect(xiv_craft_solver.test_result())
class feedMeDaddy:
durability = 70
progress = 3900
quality = 10920
progress_divider = 130
quality_divider = 115
progress_modifier = 80
quality_modifier = 70
craftsmanship = 4041
control = 3959
max_cp = 602
# Config
depth = 10
byregot_step = 10
desperate = False
threads = 8
verbose = 0
el_daddy=feedMeDaddy()
rich.inspect(xiv_craft_solver.solve_from_python(el_daddy))

View File

@ -0,0 +1,3 @@
"""
The modules in this folder are used to generate the GUI and parse the results
"""

View File

@ -1,5 +1,13 @@
import rich import rich
import yaml import yaml
import os
class DefaultConfig:
yaml_user = 'configs/users.yaml'
yaml_consumable = 'configs/consumables.yaml'
yaml_recipes = 'configs/recipes.yaml'
class Loader: class Loader:
@ -10,24 +18,29 @@ class Loader:
self.foods_list = {' ': [[0, 0], [0, 0], [0, 0]]} self.foods_list = {' ': [[0, 0], [0, 0], [0, 0]]}
self.pots_list = {' ': [[0, 0], [0, 0], [0, 0]]} self.pots_list = {' ': [[0, 0], [0, 0], [0, 0]]}
self.recipes_list = {'NEW': [0, 0, 0]} self.recipes_list = {'NEW': [0, 0, 0]}
self.config = DefaultConfig()
try: try:
with open('../configs/users.yaml', 'r') as file: with open(self.relative_import(self.config.yaml_user), 'r') as file:
self.user_list.update(yaml.safe_load(file)) self.user_list.update(yaml.safe_load(file))
except FileNotFoundError as e: except FileNotFoundError as e:
print(e) print(e)
try: try:
with open('../configs/consumables.yaml', 'r') as file: with open(self.relative_import(self.config.yaml_consumable), 'r') as file:
loaded_file = yaml.safe_load(file) loaded_file = yaml.safe_load(file)
self.foods_list.update(loaded_file['Foods']) self.foods_list.update(loaded_file['Foods'])
self.pots_list.update(loaded_file['Pots']) self.pots_list.update(loaded_file['Pots'])
except FileNotFoundError as e: except FileNotFoundError as e:
print(e) print(e)
try: try:
with open('../configs/recipes.yaml', 'r') as file: with open(self.relative_import(self.config.yaml_recipes), 'r') as file:
self.recipes_list.update(yaml.safe_load(file)) self.recipes_list.update(yaml.safe_load(file))
except FileNotFoundError as e: except (FileNotFoundError,IsADirectoryError) as e:
print(e) print(e)
def relative_import(self, path):
return (os.path.normpath(os.path.join(__file__,"../..",path)))
def get_users_dict(self) -> dict: def get_users_dict(self) -> dict:
return self.user_list return self.user_list

Binary file not shown.

After

Width:  |  Height:  |  Size: 248 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 352 KiB

29
python/tox.ini Normal file
View File

@ -0,0 +1,29 @@
[tox]
minversion = 3.8.0
envlist = py37, py38, py39, flake8, mypy
isolated_build = true
[gh-actions]
python =
3.7: py36, mypy, flake8
3.8: py38
3.9: py39
[testenv]
setenv =
PYTHONPATH = {toxinidir}
deps =
-r{toxinidir}/requirements_dev.txt
commands =
pytest --basetemp={envtmpdir}
[testenv:flake8]
basepython = python3.10
deps = flake8
commands = flake8 src tests
[testenv:mypy]
basepython = python3.10
deps =
-r{toxinidir}/requirements_dev.txt
commands = mypy src

View File

@ -179,6 +179,8 @@ pub struct ActionList {
pub veneration: Action, pub veneration: Action,
pub great_strides: Action, pub great_strides: Action,
pub innovation: Action, pub innovation: Action,
//pub observe: Action,
//pub focused_synthesis: Action,
} }
impl Default for ActionList { impl Default for ActionList {
@ -208,6 +210,10 @@ impl Default for ActionList {
veneration: ActionBuilder::new("Veneration").cp(18).buff(Some((Buff::Veneration, 4))).build(), veneration: ActionBuilder::new("Veneration").cp(18).buff(Some((Buff::Veneration, 4))).build(),
great_strides: ActionBuilder::new("Great Strides").cp(32).buff(Some((Buff::GreatStrides, 3))).build(), great_strides: ActionBuilder::new("Great Strides").cp(32).buff(Some((Buff::GreatStrides, 3))).build(),
innovation: ActionBuilder::new("Innovation").cp(18).buff(Some((Buff::Innovation, 4))).build(), innovation: ActionBuilder::new("Innovation").cp(18).buff(Some((Buff::Innovation, 4))).build(),
// Todo: Add back
//observe: ActionBuilder::new("observe").cp(18).buff(Some((Buff::Observe, 1))).build(),
//focused_synthesis: ActionBuilder::new("focused_synthesis").cp(18).quality(100).build(),
} }
} }
} }

View File

@ -1,4 +1,5 @@
// #![warn(missing_docs,unsafe_code,unstable_features,)] // #![warn(missing_docs,unsafe_code,unstable_features,)]
use std::time::{Instant};
use clap::Parser; use clap::Parser;
use xiv_craft_solver; use xiv_craft_solver;
@ -6,15 +7,53 @@ use xiv_craft_solver;
struct CustomError(String); struct CustomError(String);
fn main() { fn main() {
let args = xiv_craft_solver::Args::parse(); let args = xiv_craft_solver::io::Args::parse();
let params = xiv_craft_solver::Parameters{ let params = xiv_craft_solver::io::Parameters::from_args(&args);
depth: args.depth,
threads: args.threads,
verbose: args.verbose,
};
// Start timer
let now = Instant::now();
println!("Solving...");
// Solve from config
let (recipe,stats) = xiv_craft_solver::load_from_config(&args.recipe_name, &args.file_name, &args.character_name); 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);
// Stop timer
let t_final = now.elapsed().as_millis();
// Show best result depending on selected value
match results{
None => {
println!("[Error] No solutions found for craft '{}' with crafter '{}' (ms)", args.recipe_name, args.character_name);
return
}
Some(ref res)=>{
// Show best results
if args.verbose>0{
println!("[Final] {} results were found:",res.len());
#[cfg(feature = "verbose")]
if args.verbose>1{
xiv_craft_solver::print_routes(&results);
}
}
},
}
println!("\n > SOLUTION [Least steps] <");
xiv_craft_solver::find_fast_route(&results).unwrap().pretty_print();
println!("\n > SOLUTION [Most durability] <");
xiv_craft_solver::find_safe_route(&results).unwrap().pretty_print();
println!("\n > SOLUTION [Most quality] < ");
xiv_craft_solver::find_quality_route(&results).unwrap().pretty_print();
// #[cfg(feature = "verbose")]
// if params.verbose>2{
// println!("[F] Top 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();
() ()
} }

View File

@ -3,7 +3,6 @@ use crate::action::Action;
use crate::specs::{Buff, BuffState, Recipe, Stats, Success}; use crate::specs::{Buff, BuffState, Recipe, Stats, Success};
use crate::Parameters; use crate::Parameters;
#[derive(Clone)] #[derive(Clone)]
pub struct Craft<'a> { pub struct Craft<'a> {
pub recipe: Recipe, pub recipe: Recipe,
@ -70,6 +69,20 @@ impl<'a> Craft<'a> {
self.actions.push(action); self.actions.push(action);
return self; return self;
} }
// Assumes the craft is finished and tries to add the last actions
// pub fn add_last_actions(&mut self)->&Self{
// let arg = (self.recipe.progress as f32 - self.progression as f32) / self.get_base_progression() as f32;
// self.durability+=10;
// if 0.0 < arg && arg < 1.2 { self.run_action(&ACTIONS.basic_synthesis);}
// if 1.2 <= arg && arg < 1.8 { self.cp+=7; self.run_action(&ACTIONS.careful_synthesis); }
// if 1.8 <= arg && arg < 2.0 {
// self.cp+=12;
// self.run_action(&ACTIONS.observe);
// self.run_action(&ACTIONS.focused_synthesis);
// }
// self
// }
} }
impl<'a> Debug for Craft<'a> { impl<'a> Debug for Craft<'a> {

225
src/io.rs Normal file
View File

@ -0,0 +1,225 @@
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,
pub desperate:bool,
pub byregot_step: u8,
}
#[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
#[arg(short, long, default_value_t = 4)]
pub threads: usize,
/// Desperate mode, will try to finish the craft above all
#[arg(short='D', long, default_value_t = false)]
pub desperate: bool,
/// Long mode, will try to find more solutions, at the expense of time
#[arg(short='l', long, default_value_t = false)]
pub long: bool,
}
/// 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 cp:i32,
#[pyo3(get)]
pub total_cp:u32,
#[pyo3(get)]
pub total_progression:u32,
#[pyo3(get)]
pub total_quality:u32,
#[pyo3(get)]
pub total_durability:u32,
#[pyo3(get)]
pub actions: Vec<String>,
#[pyo3(get)]
pub step1_solutions: usize,
#[pyo3(get)]
pub step2_solutions: usize,
#[pyo3(get)]
pub found_100_percent: bool,
}
/// Pretty display for SolverResult
impl Display for SolverResult{
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
println!("{:?}",self.actions);
Ok(())
}
}
//#[pymethods]
impl SolverResult{
pub fn from_craft(craft: & Craft,step1_solutions : usize,step2_solutions : usize, found_100_percent: bool)->SolverResult{
// Todo: recreate actions
// Where steps ?
let mut actions = craft.actions.iter().map(|action|
format!("{}",action.short_name)
).collect::<Vec<String>>();
let arg = (craft.recipe.progress as f32 - craft.progression as f32) / craft.get_base_progression() as f32;
if 0.0 < arg && arg < 1.2 { actions.push("basicSynth2".to_string()); }
if 1.2 <= arg && arg < 1.8 { actions.push("carefulSynthesis".to_string()); }
if 1.8 <= arg && arg < 2.0 {
actions.push("observe".to_string());
actions.push("focusedSynthesis".to_string());
}
SolverResult{
steps:craft.step_count,
progression: craft.progression,
quality:craft.quality,
durability:craft.durability,
actions:actions,
step1_solutions,
step2_solutions,
found_100_percent,
total_progression:craft.recipe.progress,
total_quality:craft.recipe.quality,
total_durability:craft.recipe.durability,
cp: craft.cp,
total_cp : craft.stats.max_cp,
}
}
}
#[pymethods]
impl SolverResult{
#[staticmethod]
pub fn default()->Self{
Self{
steps:0,
progression: 0,
quality:0,
durability:0,
total_progression:0,
total_quality:0,
total_durability:0,
actions:vec!["Act1".to_string(),"Act2".to_string()],
step1_solutions:0,
step2_solutions:0,
found_100_percent:false,
cp:0,
total_cp:0,
}
}
pub fn pretty_print(&self){
println!("Quality: [{}/{}] | Durability: [{}/{}] | Cp : [{}/{}] | Steps : {}",
self.quality, self.total_quality, self.durability, self.total_durability, self.cp, self.total_cp, self.steps);
println!("{:?}", self.actions);
}
}
impl Parameters{
pub fn from_args(args:& Args) -> Self{
Self{
depth: if args.desperate{11}else{8},
threads: args.threads,
verbose: args.verbose,
desperate: args.desperate,
byregot_step: if args.long{6}else{8}
}
}
}
////// 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!(test_result, m)?)?;
m.add_function(wrap_pyfunction!(solve_from_python, m)?)?;
Ok(())
}
///
#[cfg(not(feature="no_python"))]
#[pyfunction]
pub fn test_result()-> SolverResult {
SolverResult::default()
}
/// Create a stat struct stats with the base values
#[cfg(not(feature="no_python"))]
use crate::{Recipe,Stats,solve_craft};
#[cfg(not(feature="no_python"))]
#[pyfunction]
pub fn solve_from_python(values : &PyAny)->PyResult<Option<Vec<SolverResult>>>{
// // Create Recipe
let recipe = Recipe{
durability: values.getattr("durability")?.extract()?,
progress: values.getattr("progress")?.extract()?,
progress_divider: values.getattr("progress_divider")?.extract()?,
progress_modifier: values.getattr("progress_modifier")?.extract()?,
quality: values.getattr("quality")?.extract()?,
quality_divider:values.getattr("quality_divider")?.extract()?,
quality_modifier:values.getattr("quality_modifier")?.extract()?,
};
// Create Stats
let stats = Stats{
craftsmanship: values.getattr("craftsmanship")?.extract()?,
control: values.getattr("control")?.extract()?,
max_cp: values.getattr("max_cp")?.extract()?,
};
// Create parameters
let param = Parameters{
depth: values.getattr("depth")?.extract()?,
byregot_step: values.getattr("byregot_step")?.extract()?,
desperate: values.getattr("desperate")?.extract()?,
threads: values.getattr("threads")?.extract()?,
verbose: values.getattr("verbose")?.extract()?,
};
// println!("{:?} len: {:?} ",values,values.getattr("len()"));
let res = solve_craft(recipe, stats, param);
Ok(res)
}

View File

@ -1,98 +1,42 @@
use crate::io::SolverResult;
use crate::{ use crate::{
craft::Craft, craft::Craft,
specs::{Recipe,Stats}, specs::{Recipe,Stats},
io::Parameters,
}; };
use std::time::{Instant};
use threadpool::ThreadPool; use threadpool::ThreadPool;
use std::sync::{Arc,Mutex}; use std::sync::{Arc,Mutex};
use clap::Parser;
use pyo3::prelude::*;
mod solver; mod solver;
mod specs; mod specs;
pub mod action; pub mod action;
pub mod craft; pub mod craft;
pub mod io;
/// Solve the craft with given arguments, this functions calls threads and must own it's values
#[derive(Debug, Clone, Copy)] pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Option<Vec<SolverResult>>{
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,
}
#[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
pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Option<Vec<Craft<'a>>>{
// Load the craft with given arguments // Load the craft with given arguments
let craft = Craft::new(recipe,stats,params); let craft = Craft::new(recipe,stats,params);
// Start timer
let now = Instant::now();
// Start a threadpool // Start a threadpool
let pool = ThreadPool::new(params.threads); let pool = ThreadPool::new(params.threads);
#[cfg(feature = "verbose")] #[cfg(feature = "verbose")]
if params.verbose>0{ if params.verbose>0{
println!("Solving...\n");
println!("[P1] Starting phase 1..."); println!("[P1] Starting phase 1...");
} }
let phase1_routes = solver::generate_routes_phase1(craft); let phase1_routes = solver::generate_routes_phase1(craft);
let nb_p1 = phase1_routes.len();
#[cfg(feature = "verbose")] #[cfg(feature = "verbose")]
if params.verbose>0{ if params.verbose>0{
println!("[P1] Found {} routes, testing them all...",phase1_routes.len()); println!("[P1] Found {} routes, testing them all...",phase1_routes.len());
if params.verbose>1{ if params.verbose>1{ for r in &phase1_routes{
for r in &phase1_routes{ println!("[P1] {:?} p:{}% q:{}% c:{} d:{}",r.actions,r.progression,r.quality * 100 / r.recipe.quality,r.cp,r.durability);
println!("[P1] {:?} p:{}% q:{}% c:{} d:{}", }}
r.actions,
r.progression * 100 / r.recipe.progress,
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) // Core algorithm, fill all found routes with the best route (doesn't branch, just replace)
let arc_phase2_routes = Arc::new(Mutex::new(Vec::<Craft>::new())); let arc_phase2_routes = Arc::new(Mutex::new(Vec::<Craft>::new()));
@ -100,92 +44,46 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti
let _phase2_routes = Arc::clone(&arc_phase2_routes); let _phase2_routes = Arc::clone(&arc_phase2_routes);
pool.execute(move || { pool.execute(move || {
if let Some(_route) = solver::generate_routes_phase2(route){ if let Some(mut _route) = solver::generate_routes_phase2(route){
let mut shared = _phase2_routes.lock().unwrap(); let mut shared = _phase2_routes.lock().unwrap();
shared.push(_route); shared.append(&mut _route);
}; };
}); });
} }
pool.join(); pool.join();
let phase2_routes = arc_phase2_routes.lock().unwrap(); let phase2_routes = arc_phase2_routes.lock().unwrap();
let nb_p2 = phase2_routes.len();
// Drop on empty results
if phase2_routes.len()==0{
return None
}
// Print the results if verbose // Print the results if verbose
#[cfg(feature = "verbose")] #[cfg(feature = "verbose")]
if params.verbose>0{ if params.verbose>0{
println!("[P2] Found {} solutions, sorting",phase2_routes.len()); println!("[P2] Found {} solutions, sorting",phase2_routes.len());
if params.verbose>1{ for r in phase2_routes.iter(){
if params.verbose>1{ println!("[P2] {:?} p:{}% q:{}% d:{}", r.actions, r.progression * 100 / r.recipe.progress, r.quality * 100 / r.recipe.quality, r.durability);
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<Craft> = vec![]; // let mut valid_routes : Vec<Craft> = vec![];
let mut valid_solutions: Vec<SolverResult> = vec![];
for route in phase2_routes.iter(){ for route in phase2_routes.iter(){
if route.quality>=route.recipe.quality{ if route.quality>=route.recipe.quality{
valid_routes.push(route.clone()); // valid_routes.push(route.clone());
valid_solutions.push(SolverResult::from_craft(route,nb_p1,nb_p2,true));
} }
} }
// If no craft can make it to 100% HQ, fallback to base results
if valid_routes.len()==0{ if valid_solutions.len()==0{
for route in phase2_routes.iter(){valid_routes.push(route.clone())} // Deep copy through the mutex guard for route in phase2_routes.iter(){valid_solutions.push(SolverResult::from_craft(route,nb_p1,nb_p2,false));}
} }
Some(valid_solutions)
// Select best route TODO: Seperate function
let top_route = match valid_routes.iter().max_by_key(|route| route.quality) {
Some(top) => top,
None => {
#[cfg(feature = "verbose")]
println!("[P2] No route could finish the craft.\n[P2] Runtime {}ms. Now exiting...",now.elapsed().as_millis());
return None;
},
};
// Print best route TODO: Seperate function
let mut content = (&top_route.actions)
.iter()
.map(|action| {
format!("\"{}\"", action.short_name.clone())
})
.collect::<Vec<String>>();
// 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()); }
if 1.2 <= arg && arg < 1.8 { content.push("\"carefulSynthesis\"".to_string()); }
if 1.8 <= arg && arg < 2.0 {
content.push("\"observe\"".to_string());
content.push("\"focusedSynthesis\"".to_string());
}
#[cfg(feature = "verbose")]
if params.verbose>2{
println!("[F] Top route {:?}",top_route);
}
{
println!("Quality: {}/{}", top_route.quality, top_route.recipe.quality);
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)
} }
/// Load the config from args and make a craft from it /// Load the config from args and make a craft from it
@ -254,6 +152,49 @@ pub fn load_from_config<'a>(recipe_name: &str, file_name: &str, character_name:
(recipe,stats) (recipe,stats)
} }
// fn make_craft_from_values(){ /// Print all routes in the vect, verbose
pub fn print_routes<'a>(routes: & Option<Vec<SolverResult>>){
match routes{
Some(r) => {
println!("Showing {} routes",r.len());
for c in r.iter(){
println!("\n[{}¤][{}@][{}#] {:?} ",c.quality,c.durability,c.steps,c.actions)
}
},
None => println!("No routes to print")
}
}
// } /// Find the route with the least amount of steps
pub fn find_fast_route(routes: &Option<Vec<SolverResult>>) -> Option<&SolverResult>{
match routes {
Some(_routes) => {
if _routes.len()>0{
_routes.iter().min_by_key(|key| key.steps)
} else { None }
},
None => None,
}
}
/// Find the route with the maximum amount of quality
pub fn find_quality_route(routes: &Option<Vec<SolverResult>>) -> Option<&SolverResult>{
match routes {
Some(_routes) => _routes.iter().max_by_key(|key| key.quality),
None => None,
}
}
/// Find the route with the maximum of durability left
pub fn find_safe_route(routes: &Option<Vec<SolverResult>>) -> Option<&SolverResult>{
match routes {
Some(_routes) => {
if _routes.len()>0{
_routes.iter().max_by_key(|key| key.durability)
} else {
None
}
},
None => None,
}
}

View File

@ -8,6 +8,7 @@ macro_rules! action_vec {
($($tt:expr),*) => { vec![ $(Some(&$tt),)*]}; ($($tt:expr),*) => { vec![ $(Some(&$tt),)*]};
} }
/// Find the next authorised action for this step of the craft
pub fn next_action_picker_1<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> { pub fn next_action_picker_1<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
if craft.success != Success::Pending { return vec![None]; } if craft.success != Success::Pending { return vec![None]; }
let mut available_actions = Vec::<Option<&'a Action>>::new(); let mut available_actions = Vec::<Option<&'a Action>>::new();
@ -30,8 +31,10 @@ pub fn next_action_picker_1<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
available_actions.append(&mut action_vec![ACTIONS.basic_synthesis,ACTIONS.careful_synthesis,ACTIONS.prudent_synthesis,ACTIONS.delicate_synthesis]); available_actions.append(&mut action_vec![ACTIONS.basic_synthesis,ACTIONS.careful_synthesis,ACTIONS.prudent_synthesis,ACTIONS.delicate_synthesis]);
// ACTIONS.groundwork for the --pls // ACTIONS.groundwork for the --pls
// available_actions.append(&mut action_vec![ACTIONS.groundwork]); if craft.args.desperate{
available_actions.append(&mut action_vec![ACTIONS.groundwork]);
}
// For long first run // For long first run
if craft.step_count > 8 {available_actions.append(&mut action_vec![ACTIONS.waste_not_ii, ACTIONS.waste_not])}; if craft.step_count > 8 {available_actions.append(&mut action_vec![ACTIONS.waste_not_ii, ACTIONS.waste_not])};
@ -46,6 +49,8 @@ pub fn next_action_picker_1<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
result_actions result_actions
} }
/// Find all routes that can finish in one more action
pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec<Craft<'a>> { pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec<Craft<'a>> {
let mut queue = Vec::new(); let mut queue = Vec::new();
queue.push(craft); queue.push(craft);
@ -80,7 +85,6 @@ pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec<Craft<'a>> {
// 8 Seemed to be a good initial guess with enouth to use a good amount of WN / WNII to get close // 8 Seemed to be a good initial guess with enouth to use a good amount of WN / WNII to get close
// A higher value will yield more initial guesses with minimal benefits // A higher value will yield more initial guesses with minimal benefits
// A lover value will yield less initial guesses and might spent too much CP to get to the required progression // A lover value will yield less initial guesses and might spent too much CP to get to the required progression
// TODO: Pass a flag to get more attempts
if craft.step_count < craft.args.depth { queue.push(craft); } if craft.step_count < craft.args.depth { queue.push(craft); }
} }
} }
@ -88,6 +92,7 @@ pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec<Craft<'a>> {
} }
/// Find the list of authorised actions for this step
pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> { pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
let mut available_actions = vec![&ACTIONS.basic_touch, &ACTIONS.prudent_touch, &ACTIONS.preparatory_touch]; let mut available_actions = vec![&ACTIONS.basic_touch, &ACTIONS.prudent_touch, &ACTIONS.preparatory_touch];
let mut forbidden_actions = Vec::new(); let mut forbidden_actions = Vec::new();
@ -125,7 +130,7 @@ pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
forbidden_actions.push(&ACTIONS.basic_touch); forbidden_actions.push(&ACTIONS.basic_touch);
} }
// Todo, allow earlier byregot if the craft can be finished all the same (useless with always optimize on) // Todo, allow earlier byregot if the craft can be finished all the same (useless with always optimize on)
if craft.buffs.inner_quiet >= 8 { // 10 if craft.buffs.inner_quiet >= craft.args.byregot_step { // 10
available_actions.push(&ACTIONS.trained_finesse); available_actions.push(&ACTIONS.trained_finesse);
available_actions.push(&ACTIONS.great_strides); available_actions.push(&ACTIONS.great_strides);
} }
@ -137,8 +142,7 @@ pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
} }
} }
let mut final_actions: Vec<Option<&Action>> = Vec::new(); let mut final_actions: Vec<Option<&Action>> = Vec::new();
//drop duplicates
for action in available_actions { for action in available_actions {
if !forbidden_actions.contains(&action) && !final_actions.iter().any(|a| a.unwrap() == action) { if !forbidden_actions.contains(&action) && !final_actions.iter().any(|a| a.unwrap() == action) {
final_actions.push(Some(action)); final_actions.push(Some(action));
@ -147,12 +151,14 @@ pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
final_actions final_actions
} }
pub fn generate_routes_phase2<'a>(craft: Craft<'a>) -> Option<Craft<'a>> { /// Apply all actions to the current route
pub fn generate_routes_phase2<'a>(craft: Craft<'a>) -> Option<Vec<Craft<'a>>> {
let mut queue = VecDeque::new(); let mut queue = VecDeque::new();
// println!("{}", ACTIONS.careful_synthesis.can_use(&craft)); // Todo: Return a vec of relevant functions, instead of the most quality one
let mut top_route: Option<Craft<'a>> = Some(craft.clone()); // Default route, no hq on that one let mut top_route: Craft<'a> = craft.clone(); // Default route, no hq on that one
let mut top_routes: Vec<Craft<'a>> = vec![];
queue.push_back(craft); queue.push_back(craft);
while !queue.is_empty() { while !queue.is_empty() {
@ -164,18 +170,21 @@ pub fn generate_routes_phase2<'a>(craft: Craft<'a>) -> Option<Craft<'a>> {
let mut craft = _craft.clone(); let mut craft = _craft.clone();
craft.run_action(action.unwrap()); craft.run_action(action.unwrap());
if action.unwrap() == &ACTIONS.byregot_blessing { if action.unwrap() == &ACTIONS.byregot_blessing {
if let Some(top_route) = &mut top_route { #[cfg(not(feature="fast"))]
if top_route.quality < craft.quality { if top_route.quality>=craft.recipe.quality{
// TODO: Should we erase the craft if the improvement is cosmetic (aka, already finished) top_routes.push(craft.clone()); // Me memory
*top_route = craft; }
} if top_route.quality < craft.quality {
} else { #[cfg(feature="fast")]
top_route = Some(craft); top_routes.push(craft.clone());
top_route = craft;
} }
} else { } else {
queue.push_back(craft); queue.push_back(craft);
} }
} }
} }
top_route // Let's not forget the best result
top_routes.push(top_route);
Some(top_routes)
} }

View File

@ -33,7 +33,7 @@ pub enum Buff {
// v Hidden v // v Hidden v
BasicTouch, BasicTouch,
StandardTouch, StandardTouch,
// Observe, Observe,
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
@ -47,6 +47,7 @@ pub struct BuffState {
pub muscle_memory: u8, pub muscle_memory: u8,
pub basic_touch: u8, pub basic_touch: u8,
pub standard_touch: u8, pub standard_touch: u8,
pub observe: u8,
} }
impl BuffState { impl BuffState {
@ -61,6 +62,7 @@ impl BuffState {
muscle_memory: 0, muscle_memory: 0,
basic_touch: 0, basic_touch: 0,
standard_touch: 0, standard_touch: 0,
observe: 0,
} }
} }
@ -75,6 +77,7 @@ impl BuffState {
Buff::MuscleMemory => self.muscle_memory = 0, Buff::MuscleMemory => self.muscle_memory = 0,
Buff::BasicTouch => self.basic_touch = 0, Buff::BasicTouch => self.basic_touch = 0,
Buff::StandardTouch => self.standard_touch = 0, Buff::StandardTouch => self.standard_touch = 0,
Buff::Observe => self.observe = 0,
} }
} }
@ -95,11 +98,11 @@ impl BuffState {
Buff::MuscleMemory => self.muscle_memory = value, Buff::MuscleMemory => self.muscle_memory = value,
Buff::BasicTouch => self.basic_touch = value, Buff::BasicTouch => self.basic_touch = value,
Buff::StandardTouch => self.standard_touch = value, Buff::StandardTouch => self.standard_touch = value,
Buff::Observe => self.standard_touch = value,
} }
} }
pub fn tick(&mut self) { pub fn tick(&mut self) {
if self.waste_not > 0 { self.waste_not -= 1; } if self.waste_not > 0 { self.waste_not -= 1; }
if self.great_strides > 0 { self.great_strides -= 1; } if self.great_strides > 0 { self.great_strides -= 1; }
if self.innovation > 0 { self.innovation -= 1; } if self.innovation > 0 { self.innovation -= 1; }