Compare commits
80 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
49d1e9d300 | |
|
|
93043bdd18 | |
|
|
6fb5e8409a | |
|
|
f6c6d0c5aa | |
|
|
a87e425829 | |
|
|
753e6cf4e5 | |
|
|
2aa56b70e4 | |
|
|
aae80ae864 | |
|
|
6ec10f7372 | |
|
|
0b95d42d68 | |
|
|
79a3006fa2 | |
|
|
5cd3d65de6 | |
|
|
d5a0f1b543 | |
|
|
a6e7fac1b7 | |
|
|
b91287c160 | |
|
|
72a1fa4fdc | |
|
|
a54c09bc66 | |
|
|
283d00d31a | |
|
|
686c7d97c0 | |
|
|
25678a307a | |
|
|
9cf9791a37 | |
|
|
9fa1ee8cf6 | |
|
|
a5c196b764 | |
|
|
0c5ed39573 | |
|
|
47792825f7 | |
|
|
95353bd86d | |
|
|
78e7f56b67 | |
|
|
4321cb1a6a | |
|
|
c0aafa15bd | |
|
|
cf9fe275ee | |
|
|
a2b618f566 | |
|
|
fca57523eb | |
|
|
383912d8f4 | |
|
|
d8819feb41 | |
|
|
f090c6551f | |
|
|
53779bb19d | |
|
|
0df009ce98 | |
|
|
4f2e2b0aa8 | |
|
|
b9b751cc28 | |
|
|
ac25cff955 | |
|
|
7967a9dcdb | |
|
|
c90b24fd6f | |
|
|
a6c523bd78 | |
|
|
d6544cc34a | |
|
|
fad34e903d | |
|
|
590f8f6787 | |
|
|
4f94ebd05f | |
|
|
b15d971c75 | |
|
|
021d42c2fd | |
|
|
2883f14d71 | |
|
|
de0f279d92 | |
|
|
aef7f86742 | |
|
|
bf8da55379 | |
|
|
e17e101c39 | |
|
|
6d9fdf8d9a | |
|
|
d6081edeb7 | |
|
|
ed904f5eca | |
|
|
3e1796f2d6 | |
|
|
b73129aa38 | |
|
|
fcaf53a150 | |
|
|
6f1e721c5d | |
|
|
b4db930466 | |
|
|
d1e6c9d248 | |
|
|
9678a3bd98 | |
|
|
b47d51c7ac | |
|
|
67b67712cf | |
|
|
4015bda699 | |
|
|
7a8dca2f06 | |
|
|
198c590442 | |
|
|
18d6321fe6 | |
|
|
a3a7af5706 | |
|
|
cee056ef3a | |
|
|
e7bced1505 | |
|
|
775dc29f13 | |
|
|
4267db11da | |
|
|
ba71725d69 | |
|
|
09e88a8f78 | |
|
|
f20596691b | |
|
|
6ffe91174b | |
|
|
42aadd5af9 |
|
|
@ -0,0 +1,9 @@
|
|||
[bumpversion]
|
||||
current_version = 0.1.8
|
||||
tag = True
|
||||
|
||||
[bumpversion:file:python/pyproject.toml]
|
||||
|
||||
[bumpversion:file:Cargo.toml]
|
||||
|
||||
[bumpversion:file:pyproject.toml]
|
||||
|
|
@ -1,11 +1,14 @@
|
|||
/target
|
||||
/.idea
|
||||
*.iml
|
||||
expected_values.md
|
||||
/bin.py
|
||||
python/dontlook.py
|
||||
expected_values.md
|
||||
releases/*
|
||||
.whl
|
||||
pyinstaller_log.txt
|
||||
llvm/*
|
||||
/coverage/*
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
|
|
@ -159,4 +162,5 @@ dmypy.json
|
|||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
cython_debug/
|
||||
Cargo.lock
|
||||
|
|
@ -63,6 +63,22 @@ dependencies = [
|
|||
"os_str_bytes",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctor"
|
||||
version = "0.1.26"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6d2301688392eb071b0bf1a37be05c469d3cc4dbbd95df672fe28ab021e6a096"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "diff"
|
||||
version = "0.1.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8"
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.2.8"
|
||||
|
|
@ -86,9 +102,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.4.0"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9"
|
||||
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
|
|
@ -192,6 +208,15 @@ version = "6.4.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b7820b9daea5457c9f21c69448905d723fbd21136ccf521748f23fd49e723ee"
|
||||
|
||||
[[package]]
|
||||
name = "output_vt100"
|
||||
version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "628223faebab4e3e40667ee0b2336d34a5b960ff60ea743ddfdbcf7770bcfb66"
|
||||
dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.12.1"
|
||||
|
|
@ -215,6 +240,18 @@ dependencies = [
|
|||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pretty_assertions"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a25e9bcb20aa780fd0bb16b72403a9064d6b3f22f026946029acb941a50af755"
|
||||
dependencies = [
|
||||
"ctor",
|
||||
"diff",
|
||||
"output_vt100",
|
||||
"yansi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-error"
|
||||
version = "1.0.4"
|
||||
|
|
@ -241,9 +278,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.43"
|
||||
version = "1.0.51"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0a2ca2c61bc9f3d74d2886294ab7b9853abd9c1ad903a3ac7815c58989bb7bab"
|
||||
checksum = "5d727cae5b39d21da60fa540906919ad737832fe0b1c165da3a34d6548c849d6"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
|
@ -310,9 +347,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.21"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179"
|
||||
checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
|
@ -342,9 +379,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.9"
|
||||
version = "1.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97477e48b4cf8603ad5f7aaf897467cf42ab4218a38ef76fb14c2d6773a6d6a8"
|
||||
checksum = "5583e89e108996506031660fe09baa5011b9dd0341b89029313006d1fb508d70"
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
|
|
@ -354,9 +391,9 @@ checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
|
|||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.144"
|
||||
version = "1.0.152"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f747710de3dcd43b88c9168773254e809d8ddbdf9653b84e2554ab219f17860"
|
||||
checksum = "bb7d1f0d3021d347a83e556fc4683dea2ea09d87bccdf88ff5c12545d89d5efb"
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
|
|
@ -394,9 +431,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "1.0.99"
|
||||
version = "1.0.108"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "58dbef6ec655055e20b86b15a8cc6d439cca19b667537ac6a1369572d151ab13"
|
||||
checksum = "d56e159d99e6c2b93995d171050271edb50ecc5288fbc7cc17de8fdce4e58c14"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
|
@ -429,18 +466,18 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "0.5.9"
|
||||
version = "0.5.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7"
|
||||
checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.3"
|
||||
version = "1.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4f5b37a154999a8f3f98cc23a628d850e154479cd94decf3414696e12e31aaf"
|
||||
checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc"
|
||||
|
||||
[[package]]
|
||||
name = "unindent"
|
||||
|
|
@ -552,14 +589,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd"
|
||||
|
||||
[[package]]
|
||||
name = "xiv_craft_solver"
|
||||
version = "0.1.3"
|
||||
name = "xiv_csolver"
|
||||
version = "0.1.7"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"lazy_static",
|
||||
"pretty_assertions",
|
||||
"pyo3",
|
||||
"strum",
|
||||
"strum_macros",
|
||||
"threadpool",
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yansi"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec"
|
||||
|
|
|
|||
24
Cargo.toml
|
|
@ -1,9 +1,13 @@
|
|||
[package]
|
||||
name = "xiv_craft_solver"
|
||||
version = "0.1.3"
|
||||
name = "xiv_csolver"
|
||||
version = "0.1.8"
|
||||
edition = "2021"
|
||||
authors = ["谭俊健","Dandaedre","Vkyfox"]
|
||||
description = "Small XIV solver library in rust, with python and rust bindings"
|
||||
homepage = "https://proxy.dandaedre.com/gitea/Dandaedre/xiv_csolver"
|
||||
documentation = "https://proxy.dandaedre.com/gitea/Dandaedre/xiv_csolver"
|
||||
repository = "https://proxy.dandaedre.com/gitea/Dandaedre/xiv_csolver.git"
|
||||
license = "Apache-2.0"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
|
|
@ -15,7 +19,7 @@ toml = "0.5.9"
|
|||
clap = {version = "4.1.6", features = ["derive"]}
|
||||
threadpool = "1.8.1"
|
||||
# For python bindings TODO: make it optionnal
|
||||
pyo3 = { version = "0.18.0", features = ["extension-module"] }
|
||||
pyo3 = { version = "0.18.1", features= ["extension-module"]}
|
||||
|
||||
# [target.'cfg(not(no_python))'.dependencies]
|
||||
# pyo3 = { version = "0.18.0", features = ["extension-module"] }
|
||||
|
|
@ -23,25 +27,27 @@ pyo3 = { version = "0.18.0", features = ["extension-module"] }
|
|||
# [build]
|
||||
# target = ["x86_64-unknown-linux-gnu", "x86_64-unknown-windows-gnu"]
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = "1"
|
||||
|
||||
[profile.release]
|
||||
panic = 'abort'
|
||||
opt-level = 3
|
||||
lto = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
extension-module = ["pyo3/extension-module"]
|
||||
default = ["extension-module"]
|
||||
verbose = []
|
||||
no_python = [] # Removes the python bindings
|
||||
fast = [] # Remove some under optimisations that try to find other routes
|
||||
|
||||
[lib]
|
||||
name = "xiv_craft_solver" # Pending rename ffcraft_solver_lib
|
||||
name = "xiv_csolver_lib"
|
||||
path = "src/lib.rs"
|
||||
crate-type = ["cdylib","rlib"]
|
||||
|
||||
[[bin]]
|
||||
name = "ffcraft_solver_cli"
|
||||
path = "src/bin/ffcraft.rs"
|
||||
name = "xiv_csolver_cli"
|
||||
path = "src/bin/xiv_csolver.rs"
|
||||
|
||||
[tool.maturin]
|
||||
python-source = "python"
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
[tasks.release]
|
||||
dependencies = [
|
||||
"format",
|
||||
"clean",
|
||||
"build",
|
||||
"maturin",
|
||||
"maturin_build",
|
||||
"pip",
|
||||
"pyinstaller",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[tasks.upload]
|
||||
script_runner="@shell"
|
||||
ignore_errors = true
|
||||
script = [
|
||||
"twine upload releases/xiv_csolver*.whl --repository gitea",
|
||||
"twine upload releases/xiv_csolver_lib*.whl --repository gitea",
|
||||
]
|
||||
|
||||
[tasks.fmt]
|
||||
script_runner = "@shell"
|
||||
script = [
|
||||
"cargo +nightly fmt -- --config format_code_in_doc_comments=true --config imports_granularity=Module"
|
||||
]
|
||||
|
||||
[tasks.testcov]
|
||||
script_runner = "@shell"
|
||||
ignore_errors = true
|
||||
script = [
|
||||
"mkdir -p coverage",
|
||||
"mkdir -p coverage/html",
|
||||
"mkdir -p coverage/",
|
||||
"CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage -Ccodegen-units=1 -Copt-level=0 -Coverflow-checks=off' LLVM_PROFILE_FILE='llvm/cargo-test-%p-%m.profraw' cargo test",
|
||||
"grcov . --binary-path ./target/debug/deps/ -s . -t html --branch --ignore-not-existing --ignore '../*' --ignore '/*' --ignore '*xiv_csolver.rs' --ignore '*python*.rs' -o coverage/html/",
|
||||
]
|
||||
|
||||
[tasks.clean]
|
||||
command = "cargo"
|
||||
args = ["clean"]
|
||||
dependencies = ["remove_tmp"]
|
||||
|
||||
[tasks.remove_tmp]
|
||||
script_runner = "@shell"
|
||||
ignore_errors = true
|
||||
script = '''
|
||||
rm -rf releases
|
||||
rm -rf python/build
|
||||
rm -rf python/dist
|
||||
'''
|
||||
|
||||
[tasks.zip]
|
||||
windows_alias = 'zip_win'
|
||||
linux_alias = 'zip_linux'
|
||||
|
||||
[tasks.zip_linux]
|
||||
script_runner = "@shell"
|
||||
script = '''
|
||||
mkdir -p releases # Add version as an arg and things
|
||||
cp target/wheels/*.whl releases/
|
||||
zip releases/xiv_csolver_cli_linux.zip -j target/release/xiv_csolver_cli craft.toml -j target/release/libxiv_craft_solver.so
|
||||
cd python/dist/ && zip ../../releases/xiv_csolver_gui_linux.zip -r xiv_csolver_gui_linux/
|
||||
'''
|
||||
|
||||
[tasks.zip_win]
|
||||
script_runner = "@shell"
|
||||
script = '''
|
||||
mkdir -p releases # Add version as an arg and things
|
||||
cp target/wheels/*.whl releases/
|
||||
tar acvf releases/xiv_csolver_cli_win.zip .\craft.toml -C .\target\release\ xiv_csolver_cli.exe libxiv_craft_solver.d
|
||||
tar acvf releases/xiv_csolver_gui_win.zip -C .\python\dist\ .\xiv_csolver_gui_win\*
|
||||
'''
|
||||
|
||||
[tasks.pip]
|
||||
script_runner = "@shell"
|
||||
ignore_errors = true
|
||||
script = '''
|
||||
cd python
|
||||
rm -rf build dist
|
||||
pip install -q -r requirements_dev.txt
|
||||
pip install -q -e .
|
||||
python -m pip wheel . --wheel-dir=../releases/
|
||||
'''
|
||||
|
||||
[tasks.pyinstaller]
|
||||
windows_alias = "windows_pyinstaller"
|
||||
linux_alias = "linux_pyinstaller"
|
||||
|
||||
[tasks.linux_pyinstaller]
|
||||
script_runner = "@shell"
|
||||
script = '''
|
||||
cd python
|
||||
pyinstaller src/xiv_csolver/__main__.py -i "src/xiv_csolver/ressources/xiv_csolver.ico" --add-data "src/xiv_csolver/configs/:xiv_csolver/configs" --add-data "src/xiv_csolver/ressources/:xiv_csolver/ressources" --name xiv_csolver_gui_linux -y
|
||||
'''
|
||||
|
||||
[tasks.windows_pyinstaller]
|
||||
script_runner = "@shell"
|
||||
script = '''
|
||||
cd python
|
||||
pyinstaller src\xiv_csolver\__main__.py -i "src/xiv_csolver/ressources/xiv_csolver.ico" --add-data "src\xiv_csolver\configs\;xiv_csolver\configs" --add-data "src\xiv_csolver\ressources\;xiv_csolver\ressources" --name xiv_csolver_gui_win -y
|
||||
'''
|
||||
|
||||
[tasks.build]
|
||||
command = "cargo"
|
||||
args = ["build","--release"]
|
||||
dependencies = ["clean"]
|
||||
|
||||
[tasks.maturin]
|
||||
command = "maturin"
|
||||
args = ["develop", "--release"]
|
||||
|
||||
[tasks.maturin_build]
|
||||
command = "maturin"
|
||||
args = ["build", "--release"]
|
||||
|
||||
[tasks.rebuild]
|
||||
dependencies = ["clean","build","maturin","pip"]
|
||||
|
||||
[tasks.rust]
|
||||
dependencies = ["build","maturin"]
|
||||
19
README.md
|
|
@ -1,9 +1,12 @@
|
|||
# xiv_craft_solver
|
||||
# xiv_csolver
|
||||
A rust program for solving FFXIV craft recipe.
|
||||
|
||||
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.
|
||||
|
|
@ -19,7 +22,7 @@ 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]
|
||||
Usage: xiv_csolver_cli [OPTIONS]
|
||||
|
||||
Options:
|
||||
-r, --recipe-name <RECIPE_NAME>
|
||||
|
|
@ -43,7 +46,13 @@ Options:
|
|||
-V, --version
|
||||
Print version
|
||||
```
|
||||
|
||||
## Developpement
|
||||
Please remember to set and use a venv before building
|
||||
While not mandatory, using ``cargo-make`` will provide you with the commands:
|
||||
- cargo make rebuild (rebuilding both the rust and pip bindings)
|
||||
- cargo make release (rebuilding and bundling the executables (for your os)) in a releases folder
|
||||
|
||||
### Rust
|
||||
Everything is located in the root & src.
|
||||
You can build the program (CLI) with cargo build the following features are available
|
||||
|
|
@ -51,8 +60,9 @@ You can build the program (CLI) with cargo build the following features are avai
|
|||
- 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``
|
||||
To build the python module, run either ``maturin develop`` or ``maturin build`` then ``maturin install``
|
||||
|
||||
### Python
|
||||
#### Developping the GUI
|
||||
|
|
@ -60,10 +70,9 @@ To build the python module, run ``maturin develop`` or ``maturin build`` then ``
|
|||
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``
|
||||
4. Invoke the project (from anywhere) ``python -m xiv_csolver``
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,41 @@
|
|||
# Pre-Release
|
||||
|
||||
## v0.2
|
||||
### Breaking
|
||||
✅ (GUI) Make macros work
|
||||
🟩 (GUI) Visual feedback when pressing solve
|
||||
🟩 (GUI) Update on the Quality %
|
||||
✅ (GUI) Ability to save
|
||||
✅ (GUI) Make the logging work
|
||||
✅ (PKG) Rename libs, bin, python, exe
|
||||
### Important
|
||||
✅ (PKG) Have cargo-make setup for release/cleanup/build
|
||||
✅ (PKG) Merge latest pre-release for the GUI
|
||||
✅ (PKG) Have a rebuild function
|
||||
🟩 (CLI) Rework the parameters and return structs to only have one ref each
|
||||
### Features
|
||||
🟩 (GUI) Refactor code
|
||||
🟩 (GUI) Restore GUI state
|
||||
🟩 (GUI) Bugfix the gui and clean it up
|
||||
🟩 (LIB) Restructure code, cleanup the mess
|
||||
🟩 (LIB) Have an autoretry
|
||||
🟩 (LIB) Have the autoretry be smart and/or threaded with interrupts
|
||||
🟩 (LIB) Cleanup the Toml to have one unique Food/Receipe/Craftsman with the gui
|
||||
🟩 (LIB) Be more aggressive with the mem optimisations
|
||||
🟩 (LIB) Have a thread interrupt mode for fast mode
|
||||
🟩 (LIB) Cleanup features (verbose doesn't really make sense)
|
||||
|
||||
# Roadmap
|
||||
## v1.0.0
|
||||
|
||||
### Important
|
||||
✅ (LIB) Rust API docs
|
||||
🟩 (CLI) Accept and copy from the base recipes
|
||||
🟩 (CLI) Accept and copy pots & food
|
||||
🟩 (PKG) Have a unified toml/yaml way of registering recipes
|
||||
🟩 (LIB) Tests
|
||||
|
||||
### Features
|
||||
🟩 (GUI) Have full documentation
|
||||
🟩 (LIB) Benchmarks
|
||||
🟩 (GUI) Code coverage
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 99%">
|
||||
<title>coverage: 99%</title>
|
||||
<linearGradient id="s" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
|
||||
<stop offset="1" stop-opacity=".1"/>
|
||||
</linearGradient>
|
||||
<clipPath id="r">
|
||||
<rect width="96" height="20" rx="3" fill="#fff"/>
|
||||
</clipPath>
|
||||
<g clip-path="url(#r)">
|
||||
<rect width="61" height="20" fill="#555"/>
|
||||
<rect x="61" width="35" height="20" fill="#97ca00"/>
|
||||
<rect width="96" height="20" fill="url(#s)"/>
|
||||
</g>
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110">
|
||||
<text aria-hidden="true" x="315" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="510">coverage</text>
|
||||
<text x="315" y="140" transform="scale(.1)" fill="#fff" textLength="510">coverage</text>
|
||||
<text aria-hidden="true" x="775" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">99%</text>
|
||||
<text x="775" y="140" transform="scale(.1)" fill="#fff" textLength="250">99%</text>
|
||||
</g>
|
||||
<script xmlns=""/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
|
|
@ -0,0 +1,13 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="20" role="img" aria-label="coverage: 99%">
|
||||
<title>coverage: 99%</title>
|
||||
<g shape-rendering="crispEdges">
|
||||
<rect width="61" height="20" fill="#555"/>
|
||||
<rect x="61" width="35" height="20" fill="#97ca00"/>
|
||||
</g>
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110">
|
||||
<text x="315" y="140" transform="scale(.1)" fill="#fff" textLength="510">coverage</text>
|
||||
<text x="775" y="140" transform="scale(.1)" fill="#fff" textLength="250">99%</text>
|
||||
</g>
|
||||
<script xmlns=""/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 712 B |
|
|
@ -0,0 +1,13 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink" width="142.5" height="28" role="img" aria-label="COVERAGE: 99%">
|
||||
<title>COVERAGE: 99%</title>
|
||||
<g shape-rendering="crispEdges">
|
||||
<rect width="91" height="28" fill="#555"/>
|
||||
<rect x="91" width="51.5" height="28" fill="#97ca00"/>
|
||||
</g>
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="100">
|
||||
<text fill="#fff" x="455" y="175" transform="scale(.1)" textLength="670">COVERAGE</text>
|
||||
<text fill="#fff" x="1167.5" y="175" font-weight="bold" transform="scale(.1)" textLength="275">99%</text>
|
||||
</g>
|
||||
<script xmlns=""/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 739 B |
|
|
@ -0,0 +1,25 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink" width="96" height="18" role="img" aria-label="coverage: 99%">
|
||||
<title>coverage: 99%</title>
|
||||
<linearGradient id="s" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#fff" stop-opacity=".7"/>
|
||||
<stop offset=".1" stop-color="#aaa" stop-opacity=".1"/>
|
||||
<stop offset=".9" stop-color="#000" stop-opacity=".3"/>
|
||||
<stop offset="1" stop-color="#000" stop-opacity=".5"/>
|
||||
</linearGradient>
|
||||
<clipPath id="r">
|
||||
<rect width="96" height="18" rx="4" fill="#fff"/>
|
||||
</clipPath>
|
||||
<g clip-path="url(#r)">
|
||||
<rect width="61" height="18" fill="#555"/>
|
||||
<rect x="61" width="35" height="18" fill="#97ca00"/>
|
||||
<rect width="96" height="18" fill="url(#s)"/>
|
||||
</g>
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110">
|
||||
<text aria-hidden="true" x="315" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="510">coverage</text>
|
||||
<text x="315" y="130" transform="scale(.1)" fill="#fff" textLength="510">coverage</text>
|
||||
<text aria-hidden="true" x="775" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">99%</text>
|
||||
<text x="775" y="130" transform="scale(.1)" fill="#fff" textLength="250">99%</text>
|
||||
</g>
|
||||
<script xmlns=""/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
|
|
@ -0,0 +1,27 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:xlink="http://www.w3.org/1999/xlink" width="99" height="20" role="img" aria-label="Coverage: 99%">
|
||||
<title>Coverage: 99%</title>
|
||||
<style>a:hover #llink{fill:url(#b);stroke:#ccc}a:hover #rlink{fill:#4183c4}</style>
|
||||
<linearGradient id="a" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#fcfcfc" stop-opacity="0"/>
|
||||
<stop offset="1" stop-opacity=".1"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="b" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#ccc" stop-opacity=".1"/>
|
||||
<stop offset="1" stop-opacity=".1"/>
|
||||
</linearGradient>
|
||||
<g stroke="#d5d5d5">
|
||||
<rect stroke="none" fill="#fcfcfc" x="0.5" y="0.5" width="61" height="19" rx="2"/>
|
||||
<rect x="67.5" y="0.5" width="31" height="19" rx="2" fill="#fafafa"/>
|
||||
<rect x="67" y="7.5" width="0.5" height="5" stroke="#fafafa"/>
|
||||
<path d="M67.5 6.5 l-3 3v1 l3 3" stroke="d5d5d5" fill="#fafafa"/>
|
||||
</g>
|
||||
<g aria-hidden="true" fill="#333" text-anchor="middle" font-family="Helvetica Neue,Helvetica,Arial,sans-serif" text-rendering="geometricPrecision" font-weight="700" font-size="110px" line-height="14px">
|
||||
<rect id="llink" stroke="#d5d5d5" fill="url(#a)" x=".5" y=".5" width="61" height="19" rx="2"/>
|
||||
<text aria-hidden="true" x="305" y="150" fill="#fff" transform="scale(.1)" textLength="510">Coverage</text>
|
||||
<text x="305" y="140" transform="scale(.1)" textLength="510">Coverage</text>
|
||||
<text aria-hidden="true" x="825" y="150" fill="#fff" transform="scale(.1)" textLength="230">99%</text>
|
||||
<text id="rlink" x="825" y="140" transform="scale(.1)" textLength="230">99%</text>
|
||||
</g>
|
||||
<script xmlns=""/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.7 KiB |
27
makefile
|
|
@ -1,27 +0,0 @@
|
|||
clean:
|
||||
@echo "[MAKE] Cleaning last release"
|
||||
cargo clean
|
||||
rm -rf releases
|
||||
rm -rf python/build
|
||||
rm -rf python/dist
|
||||
|
||||
rust:
|
||||
@echo "[MAKE] Building the libraries"
|
||||
maturin develop --release -q
|
||||
cargo build --release -q # --features="no_python"
|
||||
|
||||
python:
|
||||
@echo "[MAKE] Building the python project"
|
||||
cd python && rm -rf build dist
|
||||
cd python && pip install -q -r requirements_dev.txt
|
||||
cd python && pip install -q -e .
|
||||
cd python && pyinstaller src/ffcraft_solver/__main__.py -i "src/ffcraft_solver/ressources/ffcraft_solver.ico" --add-data "src/ffcraft_solver/configs/:ffcraft_solver/configs" --add-data "src/ffcraft_solver/ressources/:ffcraft_solver/ressources" --name ffcraft_solver_gui -y > /dev/null 2>pyinstaller_log.txt
|
||||
|
||||
|
||||
|
||||
.PHONY: clean rust python
|
||||
release: clean rust python
|
||||
mkdir -p releases # Add version as an arg and things
|
||||
@echo "[MAKE] Copying releases in the releases/ directory"
|
||||
zip releases/ffcraft_solver_cli.zip -q -j target/release/ffcraft_solver_cli craft.toml -j target/release/libxiv_craft_solver.so
|
||||
cd python/dist/ && zip -q ../../releases/ffcraft_solver_gui.zip -r ffcraft_solver_gui/
|
||||
|
|
@ -3,11 +3,14 @@ requires = ["maturin>=0.14,<0.15"]
|
|||
build-backend = "maturin"
|
||||
|
||||
[project] # The rust bindings
|
||||
name = "xiv_craft_solver"
|
||||
name = "xiv_csolver_lib"
|
||||
requires-python = ">=3.7"
|
||||
version = "0.0.4"
|
||||
version = "0.1.8"
|
||||
classifiers = [
|
||||
"Programming Language :: Rust",
|
||||
"Programming Language :: Python :: Implementation :: CPython",
|
||||
"Programming Language :: Python :: Implementation :: PyPy",
|
||||
]
|
||||
]
|
||||
|
||||
[tool.maturin]
|
||||
features = ["pyo3/extension-module"]
|
||||
|
|
@ -8,8 +8,8 @@ classifiers =
|
|||
|
||||
[options]
|
||||
packages =
|
||||
ffcraft_solver
|
||||
ffcraft_solver.modules
|
||||
xiv_csolver
|
||||
xiv_csolver.modules
|
||||
install_requires =
|
||||
pyyaml>=6.0
|
||||
python_requires = >=3.9
|
||||
|
|
@ -21,7 +21,7 @@ zip_safe = no
|
|||
[options.packages.find]
|
||||
where =
|
||||
= src
|
||||
= src/ffcraft_solver
|
||||
= src/xiv_csolver
|
||||
|
||||
[options.extras_require]
|
||||
testing =
|
||||
|
|
|
|||
|
|
@ -1,58 +0,0 @@
|
|||
71 INFO: PyInstaller: 5.8.0
|
||||
71 INFO: Python: 3.10.6
|
||||
72 INFO: Platform: Linux-6.1.11-76060111-generic-x86_64-with-glibc2.35
|
||||
72 INFO: wrote /home/dandaedre/Documents/Git/ffcraft_solver/python/ffcraft_solver_gui.spec
|
||||
74 INFO: UPX is available.
|
||||
74 INFO: Extending PYTHONPATH with paths
|
||||
['/home/dandaedre/Documents/Git/ffcraft_solver/python/src']
|
||||
166 INFO: checking Analysis
|
||||
166 INFO: Building Analysis because Analysis-00.toc is non existent
|
||||
166 INFO: Initializing module dependency graph...
|
||||
167 INFO: Caching module graph hooks...
|
||||
176 INFO: Analyzing base_library.zip ...
|
||||
581 INFO: Loading module hook 'hook-heapq.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
625 INFO: Loading module hook 'hook-encodings.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
1292 INFO: Loading module hook 'hook-pickle.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
2161 INFO: Caching module dependency graph...
|
||||
2221 INFO: running Analysis Analysis-00.toc
|
||||
2236 INFO: Analyzing /home/dandaedre/Documents/Git/ffcraft_solver/python/src/ffcraft_solver/__main__.py
|
||||
2508 INFO: Loading module hook 'hook-platform.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
2672 INFO: Loading module hook 'hook-pygments.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
3097 INFO: Loading module hook 'hook-pkg_resources.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
3438 INFO: Loading module hook 'hook-xml.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
3457 INFO: Loading module hook 'hook-sysconfig.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
4100 INFO: Processing module hooks...
|
||||
5030 INFO: Processing pre-safe import module hook win32com from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/_pyinstaller_hooks_contrib/hooks/pre_safe_import_module/hook-win32com.py'.
|
||||
5209 INFO: Loading module hook 'hook-packaging.py' from '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks'...
|
||||
5271 INFO: Looking for ctypes DLLs
|
||||
5276 INFO: Analyzing run-time hooks ...
|
||||
5278 INFO: Including run-time hook '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks/rthooks/pyi_rth_inspect.py'
|
||||
5279 INFO: Including run-time hook '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks/rthooks/pyi_rth_pkgres.py'
|
||||
5281 INFO: Including run-time hook '/home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/hooks/rthooks/pyi_rth_pkgutil.py'
|
||||
5288 INFO: Looking for dynamic libraries
|
||||
5630 INFO: Looking for eggs
|
||||
5630 INFO: Python library not among binary dependencies. Performing additional search...
|
||||
5642 INFO: Using Python library /lib/x86_64-linux-gnu/libpython3.10.so.1.0
|
||||
5644 INFO: Warnings written to /home/dandaedre/Documents/Git/ffcraft_solver/python/build/ffcraft_solver_gui/warn-ffcraft_solver_gui.txt
|
||||
5669 INFO: Graph cross-reference written to /home/dandaedre/Documents/Git/ffcraft_solver/python/build/ffcraft_solver_gui/xref-ffcraft_solver_gui.html
|
||||
5679 INFO: Appending 'datas' from .spec
|
||||
5684 INFO: checking PYZ
|
||||
5684 INFO: Building PYZ because PYZ-00.toc is non existent
|
||||
5684 INFO: Building PYZ (ZlibArchive) /home/dandaedre/Documents/Git/ffcraft_solver/python/build/ffcraft_solver_gui/PYZ-00.pyz
|
||||
6064 INFO: Building PYZ (ZlibArchive) /home/dandaedre/Documents/Git/ffcraft_solver/python/build/ffcraft_solver_gui/PYZ-00.pyz completed successfully.
|
||||
6073 WARNING: Ignoring icon; supported only on Windows and macOS!
|
||||
6073 INFO: checking PKG
|
||||
6073 INFO: Building PKG because PKG-00.toc is non existent
|
||||
6073 INFO: Building PKG (CArchive) ffcraft_solver_gui.pkg
|
||||
6087 INFO: Building PKG (CArchive) ffcraft_solver_gui.pkg completed successfully.
|
||||
6087 INFO: Bootloader /home/dandaedre/Documents/Git/ffcraft_solver/.venv/lib/python3.10/site-packages/PyInstaller/bootloader/Linux-64bit-intel/run
|
||||
6087 INFO: checking EXE
|
||||
6087 INFO: Building EXE because EXE-00.toc is non existent
|
||||
6087 INFO: Building EXE from EXE-00.toc
|
||||
6087 INFO: Copying bootloader EXE to /home/dandaedre/Documents/Git/ffcraft_solver/python/build/ffcraft_solver_gui/ffcraft_solver_gui
|
||||
6088 INFO: Appending PKG archive to custom ELF section in EXE
|
||||
6096 INFO: Building EXE from EXE-00.toc completed successfully.
|
||||
6096 INFO: checking COLLECT
|
||||
6096 INFO: Building COLLECT because COLLECT-00.toc is non existent
|
||||
6096 INFO: Building COLLECT COLLECT-00.toc
|
||||
6236 INFO: Building COLLECT COLLECT-00.toc completed successfully.
|
||||
|
|
@ -3,13 +3,13 @@ requires = ["setuptools>=42.0", "wheel"]
|
|||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project] # The Python GUI
|
||||
name = "ffcraft_solver"
|
||||
name = "xiv_csolver"
|
||||
authors = [
|
||||
{name="Vkyfox"},
|
||||
{name="Dandaedre"},
|
||||
]
|
||||
requires-python = ">=3.7"
|
||||
version = "0.0.4"
|
||||
version = "0.1.8"
|
||||
license = {text="Mozilla Public License Version 2.0"}
|
||||
classifiers = [
|
||||
"Programming Language :: Rust",
|
||||
|
|
@ -18,7 +18,7 @@ classifiers = [
|
|||
]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
addopts = "--cov=ffcraft_solver"
|
||||
addopts = "--cov=xiv_csolver"
|
||||
testpaths = [
|
||||
"tests",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -1,182 +0,0 @@
|
|||
import dearpygui.dearpygui as dpg
|
||||
import xiv_craft_solver as xcs
|
||||
from ffcraft_solver.modules import loader
|
||||
import rich
|
||||
|
||||
dpg.create_context()
|
||||
dpg.configure_app(manual_callback_management=True)
|
||||
dpg.create_viewport(title='XIV Solver', width=500, height=700)
|
||||
|
||||
class User:
|
||||
name = 'NEW'
|
||||
food = ''
|
||||
pot = ''
|
||||
specialist = False
|
||||
initial_craftsmanship = 0
|
||||
initial_control = 0
|
||||
initial_cp = 0
|
||||
craftsmanship = 0
|
||||
control = 0
|
||||
cp = 0
|
||||
|
||||
def refresh_gui(self) -> True:
|
||||
self.compute_stats()
|
||||
dpg.set_value(user_combo, self.name)
|
||||
dpg.set_value(food_combo, self.food)
|
||||
dpg.set_value(pot_combo, self.pot)
|
||||
dpg.set_value(user_effective_stats, [self.craftsmanship, self.control, self.cp])
|
||||
return True
|
||||
|
||||
def compute_stats(self) -> list:
|
||||
food = []
|
||||
try:
|
||||
full_food = full_config.get_foods_dict()[self.food]
|
||||
# [[5, 120], [0, 0], [26, 82]]
|
||||
if user.initial_craftsmanship * full_food[0][0] / 100 > full_food[0][1]:
|
||||
food.append(full_food[0][1])
|
||||
else:
|
||||
food.append(round(user.initial_craftsmanship * full_food[0][0] / 100))
|
||||
if user.initial_control * full_food[1][0] / 100 > full_food[1][1]:
|
||||
food.append(full_food[1][1])
|
||||
else:
|
||||
food.append(round(user.initial_control * full_food[1][0] / 100))
|
||||
if user.initial_cp * full_food[2][0] / 100 > full_food[2][1]:
|
||||
food.append(full_food[2][1])
|
||||
else:
|
||||
food.append(round(user.initial_cp * full_food[2][0] / 100))
|
||||
except KeyError as _:
|
||||
food = [0, 0, 0]
|
||||
pass
|
||||
|
||||
pot = []
|
||||
try:
|
||||
full_pot = full_config.get_pots_dict()[self.pot]
|
||||
# [(0, 0), (0, 0), (6, 21)]
|
||||
if user.initial_craftsmanship * full_pot[0][0] / 100 > full_pot[0][1]:
|
||||
pot.append(full_pot[0][1])
|
||||
else:
|
||||
pot.append(round(user.initial_craftsmanship * full_pot[0][0] / 100))
|
||||
if user.initial_control * full_pot[1][0] / 100 > full_pot[1][1]:
|
||||
pot.append(full_pot[1][1])
|
||||
else:
|
||||
pot.append(round(user.initial_control * full_pot[1][0] / 100))
|
||||
if user.initial_cp * full_pot[2][0] / 100 > full_pot[2][1]:
|
||||
pot.append(full_pot[2][1])
|
||||
else:
|
||||
pot.append(round(user.initial_cp * full_pot[2][0] / 100))
|
||||
except KeyError as _:
|
||||
pot = [0, 0, 0]
|
||||
pass
|
||||
|
||||
if user.specialist:
|
||||
specialist = [20, 20, 15]
|
||||
else:
|
||||
specialist = [0, 0, 0]
|
||||
|
||||
self.craftsmanship = self.initial_craftsmanship + food[0] + pot[0] + specialist[0]
|
||||
self.control = self.initial_control + food[1] + pot[1] + specialist[1]
|
||||
self.cp = self.initial_cp + food[2] + pot[2] + specialist[2]
|
||||
|
||||
def set_initial_stats(self, _, app_data, __) -> list:
|
||||
self.initial_craftsmanship = app_data[0]
|
||||
self.initial_control = app_data[1]
|
||||
self.initial_cp = app_data[2]
|
||||
self.refresh_gui()
|
||||
return [self.initial_craftsmanship, self.initial_control, self.initial_cp]
|
||||
|
||||
def set_specialist(self, _, app_data, __) -> bool:
|
||||
if app_data:
|
||||
self.specialist = True
|
||||
else:
|
||||
self.specialist = False
|
||||
self.refresh_gui()
|
||||
return self.specialist
|
||||
|
||||
def set_food(self, _, app_data, __) -> str:
|
||||
self.food = app_data
|
||||
self.refresh_gui()
|
||||
return self.food
|
||||
|
||||
def set_pot(self, _, app_data, __) -> str:
|
||||
self.pot = app_data
|
||||
self.refresh_gui()
|
||||
return self.food
|
||||
|
||||
|
||||
class Recipe:
|
||||
name = ''
|
||||
quality = 0
|
||||
difficulty = 0
|
||||
durability = 0
|
||||
|
||||
def set_recipe_stats(self, _, app_data, __):
|
||||
self.quality = app_data[0]
|
||||
self.difficulty = app_data[1]
|
||||
self.durability = app_data[2]
|
||||
return self.quality, self.difficulty, self.durability
|
||||
|
||||
def get_recipe_stats(self):
|
||||
return self.quality, self.difficulty, self.durability
|
||||
|
||||
def set_recipe_name(self, _, app_data, __):
|
||||
self.name = app_data
|
||||
self.set_recipe_stats(0, full_config.get_recipes_dict()[self.name], 0)
|
||||
dpg.set_value(recipe_stats, self.get_recipe_stats())
|
||||
return self.name
|
||||
|
||||
|
||||
with dpg.window(label="Settings", width=500, height=700, no_resize=True, no_title_bar=True):
|
||||
user = User()
|
||||
recipe = Recipe()
|
||||
|
||||
full_config = loader.Loader()
|
||||
characters_names = full_config.get_users_names()
|
||||
foods_names = full_config.get_foods_names()
|
||||
pots_names = full_config.get_pots_names()
|
||||
recipe_names = full_config.get_recipes_names()
|
||||
|
||||
dpg.add_text("Character")
|
||||
user_combo = dpg.add_combo(items=characters_names, label="Your character")
|
||||
dpg.set_value(user_combo, "NEW")
|
||||
# TODO: Load 1rst user in users.yaml by default
|
||||
# TODO: Make NEW prompt for a name when saving
|
||||
user_stats = dpg.add_input_intx(size=3, label="Stats", tag="stats_tooltip", callback=user.set_initial_stats)
|
||||
with dpg.tooltip("stats_tooltip"):
|
||||
dpg.add_text("Craftsmanship / Control / CP")
|
||||
dpg.add_button(label="Save!", indent=282)
|
||||
specialist_checkbox = dpg.add_checkbox(label="Specialist", tag="specialist", callback=user.set_specialist)
|
||||
dpg.add_text(" ")
|
||||
user_effective_stats = dpg.add_input_intx(size=3, label="Effective stats", tag="effective_stats_tooltip", readonly=True)
|
||||
with dpg.tooltip("effective_stats_tooltip"):
|
||||
dpg.add_text("Craftsmanship / Control / CP")
|
||||
|
||||
dpg.add_separator()
|
||||
|
||||
dpg.add_text("Consumables")
|
||||
food_combo = dpg.add_combo(items=foods_names, label="Food", callback=user.set_food)
|
||||
pot_combo = dpg.add_combo(items=pots_names, label="Pot", callback=user.set_pot)
|
||||
|
||||
dpg.add_separator()
|
||||
|
||||
dpg.add_text("Recipe")
|
||||
recipe_combo = dpg.add_combo(items=recipe_names, label="Recipe", callback=recipe.set_recipe_name)
|
||||
dpg.set_value(recipe_combo, "NEW")
|
||||
recipe_stats = dpg.add_input_intx(size=3, label="Stats", tag="recipe_tooltip", callback=recipe.set_recipe_stats)
|
||||
with dpg.tooltip("recipe_tooltip"):
|
||||
dpg.add_text("Quality / Difficulty / Durability")
|
||||
# TODO: add a small grey text message if recipe matches a known recipe
|
||||
dpg.add_button(label="Save!", indent=282)
|
||||
|
||||
dpg.add_button(label="Solve!")
|
||||
dpg.add_collapsing_header(label="Result")
|
||||
|
||||
# TODO: add a log space at the bottom
|
||||
|
||||
dpg.setup_dearpygui()
|
||||
dpg.show_viewport()
|
||||
while dpg.is_dearpygui_running():
|
||||
jobs = dpg.get_callback_queue() # retrieves and clears queue
|
||||
dpg.run_callbacks(jobs)
|
||||
dpg.render_dearpygui_frame()
|
||||
dpg.start_dearpygui()
|
||||
dpg.destroy_context()
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
# Name: [Quality, difficulty, durability]
|
||||
Grade 7 Tincture of Strength: [12628, 5060, 70]
|
||||
Grade 5 Strength Alkahest: [6200, 1300, 35]
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
import rich
|
||||
import yaml
|
||||
import os
|
||||
|
||||
class DefaultConfig:
|
||||
yaml_user = 'configs/users.yaml'
|
||||
yaml_consumable = 'configs/consumables.yaml'
|
||||
yaml_recipes = 'configs/recipes.yaml'
|
||||
|
||||
|
||||
|
||||
|
||||
class Loader:
|
||||
# TODO: create folder/file if missing when clicking "save"
|
||||
# TODO: log any missing file(s) or the whole folder
|
||||
def __init__(self):
|
||||
self.user_list = {'NEW': [0, 0, 0]}
|
||||
self.foods_list = {' ': [[0, 0], [0, 0], [0, 0]]}
|
||||
self.pots_list = {' ': [[0, 0], [0, 0], [0, 0]]}
|
||||
self.recipes_list = {'NEW': [0, 0, 0]}
|
||||
self.config = DefaultConfig()
|
||||
|
||||
try:
|
||||
with open(self.relative_import(self.config.yaml_user), 'r') as file:
|
||||
self.user_list.update(yaml.safe_load(file))
|
||||
except FileNotFoundError as e:
|
||||
print(e)
|
||||
try:
|
||||
with open(self.relative_import(self.config.yaml_consumable), 'r') as file:
|
||||
loaded_file = yaml.safe_load(file)
|
||||
self.foods_list.update(loaded_file['Foods'])
|
||||
self.pots_list.update(loaded_file['Pots'])
|
||||
except FileNotFoundError as e:
|
||||
print(e)
|
||||
try:
|
||||
with open(self.relative_import(self.config.yaml_recipes), 'r') as file:
|
||||
self.recipes_list.update(yaml.safe_load(file))
|
||||
except (FileNotFoundError,IsADirectoryError) as e:
|
||||
print(e)
|
||||
|
||||
def relative_import(self, path):
|
||||
return (os.path.normpath(os.path.join(__file__,"../..",path)))
|
||||
|
||||
def get_users_dict(self) -> dict:
|
||||
return self.user_list
|
||||
|
||||
def get_users_names(self) -> list:
|
||||
user_names = []
|
||||
for n in self.user_list:
|
||||
user_names.append(n)
|
||||
return user_names
|
||||
|
||||
def get_foods_dict(self) -> dict:
|
||||
return self.foods_list
|
||||
|
||||
def get_foods_names(self) -> list:
|
||||
foods_names = []
|
||||
for f in self.foods_list:
|
||||
foods_names.append(f)
|
||||
return foods_names
|
||||
|
||||
def get_pots_dict(self) -> dict:
|
||||
return self.pots_list
|
||||
|
||||
def get_pots_names(self) -> list:
|
||||
pots_names = []
|
||||
for p in self.pots_list:
|
||||
pots_names.append(p)
|
||||
return pots_names
|
||||
|
||||
def get_recipes_dict(self) -> dict:
|
||||
return self.recipes_list
|
||||
|
||||
def get_recipes_names(self) -> list:
|
||||
recipes_names = []
|
||||
for r in self.recipes_list:
|
||||
recipes_names.append(r)
|
||||
return recipes_names
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
loader = Loader()
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
"""
|
||||
A rust program for solving FFXIV craft recipe.
|
||||
- ffcraft_solver
|
||||
- xiv_csolver
|
||||
"""
|
||||
|
|
@ -0,0 +1,351 @@
|
|||
import re
|
||||
import dearpygui.dearpygui as dpg
|
||||
from xiv_csolver.modules import loader, log, solver, printer
|
||||
|
||||
|
||||
class User:
|
||||
name = ' '
|
||||
food = ''
|
||||
pot = ''
|
||||
specialist = False
|
||||
initial_craftsmanship = 0
|
||||
initial_control = 0
|
||||
initial_cp = 0
|
||||
craftsmanship = 0
|
||||
control = 0
|
||||
cp = 0
|
||||
|
||||
def refresh_gui(self) -> True:
|
||||
self.compute_stats()
|
||||
dpg.set_value(user_combo, self.name)
|
||||
dpg.set_value(food_combo, self.food)
|
||||
dpg.set_value(pot_combo, self.pot)
|
||||
dpg.set_value(user_effective_stats, [self.craftsmanship, self.control, self.cp])
|
||||
if self.name != ' ':
|
||||
dpg.set_value(save_user_as, self.name)
|
||||
else:
|
||||
dpg.set_value(save_user_as, '')
|
||||
return True
|
||||
|
||||
def compute_stats(self) -> list:
|
||||
food = []
|
||||
try:
|
||||
full_food = full_config.get_foods_dict()[self.food]
|
||||
if user.initial_craftsmanship * full_food[0][0] / 100 > full_food[0][1]:
|
||||
food.append(full_food[0][1])
|
||||
else:
|
||||
food.append(round(user.initial_craftsmanship * full_food[0][0] / 100))
|
||||
if user.initial_control * full_food[1][0] / 100 > full_food[1][1]:
|
||||
food.append(full_food[1][1])
|
||||
else:
|
||||
food.append(round(user.initial_control * full_food[1][0] / 100))
|
||||
if user.initial_cp * full_food[2][0] / 100 > full_food[2][1]:
|
||||
food.append(full_food[2][1])
|
||||
else:
|
||||
food.append(round(user.initial_cp * full_food[2][0] / 100))
|
||||
except KeyError as _:
|
||||
food = [0, 0, 0]
|
||||
pass
|
||||
|
||||
pot = []
|
||||
try:
|
||||
full_pot = full_config.get_pots_dict()[self.pot]
|
||||
if user.initial_craftsmanship * full_pot[0][0] / 100 > full_pot[0][1]:
|
||||
pot.append(full_pot[0][1])
|
||||
else:
|
||||
pot.append(round(user.initial_craftsmanship * full_pot[0][0] / 100))
|
||||
if user.initial_control * full_pot[1][0] / 100 > full_pot[1][1]:
|
||||
pot.append(full_pot[1][1])
|
||||
else:
|
||||
pot.append(round(user.initial_control * full_pot[1][0] / 100))
|
||||
if user.initial_cp * full_pot[2][0] / 100 > full_pot[2][1]:
|
||||
pot.append(full_pot[2][1])
|
||||
else:
|
||||
pot.append(round(user.initial_cp * full_pot[2][0] / 100))
|
||||
except KeyError as _:
|
||||
pot = [0, 0, 0]
|
||||
pass
|
||||
|
||||
if user.specialist:
|
||||
specialist = [20, 20, 15]
|
||||
else:
|
||||
specialist = [0, 0, 0]
|
||||
|
||||
self.craftsmanship = self.initial_craftsmanship + food[0] + pot[0] + specialist[0]
|
||||
self.control = self.initial_control + food[1] + pot[1] + specialist[1]
|
||||
self.cp = self.initial_cp + food[2] + pot[2] + specialist[2]
|
||||
|
||||
return [self.craftsmanship, self.control, self.cp]
|
||||
|
||||
def set_initial_stats(self, _, app_data, __) -> list:
|
||||
self.initial_craftsmanship = app_data[0]
|
||||
self.initial_control = app_data[1]
|
||||
self.initial_cp = app_data[2]
|
||||
self.refresh_gui()
|
||||
return [self.initial_craftsmanship, self.initial_control, self.initial_cp]
|
||||
|
||||
def set_specialist(self, _, app_data, __) -> bool:
|
||||
if app_data:
|
||||
self.specialist = True
|
||||
else:
|
||||
self.specialist = False
|
||||
self.refresh_gui()
|
||||
return self.specialist
|
||||
|
||||
def set_food(self, _, app_data, __) -> str:
|
||||
self.food = app_data
|
||||
self.refresh_gui()
|
||||
return self.food
|
||||
|
||||
def set_pot(self, _, app_data, __) -> str:
|
||||
self.pot = app_data
|
||||
self.refresh_gui()
|
||||
return self.food
|
||||
|
||||
def set_name_combo(self, _, app_data, __) -> str:
|
||||
self.name = app_data
|
||||
self.set_initial_stats(0, full_config.get_users_dict()[self.name], None)
|
||||
dpg.set_value(user_stats, [self.initial_craftsmanship, self.initial_control, self.initial_cp])
|
||||
return self.name
|
||||
|
||||
@staticmethod
|
||||
def save_users() -> True:
|
||||
if dpg.get_value(save_user_as) == '':
|
||||
loggers.add_log('Cannot save user without a name.')
|
||||
elif re.search(r'^\s+$', dpg.get_value(save_user_as)):
|
||||
loggers.add_log('Name cannot be only whitespaces.')
|
||||
elif re.search(r'^\s.+', dpg.get_value(save_user_as)):
|
||||
loggers.add_log('Name cannot start with a whitespace.')
|
||||
elif re.search(r'\s$', dpg.get_value(save_user_as)):
|
||||
loggers.add_log('Name cannot end with a whitespace.')
|
||||
else:
|
||||
saver.save_users(dpg.get_value(save_user_as), dpg.get_value(user_stats))
|
||||
loggers.add_log('User saved!')
|
||||
dpg.configure_item('user_combo', items=full_config.get_users_names())
|
||||
return True
|
||||
|
||||
|
||||
class Recipe:
|
||||
name = ' '
|
||||
progress = 0
|
||||
quality = 0
|
||||
durability = 0
|
||||
quality_difficulty = 0
|
||||
progress_difficulty = 0
|
||||
quality_extra_difficulty = 0
|
||||
progress_extra_difficulty = 0
|
||||
|
||||
def refresh_gui(self):
|
||||
dpg.set_value(basic_recipe_stats, self.get_recipe_stats()[0:3])
|
||||
dpg.set_value(advanced_recipe_stats, self.get_recipe_stats()[3:7])
|
||||
if self.name != ' ':
|
||||
dpg.set_value(save_recipe_as, self.name)
|
||||
else:
|
||||
dpg.set_value(save_recipe_as, '')
|
||||
|
||||
def set_recipe_stats(self, tag, app_data, _) -> list[int, int, int, int, int, int, int]:
|
||||
stats = [0, 0, 0]
|
||||
advanced_stats = [0, 0, 0, 0]
|
||||
|
||||
if tag == 'basic_recipe_stats':
|
||||
stats = app_data
|
||||
advanced_stats = dpg.get_value(advanced_recipe_stats)
|
||||
elif tag == 'advanced_recipe_stats':
|
||||
stats = dpg.get_value(basic_recipe_stats)
|
||||
advanced_stats = app_data
|
||||
elif tag == 0:
|
||||
stats = [app_data[0], app_data[1], app_data[2]]
|
||||
advanced_stats = [app_data[3], app_data[4], app_data[5], app_data[6]]
|
||||
else:
|
||||
loggers.add_log('Something went very wrong in recipe stat assignment.')
|
||||
|
||||
self.progress = stats[0]
|
||||
self.quality = stats[1]
|
||||
self.durability = stats[2]
|
||||
self.progress_difficulty = advanced_stats[0]
|
||||
self.quality_difficulty = advanced_stats[1]
|
||||
self.progress_extra_difficulty = advanced_stats[2]
|
||||
self.quality_extra_difficulty = advanced_stats[3]
|
||||
|
||||
return [self.progress, self.quality, self.durability, self.progress_difficulty, self.quality_difficulty,
|
||||
self.progress_extra_difficulty, self.quality_extra_difficulty]
|
||||
|
||||
def get_recipe_stats(self) -> list[int, int, int, int, int, int, int]:
|
||||
return [self.progress, self.quality, self.durability, self.progress_difficulty, self.quality_difficulty,
|
||||
self.progress_extra_difficulty, self.quality_extra_difficulty]
|
||||
|
||||
def set_recipe_name(self, _, app_data, __):
|
||||
self.name = app_data
|
||||
self.set_recipe_stats(0, full_config.get_recipes_dict()[self.name], 0)
|
||||
self.refresh_gui()
|
||||
return self.name
|
||||
|
||||
def get_recipe_name(self) -> str:
|
||||
return self.name
|
||||
|
||||
@staticmethod
|
||||
def save_recipe() -> True:
|
||||
if dpg.get_value(save_recipe_as) == '':
|
||||
loggers.add_log('Cannot save recipe without a name.')
|
||||
elif re.search(r'^\s+$', dpg.get_value(save_recipe_as)):
|
||||
loggers.add_log('Name cannot be only whitespaces.')
|
||||
elif re.search(r'^\s.+', dpg.get_value(save_recipe_as)):
|
||||
loggers.add_log('Name cannot start with a whitespace.')
|
||||
elif re.search(r'\s$', dpg.get_value(save_recipe_as)):
|
||||
loggers.add_log('Name cannot end with a whitespace.')
|
||||
else:
|
||||
saver.save_recipe(dpg.get_value(save_recipe_as), dpg.get_value(basic_recipe_stats), dpg.get_value(advanced_recipe_stats))
|
||||
loggers.add_log('Recipe saved!')
|
||||
dpg.configure_item('recipe_combo', items=full_config.get_recipes_names())
|
||||
return True
|
||||
|
||||
|
||||
class Solution:
|
||||
def __init__(self, title, logger):
|
||||
self.loggers = logger
|
||||
self.result = None
|
||||
self.title = title
|
||||
|
||||
def print_result(self):
|
||||
if self.result:
|
||||
dpg.set_value(results, self.result)
|
||||
else:
|
||||
self.loggers.add_log('No solution to display.')
|
||||
|
||||
def print_macro_1(self):
|
||||
if self.result and self.result.macro1:
|
||||
dpg.set_value(results, self.result.macro1)
|
||||
else:
|
||||
self.loggers.add_log('No macro to display.')
|
||||
|
||||
def print_macro_2(self):
|
||||
if self.result and self.result.macro2:
|
||||
dpg.set_value(results, self.result.macro2)
|
||||
else:
|
||||
self.loggers.add_log('No macro to display.')
|
||||
|
||||
def print_macro_3(self):
|
||||
if self.result and self.result.macro3:
|
||||
dpg.set_value(results, self.result.macro3)
|
||||
else:
|
||||
self.loggers.add_log('No macro to display.')
|
||||
|
||||
|
||||
def request_solve() -> True:
|
||||
loggers.add_log('Solver initialised. Please stand by.')
|
||||
all_results = solver.Solver(user, recipe, loggers)
|
||||
best_quality.result = all_results.best_quality
|
||||
least_steps.result = all_results.least_steps
|
||||
safe_50.result = all_results.safe_50
|
||||
dpg.set_value(results, best_quality.result)
|
||||
loggers.add_log('Solved!')
|
||||
return True
|
||||
|
||||
|
||||
def refresh_log() -> True:
|
||||
dpg.set_value(log_window, loggers.log)
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
dpg.create_context()
|
||||
dpg.configure_app(manual_callback_management=True)
|
||||
dpg.create_viewport(title='XIV Solver', width=500, height=700, resizable=False)
|
||||
|
||||
with dpg.window(label="Settings", width=500, height=700, no_resize=True, no_title_bar=True, no_move=True, no_collapse=True):
|
||||
# Initialization of all our classes
|
||||
loggers = log.Loggers()
|
||||
|
||||
user = User()
|
||||
recipe = Recipe()
|
||||
best_quality = Solution("Best Quality", loggers)
|
||||
least_steps = Solution("Least Steps", loggers)
|
||||
safe_50 = Solution("Safe Margin", loggers)
|
||||
|
||||
full_config = loader.Loader(loggers)
|
||||
characters_names = full_config.get_users_names()
|
||||
foods_names = full_config.get_foods_names()
|
||||
pots_names = full_config.get_pots_names()
|
||||
recipe_names = full_config.get_recipes_names()
|
||||
|
||||
saver = printer.Printer(full_config)
|
||||
|
||||
# Start of GUI drawing
|
||||
# CHARACTER
|
||||
dpg.add_text("Character")
|
||||
user_combo = dpg.add_combo(tag='user_combo', items=characters_names, label="Your character", callback=user.set_name_combo)
|
||||
dpg.set_value(user_combo, ' ')
|
||||
# TODO: Load 1rst user in users.yaml by default
|
||||
user_stats = dpg.add_input_intx(size=3, label="Stats", tag="stats_tooltip", callback=user.set_initial_stats)
|
||||
with dpg.tooltip("stats_tooltip"):
|
||||
dpg.add_text("Craftsmanship / Control / CP")
|
||||
with dpg.group(horizontal=True):
|
||||
save_user_as = dpg.add_input_text(hint='Save as...')
|
||||
# TODO: make it so field is not cleared at every input in stats
|
||||
dpg.add_button(label="Save!", callback=user.save_users)
|
||||
|
||||
# EFFECTIVE STATS
|
||||
dpg.add_separator()
|
||||
user_effective_stats = dpg.add_input_intx(size=3, label="Effective stats", tag="effective_stats_tooltip", readonly=True)
|
||||
with dpg.tooltip("effective_stats_tooltip"):
|
||||
dpg.add_text("Craftsmanship / Control / CP")
|
||||
dpg.add_separator()
|
||||
|
||||
# MODIFIERS
|
||||
dpg.add_text("Modifiers")
|
||||
food_combo = dpg.add_combo(items=foods_names, label="Food", callback=user.set_food)
|
||||
pot_combo = dpg.add_combo(items=pots_names, label="Pot", callback=user.set_pot)
|
||||
specialist_checkbox = dpg.add_checkbox(label="Specialist", tag="specialist", callback=user.set_specialist)
|
||||
# TODO : possibility to add new food/pots without manually adding them to the config files
|
||||
|
||||
# RECIPE
|
||||
dpg.add_separator()
|
||||
dpg.add_text("Recipe")
|
||||
recipe_combo = dpg.add_combo(items=recipe_names, tag='recipe_combo', label="Recipe", callback=recipe.set_recipe_name)
|
||||
dpg.set_value(recipe_combo, " ")
|
||||
basic_recipe_stats = dpg.add_input_intx(size=3, label="Stats", tag="basic_recipe_stats", callback=recipe.set_recipe_stats)
|
||||
with dpg.tooltip("basic_recipe_stats"):
|
||||
dpg.add_text("Progress / Quality / Durability")
|
||||
advanced_recipe_stats = dpg.add_input_intx(
|
||||
size=4, label="Advanced stats", tag="advanced_recipe_stats", callback=recipe.set_recipe_stats
|
||||
)
|
||||
with dpg.tooltip("advanced_recipe_stats"):
|
||||
dpg.add_text("Progress / Quality difficulty // Progress / Quality extra difficulty")
|
||||
# TODO: add a log if recipe matches a known recipe
|
||||
with dpg.group(horizontal=True):
|
||||
save_recipe_as = dpg.add_input_text(hint='Save as...')
|
||||
dpg.add_button(label="Save!", callback=recipe.save_recipe)
|
||||
# TODO: Can't save if value == ' '
|
||||
|
||||
# SOLVE
|
||||
dpg.add_separator()
|
||||
dpg.add_button(label="Solve!", callback=request_solve)
|
||||
dpg.add_text()
|
||||
dpg.add_collapsing_header(label="Results", leaf=True)
|
||||
# TODO: Add feedback when pressed
|
||||
|
||||
with dpg.group(horizontal=True):
|
||||
results = dpg.add_input_text(multiline=True, height=220, readonly=True)
|
||||
with dpg.child_window(autosize_x=True, height=220):
|
||||
dpg.add_button(label="BEST QUALITY", width=136, callback=best_quality.print_result)
|
||||
dpg.add_button(label="Macro 1", width=136, callback=best_quality.print_macro_1)
|
||||
dpg.add_button(label="Macro 2", width=136, callback=best_quality.print_macro_2)
|
||||
dpg.add_button(label="SAFE MARGIN", width=136, callback=safe_50.print_result)
|
||||
dpg.add_button(label="Macro 1", width=136, callback=safe_50.print_macro_1)
|
||||
dpg.add_button(label="Macro 2", width=136, callback=safe_50.print_macro_2)
|
||||
dpg.add_button(label="QUICKEST", width=136, callback=least_steps.print_result)
|
||||
dpg.add_button(label="Macro 1", width=136, callback=least_steps.print_macro_1)
|
||||
dpg.add_button(label="Macro 2", width=136, callback=least_steps.print_macro_2)
|
||||
|
||||
# LOG
|
||||
log_window = dpg.add_input_text(multiline=True, default_value=loggers.log, height=50, width=500,
|
||||
tab_input=True, pos=[0, 642], tracked=False, readonly=True, tag="log_window")
|
||||
|
||||
dpg.setup_dearpygui()
|
||||
dpg.show_viewport()
|
||||
while dpg.is_dearpygui_running():
|
||||
jobs = dpg.get_callback_queue() # retrieves and clears queue
|
||||
dpg.run_callbacks(jobs)
|
||||
dpg.render_dearpygui_frame()
|
||||
dpg.start_dearpygui()
|
||||
dpg.destroy_context()
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
# Name: [Progress, quality, durability, progress difficulty, quality difficulty, extra progress difficulty, extra quality difficulty]
|
||||
# as can be found on other solver websites, such as https://yyyy.games/crafter/index.html#/simulator and checking custom recipe.
|
||||
# The language option is the second menu to the left from the top-right hand corner.
|
||||
# If this seems super convoluted, and you'd rather it was just the three in-game values, know that me too.
|
||||
# Unfortunately that is how the craft system works in FFXIV.
|
||||
|
||||
Lvl88: [1650, 7000, 40, 128, 112, 100, 100]
|
||||
Patch6.3_precrafts: [3696, 8200, 35, 130, 115, 80, 70]
|
||||
Patch6.3_gear: [5060, 12628, 70, 130, 115, 80, 70]
|
||||
Patch6.3_gatherer: [5720, 12900, 70, 130, 115, 80, 70]
|
||||
Patch6.4_precrafts: [4488, 9090, 35, 130, 115, 80, 70]
|
||||
Patch6.4_gear: [6600, 14040, 70, 130, 115, 80, 70]
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
# Name: [Craftsmanship, control, cp]
|
||||
# You are encouraged to use this either for multiple characters if you have them, or different jobs having
|
||||
# different gear or melds.
|
||||
# The top line will always be selected by default
|
||||
# The top line will always be selected by default
|
||||
|
||||
Vicky Crosia: [4021, 3933, 587]
|
||||
Dandaedre Zadiel: [0, 0, 0]
|
||||
Sekundes Dullahan: [2566, 2443, 522]
|
||||
|
||||
Vicky Crosia: [4021, 3987, 601]
|
||||
Ladisla Kociann: [4021, 3951, 580]
|
||||
|
|
@ -1,13 +1,13 @@
|
|||
import xiv_craft_solver
|
||||
import xiv_csolver_lib
|
||||
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())
|
||||
rich.inspect(xiv_csolver_lib)
|
||||
rich.inspect(xiv_csolver_lib.test_result())
|
||||
rich.inspect(xiv_csolver_lib.test_info())
|
||||
rich.inspect(xiv_csolver_lib.test_final_results())
|
||||
|
||||
|
||||
class feedMeDaddy:
|
||||
class FeedMeDaddy:
|
||||
durability = 70
|
||||
progress = 3900
|
||||
quality = 10920
|
||||
|
|
@ -27,6 +27,6 @@ class feedMeDaddy:
|
|||
verbose = 0
|
||||
|
||||
|
||||
el_daddy=feedMeDaddy()
|
||||
rich.inspect(xiv_craft_solver.solve_from_python(el_daddy))
|
||||
el_daddy = FeedMeDaddy()
|
||||
rich.inspect(xiv_csolver_lib.solve_from_python(el_daddy))
|
||||
|
||||
|
|
@ -0,0 +1,107 @@
|
|||
import rich
|
||||
import yaml
|
||||
import os
|
||||
from xiv_csolver.modules import log
|
||||
|
||||
|
||||
class DefaultConfig:
|
||||
yaml_dir = 'configs/'
|
||||
yaml_user = yaml_dir + 'users.yaml'
|
||||
yaml_consumable = yaml_dir + 'consumables.yaml'
|
||||
yaml_recipes = yaml_dir + 'recipes.yaml'
|
||||
|
||||
|
||||
class Loader:
|
||||
# TODO: create folder/file if missing when clicking "save"
|
||||
# TODO: log any missing file(s) or the whole folder
|
||||
# TODO: find a way to log at initialization
|
||||
# TODO: except ParserError and handle it
|
||||
def __init__(self, loggers: log.Loggers):
|
||||
self.loggers = loggers
|
||||
self.user_list = {' ': [0, 0, 0]}
|
||||
self.foods_list = {' ': [[0, 0], [0, 0], [0, 0]]}
|
||||
self.pots_list = {' ': [[0, 0], [0, 0], [0, 0]]}
|
||||
self.recipes_list = {' ': [0, 0, 0, 0, 0, 0, 0]}
|
||||
self.config = DefaultConfig()
|
||||
|
||||
if not os.path.exists(self.relative_import(self.config.yaml_dir)):
|
||||
os.mkdir(self.relative_import(self.config.yaml_dir))
|
||||
try:
|
||||
with open(self.relative_import(self.config.yaml_user), 'r') as file:
|
||||
loaded_file = yaml.safe_load(file)
|
||||
if loaded_file:
|
||||
self.user_list.update(loaded_file)
|
||||
except FileNotFoundError as e:
|
||||
print(e)
|
||||
# self.loggers.add_log(f'File {self.config.yaml_user} not found.')
|
||||
print(f'File {self.config.yaml_user} not found.')
|
||||
print(f'Creating {self.config.yaml_user}.')
|
||||
with open(self.relative_import(self.config.yaml_user), 'w+') as _:
|
||||
pass
|
||||
|
||||
try:
|
||||
with open(self.relative_import(self.config.yaml_consumable), 'r') as file:
|
||||
if loaded_file:
|
||||
loaded_file = yaml.safe_load(file)
|
||||
self.foods_list.update(loaded_file['Foods'])
|
||||
self.pots_list.update(loaded_file['Pots'])
|
||||
except FileNotFoundError as e:
|
||||
print(e)
|
||||
# self.loggers.add_log(f'File {self.config.yaml_consumable} not found.')
|
||||
print(f'File {self.config.yaml_consumable} not found.')
|
||||
print(f'Creating {self.config.yaml_consumable}.')
|
||||
with open(self.relative_import(self.config.yaml_consumable), 'w+') as _:
|
||||
pass
|
||||
|
||||
try:
|
||||
with open(self.relative_import(self.config.yaml_recipes), 'r') as file:
|
||||
loaded_file = yaml.safe_load(file)
|
||||
if loaded_file:
|
||||
self.recipes_list.update(loaded_file)
|
||||
except (FileNotFoundError, IsADirectoryError) as e:
|
||||
print(e)
|
||||
# self.loggers.add_log(f'File {self.config.yaml_recipes} not found.')
|
||||
print(f'File {self.config.yaml_recipes} not found.')
|
||||
print(f'Creating {self.config.yaml_recipes}.')
|
||||
with open(self.relative_import(self.config.yaml_recipes), 'w+') as _:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def relative_import(path):
|
||||
return os.path.normpath(os.path.join(__file__, "../..", path))
|
||||
|
||||
def get_users_dict(self) -> dict:
|
||||
return self.user_list
|
||||
|
||||
def get_users_names(self) -> list:
|
||||
user_names = []
|
||||
for n in self.user_list:
|
||||
user_names.append(n)
|
||||
return user_names
|
||||
|
||||
def get_foods_dict(self) -> dict:
|
||||
return self.foods_list
|
||||
|
||||
def get_foods_names(self) -> list:
|
||||
foods_names = []
|
||||
for f in self.foods_list:
|
||||
foods_names.append(f)
|
||||
return foods_names
|
||||
|
||||
def get_pots_dict(self) -> dict:
|
||||
return self.pots_list
|
||||
|
||||
def get_pots_names(self) -> list:
|
||||
pots_names = []
|
||||
for p in self.pots_list:
|
||||
pots_names.append(p)
|
||||
return pots_names
|
||||
|
||||
def get_recipes_dict(self) -> dict:
|
||||
return self.recipes_list
|
||||
|
||||
def get_recipes_names(self) -> list:
|
||||
recipes_names = []
|
||||
for r in self.recipes_list:
|
||||
recipes_names.append(r)
|
||||
return recipes_names
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
from datetime import datetime
|
||||
import dearpygui.dearpygui as dpg
|
||||
|
||||
|
||||
class Loggers:
|
||||
def __init__(self):
|
||||
timestamp = self.get_timestamp()
|
||||
self.log = f"{timestamp} Log initialised."
|
||||
|
||||
def add_log(self, other: str) -> str:
|
||||
timestamp = self.get_timestamp()
|
||||
self.log = timestamp + ' ' + other + '\n' + self.log
|
||||
dpg.set_value('log_window', self.log)
|
||||
return self.log
|
||||
|
||||
# noinspection PyMethodMayBeStatic
|
||||
def get_timestamp(self) -> str:
|
||||
now = datetime.now()
|
||||
almost_timestamp = str(now.time())
|
||||
timestamp = almost_timestamp.rsplit('.')
|
||||
return f'[{timestamp[0]}]'
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
loggers = Loggers()
|
||||
print(loggers.log)
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
from xiv_csolver.modules import loader
|
||||
|
||||
|
||||
class Printer:
|
||||
def __init__(self, full_config: loader.Loader):
|
||||
self.full_config = full_config
|
||||
self.help_text_dict = {
|
||||
'users': '''# Name: [Craftsmanship, control, cp]
|
||||
# You are encouraged to use this either for multiple characters if you have them, or different jobs having
|
||||
# different gear or melds.
|
||||
# The top line will always be selected by default
|
||||
''',
|
||||
'foods': '''Foods:
|
||||
# Name: [[Bonus craftsmanship%, max value], [bonus control%, max value], [bonus cp%, max value]]
|
||||
# For example, Calamari Ripieni HQ gives 5% craftsmanship up to a maximum of 120, and 26% CP up to a
|
||||
# maximum of 82, and is hence noted as:
|
||||
# Calamari Ripieni HQ: [[5, 120], [0, 0], [26, 82]]
|
||||
#
|
||||
# Here is your template to copy/paste and fill in:
|
||||
# Name: [[0, 0], [0, 0], [0, 0]]''',
|
||||
'pots': ''' # Same as above:
|
||||
# Name: [[Bonus craftsmanship%, max value], [bonus control%, max value], [bonus cp%, max value]]
|
||||
# For example, Cunning Craftsman's Draught HQ gives 6% CP up to a maximum of 21, and is hence noted as:
|
||||
# Cunning Craftsman's Draught HQ: [[0, 0], [0, 0], [6, 21]]
|
||||
#
|
||||
# Here is your template to copy/paste and fill in:
|
||||
# Name: [[0, 0], [0, 0], [0, 0]]''',
|
||||
'recipe': '''# Name: [Progress, quality, durability, progress difficulty, quality difficulty, extra progress difficulty, extra quality difficulty]
|
||||
# as can be found on other solver websites, such as https://yyyy.games/crafter/index.html#/simulator and checking custom recipe.
|
||||
# The language option is the second menu to the left from the top-right hand corner.
|
||||
# If this seems super convoluted, and you'd rather it was just the three in-game values, know that me too.
|
||||
# Unfortunately that is how the craft system works in FFXIV.'''
|
||||
}
|
||||
|
||||
def save_users(self, user_name: str = None, user_stats: list = None) -> dict:
|
||||
output = self.help_text_dict['users'] + '\r\n\r\n'
|
||||
|
||||
if user_name.title() == '':
|
||||
for user, stats in self.full_config.get_users_dict().items():
|
||||
if user != ' ':
|
||||
output += f'{user}: [{stats[0]}, {stats[1]}, {stats[2]}]\r\n'
|
||||
|
||||
else:
|
||||
self.full_config.get_users_dict()[user_name] = user_stats
|
||||
for user, stats in self.full_config.get_users_dict().items():
|
||||
if user != ' ':
|
||||
output += f'{user}: [{stats[0]}, {stats[1]}, {stats[2]}]\r\n'
|
||||
|
||||
self.print_users(output)
|
||||
return self.full_config.get_users_dict()
|
||||
|
||||
def print_users(self, output: str) -> True:
|
||||
with open(self.full_config.relative_import(self.full_config.config.yaml_user), 'w') as file:
|
||||
file.write(output)
|
||||
return True
|
||||
|
||||
def save_recipe(self, recipe_name: str = None, recipe_basic_stats: list = None, recipe_advanced_stats: list = None) -> dict:
|
||||
output = self.help_text_dict['recipe'] + '\r\n\r\n'
|
||||
|
||||
if recipe_name.title() == '':
|
||||
for recipe, stats in self.full_config.get_recipes_dict().items():
|
||||
if recipe != ' ':
|
||||
output += f'{recipe}: [{stats[0]}, {stats[1]}, {stats[2]}, {stats[3]}, {stats[4]}, {stats[5]}, {stats[6]}]\r\n'
|
||||
|
||||
else:
|
||||
self.full_config.get_recipes_dict()[recipe_name] = recipe_basic_stats[:-1] + recipe_advanced_stats
|
||||
for recipe, stats in self.full_config.get_recipes_dict().items():
|
||||
if recipe != ' ':
|
||||
output += f'{recipe}: [{stats[0]}, {stats[1]}, {stats[2]}, {stats[3]}, {stats[4]}, {stats[5]}, {stats[6]}]\r\n'
|
||||
|
||||
self.print_recipe(output)
|
||||
return self.full_config.get_recipes_dict()
|
||||
|
||||
def print_recipe(self, output) -> True:
|
||||
with open(self.full_config.relative_import(self.full_config.config.yaml_recipes), 'w') as file:
|
||||
file.write(output)
|
||||
return True
|
||||
|
|
@ -0,0 +1,173 @@
|
|||
import rich
|
||||
import xiv_csolver_lib as xcs
|
||||
from xiv_csolver.__main__ import User, Recipe
|
||||
from xiv_csolver.modules import log, translator
|
||||
|
||||
|
||||
class Result:
|
||||
def __init__(self, result, title: str):
|
||||
self.title = title
|
||||
self.original = result
|
||||
self.quality = result.quality
|
||||
self.actions = result.actions
|
||||
self.steps = result.steps
|
||||
self.remaining_cp = result.cp
|
||||
|
||||
self.all_buffs_list = ['manipulation', 'veneration', 'mastersMend', 'wasteNot', 'wasteNot2', 'greatStrides',
|
||||
'innovation', 'finalAppraisal', 'carefulObservation', 'heartAndSoul']
|
||||
|
||||
self.readable_actions = self.text_wrap(self.actions)
|
||||
|
||||
self.macro1 = ''
|
||||
self.macro2 = ''
|
||||
self.macro3 = ''
|
||||
self.make_macro()
|
||||
|
||||
self.readable = f"""/// {self.title}
|
||||
Rotation:
|
||||
{self.readable_actions}
|
||||
Quality: {self.quality}
|
||||
Steps: {self.steps}
|
||||
Remaining CP: {self.remaining_cp}"""
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.readable
|
||||
|
||||
@staticmethod # il est con ou quoi?
|
||||
def text_wrap(text: list[str]) -> str:
|
||||
"""Transforms a list of words into a string and wraps them at 34 characters with an indent."""
|
||||
line = ' '
|
||||
saved_lines = []
|
||||
justified_text = ''
|
||||
for w in text:
|
||||
if len(line) < 31:
|
||||
line += w + ' '
|
||||
else:
|
||||
saved_lines.append(line)
|
||||
line = ' ' + w + ' '
|
||||
|
||||
if line != saved_lines[-1]:
|
||||
saved_lines.append(line)
|
||||
|
||||
for line in saved_lines:
|
||||
justified_text += line + '\r\n'
|
||||
|
||||
return justified_text[:-1]
|
||||
|
||||
def make_macro(self) -> True:
|
||||
saved_lines = ['']
|
||||
translated_actions = translator.translate_list(self.actions, "en")
|
||||
count = 0
|
||||
|
||||
for action in translated_actions:
|
||||
line = f'/ac "{action}" <wait.{"2" if self.actions[count] in self.all_buffs_list else "3"}>'
|
||||
saved_lines.append(line)
|
||||
count += 1
|
||||
saved_lines = saved_lines[1:]
|
||||
|
||||
if self.steps != 15 and self.steps != 29 and self.steps != 44:
|
||||
saved_lines.append('/echo Craft complete ! <se.3>')
|
||||
# else:
|
||||
# TODO: Add a callback to the parent object for logging
|
||||
# self.loggers.add_log(f'No completion message in macro because rotation is exactly {self.steps} steps.')
|
||||
|
||||
if self.steps > 15:
|
||||
saved_lines.insert(14, '/echo Macro 1 complete <se.2>')
|
||||
|
||||
if self.steps > 30:
|
||||
saved_lines.insert(30, '/echo Macro 2 complete <se.2>')
|
||||
# TODO : test index
|
||||
|
||||
count = 0
|
||||
for line in saved_lines:
|
||||
count += 1
|
||||
if count < 16:
|
||||
self.macro1 += line + '\r\n'
|
||||
elif 15 < count < 31:
|
||||
self.macro2 += line + '\r\n'
|
||||
elif 30 < count < 46:
|
||||
self.macro3 += line + '\r\n'
|
||||
|
||||
self.macro1 = self.macro1[:-1]
|
||||
self.macro2 = self.macro2[:-1]
|
||||
self.macro3 = self.macro3[:-1]
|
||||
return True
|
||||
|
||||
|
||||
class Solver:
|
||||
def __init__(self, user: User, recipe: Recipe, loggers: log.Loggers):
|
||||
self.durability = recipe.durability
|
||||
self.progress = recipe.progress
|
||||
self.quality = recipe.quality
|
||||
self.progress_divider = recipe.progress_difficulty
|
||||
self.quality_divider = recipe.quality_difficulty
|
||||
self.progress_modifier = recipe.progress_extra_difficulty
|
||||
self.quality_modifier = recipe.quality_extra_difficulty
|
||||
|
||||
self.craftsmanship = user.craftsmanship
|
||||
self.control = user.control
|
||||
self.max_cp = user.cp
|
||||
|
||||
self.depth = 10
|
||||
self.byregot_step = 10
|
||||
self.desperate = False
|
||||
self.threads = 8
|
||||
self.verbose = 0
|
||||
|
||||
self.loggers = loggers
|
||||
|
||||
self.solutions = []
|
||||
self.info = None
|
||||
self.best_quality = None
|
||||
self.least_steps = None
|
||||
self.safe_50 = None
|
||||
|
||||
self.solve()
|
||||
self.compute_all()
|
||||
|
||||
def solve(self) -> str:
|
||||
self.solutions,self.info = xcs.solve_from_python(self)
|
||||
return self.solutions
|
||||
|
||||
def compute_all(self) -> True:
|
||||
if self.solutions:
|
||||
self.sort_quality()
|
||||
self.compute_best_quality()
|
||||
self.compute_least_steps()
|
||||
self.compute_50percent_quality()
|
||||
|
||||
def sort_quality(self) -> True:
|
||||
self.solutions.sort(key=lambda x: x.quality)
|
||||
return True
|
||||
|
||||
def compute_best_quality(self) -> Result:
|
||||
self.best_quality = Result(self.solutions[-1], 'Best quality')
|
||||
return self.best_quality
|
||||
|
||||
def compute_50percent_quality(self) -> Result:
|
||||
done = False
|
||||
threshold = self.quality * 1.5
|
||||
for s in reversed(self.solutions):
|
||||
if s.quality > threshold:
|
||||
self.safe_50 = Result(s, 'Safe 50')
|
||||
done = True
|
||||
else:
|
||||
break
|
||||
|
||||
if not done:
|
||||
self.loggers.add_log('Could not find a rotation for a 50% Safe Margin.\r\n'
|
||||
' Defaulting to Best Quality.')
|
||||
self.safe_50 = self.best_quality
|
||||
|
||||
return self.safe_50
|
||||
|
||||
def compute_least_steps(self) -> Result:
|
||||
least_steps = 100
|
||||
output = None
|
||||
for e in self.solutions:
|
||||
if e.steps < least_steps:
|
||||
least_steps = e.steps
|
||||
output = e
|
||||
self.least_steps = Result(output, 'Least steps')
|
||||
|
||||
return self.least_steps
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
from xiv_csolver.modules import log
|
||||
|
||||
loggers = log.Loggers
|
||||
|
||||
supported_languages = {
|
||||
"en": {
|
||||
'basicSynth': 'Basic Synthesis',
|
||||
'basicSynth2': 'Basic Synthesis',
|
||||
'basicTouch': 'Basic Touch',
|
||||
'observe': 'Observe',
|
||||
'mastersMend': "Master's mend",
|
||||
'hastyTouch': 'Hasty Touch',
|
||||
'rapidSynthesis': 'Rapid Synthesis',
|
||||
'wasteNot': 'Waste Not',
|
||||
'veneration': 'Veneration',
|
||||
'standardTouch': 'Standard Touch',
|
||||
'greatStrides': 'Great Strides',
|
||||
'innovation': 'Innovation',
|
||||
'finalAppraisal': 'Final Appraisal',
|
||||
'wasteNot2': 'Waste Not II',
|
||||
'byregotsBlessing': "Byregot's Blessing",
|
||||
'preciseTouch': 'Precise Touch',
|
||||
'muscleMemory': 'Muscle Memory',
|
||||
'carefulSynthesis': 'Careful Synthesis',
|
||||
'manipulation': 'Manipulation',
|
||||
'prudentTouch': 'Prudent Touch',
|
||||
'focusedSynthesis': 'Focused Synthesis',
|
||||
'focusedTouch': 'Focused Touch',
|
||||
'reflect': 'Reflect',
|
||||
'preparatoryTouch': 'Preparatory Touch',
|
||||
'groundwork': 'Groundwork',
|
||||
'delicateSynthesis': 'Delicate Synthesis',
|
||||
'intensiveSynthesis': 'Intensive Synthesis',
|
||||
'trainedEye': 'Trained Eye',
|
||||
'advancedTouch': 'Advanced Touch',
|
||||
'prudentSynthesis': 'Prudent Synthesis',
|
||||
'trainedFinesse': 'Trained Finesse'
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def translate_list(actions: list, lang: str):
|
||||
output = []
|
||||
if lang in supported_languages:
|
||||
dictionary = supported_languages[lang]
|
||||
for action in actions:
|
||||
try:
|
||||
output.append(dictionary[action])
|
||||
except KeyError:
|
||||
output.append(supported_languages["en"][action])
|
||||
loggers.log('Translation not found. Defaulting to English.\r\n'
|
||||
' Macros will probably be broken because of this.')
|
||||
|
||||
else:
|
||||
loggers.add_log(f'Language code "{lang}" not recognised.')
|
||||
|
||||
return output
|
||||
|
||||
|
Before Width: | Height: | Size: 248 KiB After Width: | Height: | Size: 248 KiB |
|
Before Width: | Height: | Size: 352 KiB After Width: | Height: | Size: 352 KiB |
|
|
@ -1,29 +0,0 @@
|
|||
[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
|
||||
|
|
@ -0,0 +1 @@
|
|||
reorder_imports = true
|
||||
399
src/action.rs
|
|
@ -1,33 +1,68 @@
|
|||
#[allow(dead_code)]
|
||||
//! Module containing all actions that a crafter can execute
|
||||
//!
|
||||
//! All actions are defined as Action, containing all methods to actively use it in a craft
|
||||
//! while ActionBuilder is used only initally as a lazy_static setup
|
||||
|
||||
use std::fmt::Debug;
|
||||
use lazy_static::lazy_static;
|
||||
use crate::craft::Craft;
|
||||
use crate::specs::{Buff, Success};
|
||||
use lazy_static::lazy_static;
|
||||
use std::fmt::Debug;
|
||||
|
||||
/// Hold an action for the solver to try using
|
||||
///
|
||||
/// It will be used heavily to try/discard actions durin craft
|
||||
pub struct Action {
|
||||
/// The action name, in a human readable format, it will be used to generate a short_name
|
||||
pub name: String,
|
||||
/// The natural durability cost, without buff or reductions
|
||||
pub dur: u32,
|
||||
/// The cost in cp
|
||||
pub cp: u32,
|
||||
/// The amount of progression provided in percent (not the actual value added to the craft)
|
||||
pub progress: u32,
|
||||
/// The amount of quality provided in percent (not the acual value added to the craft)
|
||||
pub quality: u32,
|
||||
/// The name of the buff given, if any
|
||||
pub buff: Option<(Buff, u8)>,
|
||||
/// The short name of the action, as used by most crafting simulator (aka: stripped of whitespace)
|
||||
pub short_name: String,
|
||||
}
|
||||
|
||||
/// Builds an action based on an action
|
||||
///
|
||||
/// Made to initialize lazy_static and nothing more
|
||||
pub struct ActionBuilder {
|
||||
action: Action,
|
||||
}
|
||||
|
||||
impl ActionBuilder {
|
||||
/// Base creator, takes a name and initialize an empty action with the short_name
|
||||
/// and name setup and default values for all other fields
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use xiv_csolver_lib::action::ActionBuilder;
|
||||
/// use xiv_csolver_lib::specs::Buff;
|
||||
/// ActionBuilder::new("Muscle Memory")
|
||||
/// .cp(6)
|
||||
/// .progress(300)
|
||||
/// .buff(Some((Buff::MuscleMemory, 5)))
|
||||
/// .build();
|
||||
/// ```
|
||||
pub fn new(name: &str) -> Self {
|
||||
let mut short_name = name.to_string();
|
||||
short_name = short_name.replace("II", "2");
|
||||
short_name.retain(|c| !c.is_whitespace() && c != '\'');
|
||||
short_name[0..1].make_ascii_lowercase();
|
||||
if name == "Basic Synthesis" { short_name = "basicSynth".to_string(); }
|
||||
if name == "Groundwork" { short_name = "groundwork".to_string(); }
|
||||
if name == "Careful Synthesis" { short_name = "carefulSynthesis".to_string(); }
|
||||
if name == "Basic Synthesis" {
|
||||
short_name = "basicSynth2".to_string();
|
||||
}
|
||||
if name == "Groundwork" {
|
||||
short_name = "groundwork".to_string();
|
||||
}
|
||||
if name == "Careful Synthesis" {
|
||||
short_name = "carefulSynthesis".to_string();
|
||||
}
|
||||
|
||||
Self {
|
||||
action: Action {
|
||||
|
|
@ -38,51 +73,82 @@ impl ActionBuilder {
|
|||
quality: 0,
|
||||
buff: None,
|
||||
short_name,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
/// Changes the durability consumption of an action
|
||||
pub fn dur(mut self, dur: u32) -> Self {
|
||||
self.action.dur = dur;
|
||||
self
|
||||
}
|
||||
|
||||
/// Changes the crafting points (cp) consumption of an action
|
||||
pub fn cp(mut self, cp: u32) -> Self {
|
||||
self.action.cp = cp;
|
||||
self
|
||||
}
|
||||
/// Changes the amount of progress of an action
|
||||
pub fn progress(mut self, progress: u32) -> Self {
|
||||
self.action.progress = progress;
|
||||
self
|
||||
}
|
||||
/// Changes the amount of quality of an action
|
||||
pub fn quality(mut self, quality: u32) -> Self {
|
||||
self.action.quality = quality;
|
||||
self
|
||||
}
|
||||
/// Makes an action add a buff for certain number of actions
|
||||
/// The buffs available are defined in [specs.rs](crate::specs::Buff)
|
||||
///
|
||||
/// ``
|
||||
/// (self.recipe.progress as f32 - self.progression as f32) / self.get_base_progression() as f32;
|
||||
/// ``
|
||||
pub fn buff(mut self, buff: Option<(Buff, u8)>) -> Self {
|
||||
self.action.buff = buff;
|
||||
self
|
||||
}
|
||||
/// Finalize the usage of the ActionBuilder and return the action
|
||||
/// Once again, all this is for the usage of lazy_static
|
||||
pub fn build(self) -> Action {
|
||||
self.action
|
||||
}
|
||||
}
|
||||
|
||||
/// Custom implementation of the equality operator, it is used to compare actions during the
|
||||
/// the crafting process
|
||||
impl PartialEq for Action {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.cp == other.cp && self.dur == other.dur && self.progress == other.progress && self.quality == other.quality
|
||||
self.cp == other.cp
|
||||
&& self.dur == other.dur
|
||||
&& self.progress == other.progress
|
||||
&& self.quality == other.quality
|
||||
}
|
||||
}
|
||||
|
||||
/// A craft action, after compilation (with lazy_static)
|
||||
// no other actions should be created
|
||||
impl Action {
|
||||
/// Get the printable name of the action
|
||||
pub fn get_name(&self) -> String {
|
||||
self.name.clone()
|
||||
}
|
||||
/// Get the CP cost, reduced by the eventual chain buffs currently active in the craft
|
||||
pub fn get_cp_cost(&self, _craft: &Craft) -> u32 {
|
||||
if self == &ACTIONS.standard_touch && _craft.buffs.basic_touch > 0 { return 18; };
|
||||
if self == &ACTIONS.advanced_touch && _craft.buffs.standard_touch > 0 { return 18; };
|
||||
if self == &ACTIONS.standard_touch && _craft.buffs.basic_touch > 0 {
|
||||
return 18;
|
||||
};
|
||||
if self == &ACTIONS.advanced_touch && _craft.buffs.standard_touch > 0 {
|
||||
return 18;
|
||||
};
|
||||
self.cp
|
||||
}
|
||||
pub fn get_durability_cost(&self, _craft: &Craft) -> u32 {
|
||||
if self == &ACTIONS.masters_mend { return 30; }
|
||||
/// Get the durability cost this action would have if used at this stage of the craft
|
||||
/// This method accounts for the effects of **master mend** and **waste not**.
|
||||
/// Note that not using i32 for durability from scratch is a desing choice
|
||||
pub fn get_durability_cost(&self, _craft: &Craft) -> i32 {
|
||||
if self == &ACTIONS.masters_mend {
|
||||
return -30;
|
||||
}
|
||||
if self.dur == 0 || self.progress == 0 && self.quality == 0 {
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -93,8 +159,16 @@ impl Action {
|
|||
if dur < 5 {
|
||||
dur = 5;
|
||||
}
|
||||
dur
|
||||
dur as i32
|
||||
}
|
||||
/// Get the progress effect this action would have if used at this stage of the craft
|
||||
/// This method accounts for the effects of **groundwork** under 20 durability,
|
||||
/// and the effects of **veneration** and **muscle memory**
|
||||
/// # Exemple
|
||||
/// ```md
|
||||
/// - Groundwork will return 200 if the durability remaining is above 20
|
||||
/// - Basic Synthesis will return 100 if no buffs are up and 150 with veneration
|
||||
/// ```
|
||||
pub fn get_progress(&self, _craft: &Craft) -> u32 {
|
||||
let mut prog = self.progress as f64;
|
||||
if self.dur == 20 && _craft.durability < self.get_durability_cost(_craft) as i32 {
|
||||
|
|
@ -109,6 +183,9 @@ impl Action {
|
|||
}
|
||||
(prog * mult).floor() as u32
|
||||
}
|
||||
|
||||
/// Get the quality effect this action would have if used at this stage of the craft.
|
||||
/// This method account for the **inner quiet** stacking effect, **innovation** and **great strides**
|
||||
pub fn get_quality(&self, _craft: &Craft) -> u32 {
|
||||
let mut qual = self.quality as f64;
|
||||
if self == &ACTIONS.byregot_blessing {
|
||||
|
|
@ -127,9 +204,19 @@ impl Action {
|
|||
let iq_mult = (_craft.buffs.inner_quiet as f64 * 0.1) + 1.0;
|
||||
(qual * mult * iq_mult).floor() as u32
|
||||
}
|
||||
/// Returns the Buff (if any) up at this time of the craft
|
||||
pub fn get_buff(&self) -> Option<(Buff, u8)> {
|
||||
self.buff
|
||||
}
|
||||
/// Returns a bool representing if this action **can** be used, note that this does only account
|
||||
/// for the game limitations and not viability limitation
|
||||
///
|
||||
/// # Improvements
|
||||
/// This function could easily prune useless actions by considering them not available.
|
||||
/// Doing so could stop early refresh of buffs and spam of observe and such.
|
||||
/// However some of such "optimisations" could just plain hurt the craft by forbidding a *seemingly*
|
||||
/// useless action. The "bruteforce" method being easily computatble on a modern computer, such
|
||||
/// optimisations arent warrented and left to aother time.
|
||||
pub fn can_use(&self, _craft: &Craft) -> bool {
|
||||
if self.get_cp_cost(_craft) > _craft.cp as u32 {
|
||||
return false;
|
||||
|
|
@ -156,61 +243,207 @@ impl Debug for Action {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
/// The callable actionlist, to be used in conjunction with lazy_static
|
||||
pub struct ActionList {
|
||||
/// Increases progress.
|
||||
/// Efficiency: 300%
|
||||
/// Success Rate: 100%
|
||||
/// Additional Effect: Efficiency of your next Synthesis action is increased by 100%
|
||||
/// Available only on the first step.
|
||||
/// Additional effect is active for five steps.
|
||||
pub muscle_memory: Action,
|
||||
/// Increases quality.
|
||||
/// Efficiency: 100%
|
||||
/// Success Rate: 100%
|
||||
/// Additional Effect: Increases Inner Quiet stack by one (up to 10)
|
||||
/// Availabe only on the first step.
|
||||
pub reflect: Action,
|
||||
/// Increases progress.
|
||||
/// Efficiency: 120%
|
||||
/// Success Rate: 100%
|
||||
pub basic_synthesis: Action,
|
||||
/// Increases progress.
|
||||
/// Efficiency: 120%
|
||||
/// Success Rate: 100%
|
||||
pub careful_synthesis: Action,
|
||||
/// Increases progress at greater cost to durability.
|
||||
/// Efficiency decreases by half when durability is below durability cost.
|
||||
/// Efficiency: 300%
|
||||
/// Success Rate: 100%
|
||||
/// Durability Cost: 20
|
||||
pub groundwork: Action,
|
||||
/// Increases progress at half the durability cost.
|
||||
/// Efficiency: 180%
|
||||
/// Success Rate: 100%
|
||||
/// Unavailable when Waste Not or Waste Not II is active.
|
||||
pub prudent_synthesis: Action,
|
||||
/// Increases both progress and quality.
|
||||
/// Efficiency: 100%
|
||||
/// Success Rate: 100%
|
||||
pub delicate_synthesis: Action,
|
||||
/// Increases quality.
|
||||
/// Efficiency: 100%
|
||||
/// Success Rate: 100%
|
||||
pub basic_touch: Action,
|
||||
/// Increases quality.
|
||||
/// Efficiency: 125%
|
||||
/// Success Rate: 100%
|
||||
/// Combo action: Basic Touch
|
||||
/// Combo bonus: CP cost reduced to 18
|
||||
pub standard_touch: Action,
|
||||
/// Increases quality. Inner Quiet effect ends upon use.
|
||||
/// Efficiency: 100% plus 20% for each count of your Inner Quiet stack, up to a maximum of 300%
|
||||
/// Success Rate: 100%
|
||||
/// Requires at least one stack of Inner Quiet.
|
||||
pub byregot_blessing: Action,
|
||||
/// Increases quality at half the durability cost.
|
||||
/// Efficiency: 100%
|
||||
/// Success Rate: 100%
|
||||
/// Unavailable when Waste Not or Waste Not II are active.
|
||||
pub prudent_touch: Action,
|
||||
/// Increases quality at a greater cost to durability.
|
||||
/// Additional Effect: Increases Inner Quiet stack by one (up to 11)
|
||||
/// Efficiency: 200%
|
||||
/// Success Rate: 100%
|
||||
/// Durability Cost: 20
|
||||
pub preparatory_touch: Action,
|
||||
/// Increases quality.
|
||||
/// Efficiency: 150%
|
||||
/// Success Rate: 100%
|
||||
/// Combo action: Standard Touch
|
||||
/// Combo bonus: CP cost reduced to 18
|
||||
pub advanced_touch: Action,
|
||||
/// Increases quality at no cost to durability.
|
||||
/// Efficiency: 100%
|
||||
/// Success Rate: 100%
|
||||
/// Available only when Inner Quiet stack size is 10.
|
||||
pub trained_finesse: Action,
|
||||
/// Restores item durability by 30.
|
||||
pub masters_mend: Action,
|
||||
|
||||
// Restores item durability by 60.
|
||||
// pub masters_mend_2: Action,
|
||||
/// Reduces loss of durability by 50% for the next four steps.
|
||||
pub waste_not: Action,
|
||||
/// Reduces loss of durability by 50% for the next eight steps.
|
||||
pub waste_not_ii: Action,
|
||||
/// Restores 5 points of durability after each step for the next eight steps.
|
||||
pub manipulation: Action,
|
||||
/// Increases efficiency of Synthesis actions by 50% for the next four steps.
|
||||
pub veneration: Action,
|
||||
/// Increases the efficiency of next Touch action by 100%.
|
||||
/// Effect active for three steps.
|
||||
pub great_strides: Action,
|
||||
/// Increases efficiency of Touch actions by 50% for the next four steps.
|
||||
pub innovation: Action,
|
||||
// Do nothing for one step.
|
||||
//pub observe: Action,
|
||||
// Increases progress.
|
||||
// Efficiency: 200%
|
||||
// Success Rate: 50%
|
||||
// Combo Action: Observe
|
||||
// Combo Bonus: Increases success rate to 100%
|
||||
//pub focused_synthesis: Action,
|
||||
}
|
||||
|
||||
/// Create all base actions as a default (for lazy_static)
|
||||
impl Default for ActionList {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
muscle_memory: ActionBuilder::new("Muscle Memory").cp(6).progress(300).buff(Some((Buff::MuscleMemory, 5))).build(),
|
||||
reflect: ActionBuilder::new("Reflect").cp(6).quality(100).buff(Some((Buff::InnerQuiet, 1))).build(),
|
||||
muscle_memory: ActionBuilder::new("Muscle Memory")
|
||||
.cp(6)
|
||||
.progress(300)
|
||||
.buff(Some((Buff::MuscleMemory, 5)))
|
||||
.build(),
|
||||
reflect: ActionBuilder::new("Reflect")
|
||||
.cp(6)
|
||||
.quality(100)
|
||||
.buff(Some((Buff::InnerQuiet, 1)))
|
||||
.build(),
|
||||
|
||||
basic_synthesis: ActionBuilder::new("Basic Synthesis").progress(120).build(),
|
||||
careful_synthesis: ActionBuilder::new("Careful Synthesis").cp(7).progress(180).build(),
|
||||
groundwork: ActionBuilder::new("Groundwork").cp(18).dur(20).progress(360).build(),
|
||||
prudent_synthesis: ActionBuilder::new("Prudent Synthesis").cp(18).dur(5).progress(180).build(),
|
||||
delicate_synthesis: ActionBuilder::new("Delicate Synthesis").cp(32).progress(100).quality(100).build(),
|
||||
careful_synthesis: ActionBuilder::new("Careful Synthesis")
|
||||
.cp(7)
|
||||
.progress(180)
|
||||
.build(),
|
||||
groundwork: ActionBuilder::new("Groundwork")
|
||||
.cp(18)
|
||||
.dur(20)
|
||||
.progress(360)
|
||||
.build(),
|
||||
prudent_synthesis: ActionBuilder::new("Prudent Synthesis")
|
||||
.cp(18)
|
||||
.dur(5)
|
||||
.progress(180)
|
||||
.build(),
|
||||
delicate_synthesis: ActionBuilder::new("Delicate Synthesis")
|
||||
.cp(32)
|
||||
.progress(100)
|
||||
.quality(100)
|
||||
.build(),
|
||||
|
||||
basic_touch: ActionBuilder::new("Basic Touch").cp(18).quality(100).buff(Some((Buff::BasicTouch, 1))).build(),
|
||||
standard_touch: ActionBuilder::new("Standard Touch").quality(125).cp(32).buff(Some((Buff::StandardTouch, 1))).build(),
|
||||
byregot_blessing: ActionBuilder::new("Byregot's Blessing").cp(24).quality(100).buff(Some((Buff::InnerQuiet, 0))).build(),
|
||||
prudent_touch: ActionBuilder::new("Prudent Touch").cp(25).dur(5).quality(100).build(),
|
||||
preparatory_touch: ActionBuilder::new("Preparatory Touch").cp(40).dur(20).quality(200).buff(Some((Buff::InnerQuiet, 1))).build(),
|
||||
advanced_touch: ActionBuilder::new("Advanced Touch").quality(150).cp(46).build(),
|
||||
trained_finesse: ActionBuilder::new("Trained Finesse").cp(32).quality(100).dur(0).build(),
|
||||
basic_touch: ActionBuilder::new("Basic Touch")
|
||||
.cp(18)
|
||||
.quality(100)
|
||||
.buff(Some((Buff::BasicTouch, 1)))
|
||||
.build(),
|
||||
standard_touch: ActionBuilder::new("Standard Touch")
|
||||
.quality(125)
|
||||
.cp(32)
|
||||
.buff(Some((Buff::StandardTouch, 1)))
|
||||
.build(),
|
||||
byregot_blessing: ActionBuilder::new("Byregot's Blessing")
|
||||
.cp(24)
|
||||
.quality(100)
|
||||
.buff(Some((Buff::InnerQuiet, 0)))
|
||||
.build(),
|
||||
prudent_touch: ActionBuilder::new("Prudent Touch")
|
||||
.cp(25)
|
||||
.dur(5)
|
||||
.quality(100)
|
||||
.build(),
|
||||
preparatory_touch: ActionBuilder::new("Preparatory Touch")
|
||||
.cp(40)
|
||||
.dur(20)
|
||||
.quality(200)
|
||||
.buff(Some((Buff::InnerQuiet, 1)))
|
||||
.build(),
|
||||
advanced_touch: ActionBuilder::new("Advanced Touch")
|
||||
.quality(150)
|
||||
.cp(46)
|
||||
.build(),
|
||||
trained_finesse: ActionBuilder::new("Trained Finesse")
|
||||
.cp(32)
|
||||
.quality(100)
|
||||
.dur(0)
|
||||
.build(),
|
||||
|
||||
masters_mend: ActionBuilder::new("Master's Mend").cp(88).build(),
|
||||
waste_not: ActionBuilder::new("Waste Not").cp(56).buff(Some((Buff::WasteNot, 4))).build(),
|
||||
waste_not_ii: ActionBuilder::new("Waste Not II").cp(98).buff(Some((Buff::WasteNot, 8))).build(),
|
||||
manipulation: ActionBuilder::new("Manipulation").cp(96).buff(Some((Buff::Manipulation, 8))).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(),
|
||||
innovation: ActionBuilder::new("Innovation").cp(18).buff(Some((Buff::Innovation, 4))).build(),
|
||||
|
||||
//masters_mend: ActionBuilder::new("Master's Mend").dur(-30).cp(88).build(),
|
||||
waste_not: ActionBuilder::new("Waste Not")
|
||||
.cp(56)
|
||||
.buff(Some((Buff::WasteNot, 4)))
|
||||
.build(),
|
||||
waste_not_ii: ActionBuilder::new("Waste Not II")
|
||||
.cp(98)
|
||||
.buff(Some((Buff::WasteNot, 8)))
|
||||
.build(),
|
||||
manipulation: ActionBuilder::new("Manipulation")
|
||||
.cp(96)
|
||||
.buff(Some((Buff::Manipulation, 8)))
|
||||
.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(),
|
||||
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(),
|
||||
|
|
@ -219,5 +452,99 @@ impl Default for ActionList {
|
|||
}
|
||||
|
||||
lazy_static! {
|
||||
pub static ref ACTIONS: ActionList = ActionList::default();
|
||||
}
|
||||
/// Initialize a static pseudo &Craft: ACTIONS
|
||||
pub static ref ACTIONS: ActionList = ActionList::default();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::action::ACTIONS;
|
||||
use pretty_assertions::assert_eq;
|
||||
use strum::IntoEnumIterator;
|
||||
#[test]
|
||||
pub fn test_structs() {
|
||||
let ac = crate::action::Action {
|
||||
name: "Michel".to_string(),
|
||||
dur: 0,
|
||||
cp: 0,
|
||||
progress: 0,
|
||||
quality: 0,
|
||||
buff: None,
|
||||
short_name: "miguel".to_string(),
|
||||
};
|
||||
let ab = crate::action::ActionBuilder { action: ac };
|
||||
let ba = crate::action::ActionBuilder::new(&"Basic Synthesis");
|
||||
let _ = crate::action::ActionBuilder::new(&"Groundwork");
|
||||
let cs = crate::action::ActionBuilder::new(&"Careful Synthesis");
|
||||
ab.dur(10)
|
||||
.cp(10)
|
||||
.progress(10)
|
||||
.quality(10)
|
||||
.buff(None)
|
||||
.build();
|
||||
let act1 = ba.cp(10).dur(22).progress(33).quality(44).build();
|
||||
let act2 = cs.cp(10).dur(22).progress(33).quality(44).build();
|
||||
assert_eq!(act1, act2);
|
||||
format!("{:?}", act1);
|
||||
let _ = crate::action::ActionList::default();
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_with_craft() {
|
||||
let mut bbs = crate::specs::BuffState::default();
|
||||
for buff in crate::specs::Buff::iter() {
|
||||
bbs.apply(buff, 2);
|
||||
}
|
||||
let mut act1 = crate::action::ActionBuilder::new(&"Basic Synthesis")
|
||||
.dur(22)
|
||||
.cp(10)
|
||||
.progress(100)
|
||||
.quality(100)
|
||||
.build();
|
||||
let mut craft = crate::craft::Craft::default();
|
||||
craft.buffs = bbs;
|
||||
|
||||
assert_eq!(act1.get_name(), "Basic Synthesis");
|
||||
assert_eq!(act1.get_cp_cost(&craft), 10);
|
||||
assert_eq!(act1.get_durability_cost(&craft), 11);
|
||||
assert_eq!(act1.get_progress(&craft), 250);
|
||||
assert_eq!(act1.get_quality(&craft), 300);
|
||||
assert_eq!(act1.get_buff(), None);
|
||||
|
||||
assert!(act1.can_use(&craft));
|
||||
|
||||
assert_eq!(&ACTIONS.standard_touch.get_cp_cost(&craft), &18);
|
||||
assert_eq!(&ACTIONS.advanced_touch.get_cp_cost(&craft), &18);
|
||||
assert_eq!(&ACTIONS.masters_mend.get_durability_cost(&craft), &-30);
|
||||
|
||||
assert_eq!(&ACTIONS.byregot_blessing.get_quality(&craft), &420);
|
||||
assert_eq!(&ACTIONS.byregot_blessing.can_use(&craft), &true);
|
||||
assert_eq!(&ACTIONS.muscle_memory.can_use(&craft), &true);
|
||||
assert_eq!(&ACTIONS.trained_finesse.can_use(&craft), &false);
|
||||
assert_eq!(&ACTIONS.reflect.can_use(&craft), &true);
|
||||
|
||||
act1.progress = 0;
|
||||
act1.quality = 0;
|
||||
assert_eq!(act1.get_durability_cost(&craft), 0);
|
||||
act1.dur = 0;
|
||||
act1.progress = 100;
|
||||
act1.quality = 100;
|
||||
assert_eq!(act1.get_durability_cost(&craft), 0);
|
||||
|
||||
act1.dur = 20;
|
||||
craft.durability = 10;
|
||||
craft.buffs = crate::specs::BuffState::default();
|
||||
assert_eq!(act1.get_progress(&craft), 50);
|
||||
assert_eq!(act1.get_quality(&craft), 50);
|
||||
|
||||
act1.dur = 2;
|
||||
assert_eq!(act1.get_durability_cost(&craft), 5);
|
||||
|
||||
craft.cp = 0;
|
||||
assert_eq!(&ACTIONS.reflect.can_use(&craft), &false);
|
||||
|
||||
craft.cp = 100;
|
||||
craft.success = crate::specs::Success::Failure;
|
||||
assert_eq!(&ACTIONS.reflect.can_use(&craft), &false);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,59 +0,0 @@
|
|||
// #![warn(missing_docs,unsafe_code,unstable_features,)]
|
||||
use std::time::{Instant};
|
||||
use clap::Parser;
|
||||
use xiv_craft_solver;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CustomError(String);
|
||||
|
||||
fn main() {
|
||||
let args = xiv_craft_solver::io::Args::parse();
|
||||
let params = xiv_craft_solver::io::Parameters::from_args(&args);
|
||||
|
||||
// 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 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();
|
||||
()
|
||||
}
|
||||
|
|
@ -0,0 +1,168 @@
|
|||
//! # Solver bin for FFXIV Crafting in Rust
|
||||
//!
|
||||
//! This project strives to provide a fast, accurate and reliable way to craft
|
||||
//! in FFXIV and obtain HQ results
|
||||
//!
|
||||
//! This project also provides bindings for python to allow hooking it to any form of better GUI/CLI
|
||||
//!
|
||||
//! The project is (for now) self-hosted and hosted on [Github](https://github.com/Dandaedre/xiv_csolver)
|
||||
//!
|
||||
//! ## Getting started
|
||||
//!
|
||||
//! ### Development
|
||||
//!
|
||||
//! #### Rust
|
||||
//! To set up the whole development environment, it is recommended to use cargo-make
|
||||
//!
|
||||
//! Doing so will allow you custom commands to
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo make rebuild
|
||||
//! ```
|
||||
//! To rebuild the whole project
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo make release
|
||||
//! ```
|
||||
//! To generate the release files, bins and libs, package them and make them ready to release
|
||||
//!
|
||||
//! #### Python
|
||||
//!
|
||||
//! It is really recommended to set up a venv to handle the python development
|
||||
//!
|
||||
//! All bindings and the explanation of how to use them can be found in the [`io`](xiv_csolver_lib::io) module.
|
||||
//!
|
||||
//! ### Features
|
||||
//!
|
||||
//! Use these by running `cargo run/build --features <name of feature>`
|
||||
//!
|
||||
//! - ``no_python`` : Don't build the lib & python bindings (WIP, not fully implemented)
|
||||
//! - ``fast`` : Don't allow some under-optimisation to run (saving global run-time)
|
||||
//! - ``verbose`` : Allow for more debug messages (note that -v(vv) must still be passed to activate them)
|
||||
//!
|
||||
//! ## Regenerating the API Bindings
|
||||
//!
|
||||
//! The python bindings are generated using maturin
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo install maturin
|
||||
//! maturin develop
|
||||
//! ```
|
||||
//! ## Solving and bias
|
||||
//!
|
||||
//! The solving algorithm used has a very strong bias toward a particular method:
|
||||
//!
|
||||
//! - **Step 1** : Try to push the progression of the craft one step before being finishable
|
||||
//! - **Step 2** : Try to increase the quality as much as possible.
|
||||
//! - **Step 3** : Finish the craft
|
||||
//!
|
||||
//! To account for a lot of possibilities, step one generates all methods to try and finish the craft
|
||||
//! and step two tests all methods to up the quality until all crafting points are depleted
|
||||
//! Doing so ensures by brute force that all permutations are thoroughly tested.
|
||||
//!
|
||||
//! While this method works and is very likely the best method for the current patch,
|
||||
//! a rework of the crafting actions could very well make this method subpar or at least
|
||||
//! on par with another method.
|
||||
//!
|
||||
//! In layman's term, only the groundwork opening is tested and no delicate synthesis spam is tested.
|
||||
//! However, for now, these two crafting techniques remain subpar and discarding them comes at no
|
||||
//! loss for the crafter.
|
||||
//!
|
||||
//! Others algorithm exists and could very well cover all other basis at the expense of runtime.
|
||||
//! We have chosen not to implement them as they (for now) would be very unlikely to uncover anything
|
||||
//! meaningful.
|
||||
//!
|
||||
//! ### Leveling
|
||||
//!
|
||||
//! We have (for now at least) no intention to release a leveling feature to the crafting solver
|
||||
//! However, selecting some spells and buffs and have them disabled could be added as a feature
|
||||
//! hence making a "leveling" option
|
||||
//!
|
||||
//! If it is ever released, this feature is likely to be heavily reliant on the python GUI.
|
||||
//!
|
||||
//!
|
||||
//! ## Contributing
|
||||
//!
|
||||
//! All form of contributions are welcome !
|
||||
//!
|
||||
//! While this project was originally a collab and didn't strive to encompass every need
|
||||
//! of a modern FFXIV crafter, more polish and finish is always welcome.
|
||||
//!
|
||||
//! ## License
|
||||
//!
|
||||
//! The original code was released without a license by [RikaKagurasaka](https://github.com/RikaKagurasaka/xiv_craft_solver)
|
||||
//!
|
||||
//! All this fork's code is released under [Apache-2.0](http://www.apache.org/licenses/LICENSE-2.0)
|
||||
|
||||
#![warn(missing_docs)]
|
||||
|
||||
use clap::Parser;
|
||||
use std::time::Instant;
|
||||
use xiv_csolver_lib;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CustomError(String);
|
||||
|
||||
fn main() {
|
||||
let args = xiv_csolver_lib::io::Args::parse();
|
||||
let params = xiv_csolver_lib::io::Parameters::from_args(&args);
|
||||
|
||||
// Start timer
|
||||
let now = Instant::now();
|
||||
println!("Solving...");
|
||||
|
||||
// Solve from config
|
||||
let (recipe, stats) =
|
||||
xiv_csolver_lib::load_from_config(&args.recipe_name, &args.file_name, &args.character_name);
|
||||
let results = xiv_csolver_lib::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.0.len());
|
||||
#[cfg(feature = "verbose")]
|
||||
if args.verbose > 1 {
|
||||
xiv_csolver_lib::print_routes(&results);
|
||||
}
|
||||
}
|
||||
println!("\n > SOLUTION [Least steps] <");
|
||||
xiv_csolver_lib::find_fast_route(&res)
|
||||
.unwrap()
|
||||
.pretty_print();
|
||||
println!("\n > SOLUTION [Most durability] <");
|
||||
xiv_csolver_lib::find_safe_route(&res)
|
||||
.unwrap()
|
||||
.pretty_print();
|
||||
println!("\n > SOLUTION [Most quality] < ");
|
||||
xiv_csolver_lib::find_quality_route(&res)
|
||||
.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();
|
||||
()
|
||||
}
|
||||
251
src/craft.rs
|
|
@ -1,25 +1,47 @@
|
|||
use std::fmt::{Debug, Formatter,Display};
|
||||
//! Module containing everything to create a craft and all methods to get the current state of the craft
|
||||
//!
|
||||
//! A craft represent the state of the recipe with a vector of actions applied to it.
|
||||
//! Applying actions to it will make the craft progress, while branching and trying other actions
|
||||
//! will be done by cloning
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::specs::{Buff, BuffState, Recipe, Stats, Success};
|
||||
use crate::Parameters;
|
||||
use std::fmt::{Debug, Display, Formatter};
|
||||
|
||||
/// The craft structure, note that there is no standard way of backtracking
|
||||
/// and a traditional branching method is applied when solving.
|
||||
#[derive(Clone)]
|
||||
pub struct Craft<'a> {
|
||||
pub recipe: Recipe,
|
||||
pub stats: Stats,
|
||||
/// The recipe used, contains all needed information on the difficulty and target
|
||||
pub recipe: Recipe,
|
||||
/// The stats of the crafter
|
||||
pub stats: Stats,
|
||||
/// The buffs currently running
|
||||
pub buffs: BuffState,
|
||||
/// The step count, aka number of steps done from the beggining of the craft
|
||||
pub step_count: u32,
|
||||
/// The remaining durability
|
||||
pub durability: i32,
|
||||
/// The current progression
|
||||
pub progression: u32,
|
||||
/// The current quality
|
||||
pub quality: u32,
|
||||
/// The cp currently remaining
|
||||
pub cp: i32,
|
||||
/// Wether the craft has succeded, is pending sucess, or failed
|
||||
pub success: Success,
|
||||
/// The vector of action already applied, structs are used for the vector since
|
||||
/// static references are used and therefore take no additional memory at runtime
|
||||
pub actions: Vec<&'a Action>,
|
||||
/// The parameters used for the craft
|
||||
/// TODO: The usage of a non reference is quite an oversight and should be changed ASAP
|
||||
pub args: Parameters,
|
||||
}
|
||||
|
||||
impl<'a> Craft<'a> {
|
||||
pub fn new(recipe: Recipe, stats: Stats, params: Parameters) -> Craft<'a> {
|
||||
/// Create a new craft with a recipe, stats and parameters
|
||||
pub fn new(recipe: Recipe, stats: Stats, params: Parameters) -> Craft<'a> {
|
||||
Self {
|
||||
recipe,
|
||||
stats,
|
||||
|
|
@ -35,16 +57,34 @@ impl<'a> Craft<'a> {
|
|||
}
|
||||
}
|
||||
|
||||
/// How much progression will be done by an action with 100 efficiency and no buffs
|
||||
/// This function is mainly used to know wether or not the craft will finish in
|
||||
/// 1, 1.2 or 2.0 actions.
|
||||
pub fn get_base_progression(&self) -> u32 {
|
||||
let base_value = (self.stats.craftsmanship as f64 / 10.0) / (self.recipe.progress_divider as f64 / 100.0) + 2.0;
|
||||
let base_value = (self.stats.craftsmanship as f64 / 10.0)
|
||||
/ (self.recipe.progress_divider as f64 / 100.0)
|
||||
+ 2.0;
|
||||
(base_value * (self.recipe.progress_modifier as f64 / 100.0) as f64).floor() as u32
|
||||
}
|
||||
|
||||
/// How much quality will the crafter generate with one action with 100 efficiency and no buffs
|
||||
/// This function is usually called by [`run_action`](crate::craft::Craft::run_action)
|
||||
/// wich will then apply all needed buff and progress the craft
|
||||
pub fn get_base_quality(&self) -> u32 {
|
||||
let base_value = (self.stats.control as f64 / 10.0) / (self.recipe.quality_divider as f64 / 100.0) + 35.0;
|
||||
let base_value = (self.stats.control as f64 / 10.0)
|
||||
/ (self.recipe.quality_divider as f64 / 100.0)
|
||||
+ 35.0;
|
||||
(base_value * (self.recipe.quality_modifier as f64 / 100.0) as f64).floor() as u32
|
||||
}
|
||||
|
||||
/// Add an action to the current craft
|
||||
/// This method will:
|
||||
/// - Check wether the action can be used
|
||||
/// - Increment the step count
|
||||
/// - Decrease cp
|
||||
/// - Decrease or increase durability
|
||||
/// - Increase progression
|
||||
/// - "Tick" buffs (substract 1 from their remaining time) and remove them if consumed
|
||||
/// - Add the used action to the vec of actions used
|
||||
pub fn run_action(&mut self, action: &'a Action) -> &mut Craft<'a> {
|
||||
if !action.can_use(self) {
|
||||
self.success = Success::Failure;
|
||||
|
|
@ -53,18 +93,39 @@ impl<'a> Craft<'a> {
|
|||
self.step_count += 1;
|
||||
self.cp -= action.get_cp_cost(self) as i32;
|
||||
self.durability -= action.get_durability_cost(self) as i32;
|
||||
self.progression += (action.get_progress(self) as f64 * (self.get_base_progression() as f64 / 100.0)).floor() as u32;
|
||||
self.quality += (action.get_quality(self) as f64 * (self.get_base_quality() as f64 / 100.0)).floor() as u32;
|
||||
if self.progression >= self.recipe.progress { self.success = Success::Success; }
|
||||
if self.durability <= 0 { self.success = Success::Failure; }
|
||||
if self.buffs.manipulation > 0 { self.durability += 5; }
|
||||
if action.quality > 0 { self.buffs.inner_quiet += 1; }
|
||||
self.progression += (action.get_progress(self) as f64
|
||||
* (self.get_base_progression() as f64 / 100.0))
|
||||
.floor() as u32;
|
||||
self.quality += (action.get_quality(self) as f64 * (self.get_base_quality() as f64 / 100.0))
|
||||
.floor() as u32;
|
||||
if self.progression >= self.recipe.progress {
|
||||
self.success = Success::Success;
|
||||
}
|
||||
if self.durability <= 0 {
|
||||
self.success = Success::Failure;
|
||||
}
|
||||
if self.buffs.manipulation > 0 {
|
||||
self.durability += 5;
|
||||
}
|
||||
if action.quality > 0 {
|
||||
self.buffs.inner_quiet += 1;
|
||||
}
|
||||
self.buffs.tick();
|
||||
if action.progress > 0 { self.buffs.remove(Buff::MuscleMemory); }
|
||||
if action.quality > 0 { self.buffs.remove(Buff::GreatStrides); }
|
||||
if let Some((buff, duration)) = action.get_buff() { self.buffs.apply(buff, duration); }
|
||||
if self.durability > self.recipe.durability as i32 { self.durability = self.recipe.durability as i32; }
|
||||
if self.buffs.inner_quiet > 10 { self.buffs.inner_quiet = 10; }
|
||||
if action.progress > 0 {
|
||||
self.buffs.remove(Buff::MuscleMemory);
|
||||
}
|
||||
if action.quality > 0 {
|
||||
self.buffs.remove(Buff::GreatStrides);
|
||||
}
|
||||
if let Some((buff, duration)) = action.get_buff() {
|
||||
self.buffs.apply(buff, duration);
|
||||
}
|
||||
if self.durability > self.recipe.durability as i32 {
|
||||
self.durability = self.recipe.durability as i32;
|
||||
}
|
||||
if self.buffs.inner_quiet > 10 {
|
||||
self.buffs.inner_quiet = 10;
|
||||
}
|
||||
|
||||
self.actions.push(action);
|
||||
return self;
|
||||
|
|
@ -95,20 +156,160 @@ impl<'a> Debug for Craft<'a> {
|
|||
.field("durability", &format!("{:?}/{:?}", &self.durability, &self.recipe.durability))
|
||||
// .field("cp", &format!("{:?}/{:?}", &self.cp, &self.stats.max_cp))
|
||||
;
|
||||
binding.field("actions",&self.actions);
|
||||
binding.field("actions", &self.actions);
|
||||
binding.finish()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl<'a> Display for Craft<'a> {
|
||||
fn fmt(&self, f: &mut Formatter)-> std::fmt::Result {
|
||||
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
|
||||
f.debug_struct("Craft")
|
||||
.field("step_count", &self.step_count)
|
||||
.field("progression", &format!("{:?}/{:?}", &self.progression, &self.recipe.progress))
|
||||
.field("quality", &format!("{:?}/{:?}", &self.quality, &self.recipe.quality))
|
||||
.field("durability", &format!("{:?}/{:?}", &self.durability, &self.recipe.durability))
|
||||
.field(
|
||||
"progression",
|
||||
&format!("{:?}/{:?}", &self.progression, &self.recipe.progress),
|
||||
)
|
||||
.field(
|
||||
"quality",
|
||||
&format!("{:?}/{:?}", &self.quality, &self.recipe.quality),
|
||||
)
|
||||
.field(
|
||||
"durability",
|
||||
&format!("{:?}/{:?}", &self.durability, &self.recipe.durability),
|
||||
)
|
||||
.field("cp", &format!("{:?}/{:?}", &self.cp, &self.stats.max_cp))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl<'a> Craft<'a> {
|
||||
/// Create a "Default" craft, testing only
|
||||
pub fn default() -> Craft<'a> {
|
||||
Self::new(
|
||||
crate::specs::Recipe {
|
||||
durability: 200,
|
||||
progress: 200,
|
||||
progress_divider: 100,
|
||||
progress_modifier: 100,
|
||||
quality: 100,
|
||||
quality_divider: 100,
|
||||
quality_modifier: 100,
|
||||
},
|
||||
crate::specs::Stats {
|
||||
craftsmanship: 200,
|
||||
control: 200,
|
||||
max_cp: 200,
|
||||
},
|
||||
crate::io::Parameters {
|
||||
threads: 10,
|
||||
verbose: 2,
|
||||
depth: 10,
|
||||
desperate: false,
|
||||
byregot_step: 10,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Create a "Two start" craft, testing only
|
||||
pub fn two_star() -> Craft<'a> {
|
||||
Self::new(
|
||||
crate::specs::Recipe {
|
||||
durability: 70,
|
||||
progress: 3900,
|
||||
quality: 10920,
|
||||
progress_divider: 130,
|
||||
quality_divider: 115,
|
||||
progress_modifier: 80,
|
||||
quality_modifier: 70,
|
||||
},
|
||||
crate::specs::Stats {
|
||||
craftsmanship: 4041,
|
||||
control: 3971,
|
||||
max_cp: 595,
|
||||
},
|
||||
crate::io::Parameters {
|
||||
threads: 8,
|
||||
verbose: 2,
|
||||
depth: 8,
|
||||
desperate: false,
|
||||
byregot_step: 10,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Create a "Zero star" craft for debbuging & testing
|
||||
pub fn zero_star() -> Craft<'a> {
|
||||
Self::new(
|
||||
crate::specs::Recipe {
|
||||
durability: 70,
|
||||
progress: 4000,
|
||||
quality: 10920,
|
||||
progress_divider: 100,
|
||||
quality_divider: 100,
|
||||
progress_modifier: 100,
|
||||
quality_modifier: 100,
|
||||
},
|
||||
crate::specs::Stats {
|
||||
craftsmanship: 4000,
|
||||
control: 4000,
|
||||
max_cp: 600,
|
||||
},
|
||||
crate::io::Parameters {
|
||||
threads: 8,
|
||||
verbose: 2,
|
||||
depth: 8,
|
||||
desperate: false,
|
||||
byregot_step: 10,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use pretty_assertions::assert_eq;
|
||||
// Struct Test
|
||||
#[test]
|
||||
pub fn struct_tests() {
|
||||
let craft = crate::craft::Craft::zero_star().clone();
|
||||
assert_eq!(craft.get_base_progression(), 402);
|
||||
assert_eq!(craft.get_base_quality(), 435);
|
||||
|
||||
format!("{}", craft);
|
||||
format!("{:?}", craft);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_craft() {
|
||||
let mut craft = crate::craft::Craft::default();
|
||||
craft.cp = 1000;
|
||||
format!("{:?}", craft);
|
||||
let mut craft2 = craft.run_action(&crate::action::ACTIONS.veneration).clone();
|
||||
|
||||
craft.run_action(&crate::action::ACTIONS.masters_mend);
|
||||
craft.run_action(&crate::action::ACTIONS.masters_mend);
|
||||
craft.run_action(&crate::action::ACTIONS.manipulation);
|
||||
craft.run_action(&crate::action::ACTIONS.basic_touch);
|
||||
craft.run_action(&crate::action::ACTIONS.basic_synthesis);
|
||||
assert_eq!(craft.durability, 190);
|
||||
craft.run_action(&crate::action::ACTIONS.masters_mend);
|
||||
assert_eq!(craft.durability, 200);
|
||||
craft.run_action(&crate::action::ACTIONS.masters_mend);
|
||||
for _ in 0..10 {
|
||||
craft.run_action(&crate::action::ACTIONS.basic_touch);
|
||||
}
|
||||
|
||||
for _ in 0..3 {
|
||||
craft.run_action(&crate::action::ACTIONS.masters_mend);
|
||||
craft.run_action(&crate::action::ACTIONS.groundwork);
|
||||
}
|
||||
assert_eq!(craft.success, crate::craft::Success::Success);
|
||||
|
||||
for _ in 0..20 {
|
||||
craft2.run_action(&crate::action::ACTIONS.preparatory_touch);
|
||||
}
|
||||
assert_eq!(craft2.durability, 0);
|
||||
assert_eq!(craft2.success, crate::craft::Success::Failure);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
332
src/io.rs
|
|
@ -1,19 +1,30 @@
|
|||
use crate::Craft;
|
||||
use core::fmt::Display;
|
||||
//! The main IO module
|
||||
//! For now it contains the Args bindings (for clap) and the struct
|
||||
//! needed to hold all parameters needed at runtime
|
||||
|
||||
use clap::Parser;
|
||||
|
||||
#[cfg(not(feature="no_python"))]
|
||||
use pyo3::prelude::*;
|
||||
|
||||
/// The parameters needed at runtime, used since Args cannot easily be passed to python
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Parameters {
|
||||
/// The number of threads to use
|
||||
/// TODO: Add an auto feature to guess threads depending on architecture and action pool
|
||||
pub threads: usize,
|
||||
/// The level of verbosity from 0 to 3
|
||||
pub verbose: u8,
|
||||
/// How many steps are allowed for finishing the craft
|
||||
/// TODO: Be a little smarted about this approach and stop guessing if enough starters are found
|
||||
/// and continue guessing if more are needed
|
||||
pub depth: u32,
|
||||
pub desperate:bool,
|
||||
/// Wether to try every mesure to finish the craft or not
|
||||
pub desperate: bool,
|
||||
/// How early byregot will be used, setting it too low high miss easy solutions (for small crafts)
|
||||
/// but setting it too low will have the solver try byregot way too often adding many useless crafts
|
||||
/// in the pool of solutions
|
||||
pub byregot_step: u8,
|
||||
}
|
||||
|
||||
/// The args passed to the CLI, used by clap to generate a nice argument parser
|
||||
#[derive(Parser, Debug, Clone)]
|
||||
#[command(author, version, about, long_about = None)]
|
||||
pub struct Args {
|
||||
|
|
@ -28,7 +39,7 @@ pub struct Args {
|
|||
/// 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,
|
||||
|
|
@ -42,184 +53,161 @@ pub struct Args {
|
|||
pub threads: usize,
|
||||
|
||||
/// Desperate mode, will try to finish the craft above all
|
||||
#[arg(short='D', long, default_value_t = false)]
|
||||
#[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)]
|
||||
#[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},
|
||||
impl Parameters {
|
||||
/// Create parameters from the arguments parsed by clap
|
||||
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}
|
||||
byregot_step: if args.long { 6 } else { 8 },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::io::{Args, Parameters};
|
||||
use crate::python_bindings::SolverResult;
|
||||
use clap::Parser;
|
||||
use pretty_assertions::{assert_eq, assert_ne};
|
||||
|
||||
////// Python Bindings //////
|
||||
impl PartialEq for Parameters {
|
||||
fn eq(&self, rhs: &Parameters) -> bool {
|
||||
(self.byregot_step == rhs.byregot_step)
|
||||
& (self.depth == rhs.depth)
|
||||
& (self.desperate == rhs.desperate)
|
||||
& (self.threads == rhs.threads)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(())
|
||||
#[test]
|
||||
pub fn test_parameters_derived_attributes() {
|
||||
let def = Parameters {
|
||||
byregot_step: 0,
|
||||
depth: 0,
|
||||
desperate: false,
|
||||
threads: 42,
|
||||
verbose: 1,
|
||||
};
|
||||
let def2 = def;
|
||||
let def3 = def2.clone();
|
||||
|
||||
assert_eq!(def2, def3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_display() {
|
||||
let def = SolverResult::default();
|
||||
assert_ne!(def.to_string(), "");
|
||||
assert_eq!(def.to_string(), "[\"Act1\", \"Act2\"]");
|
||||
def.pretty_print();
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_debug() {
|
||||
let def = SolverResult::default();
|
||||
assert_eq!(format!("{:?}", def),"SolverResult { steps: 0, quality: 0, progression: 0, durability: 0, cp: 0, total_cp: 0, total_progression: 0, total_quality: 0, total_durability: 0, actions: [\"Act1\", \"Act2\"] }");
|
||||
//, step1_solutions: 0, step2_solutions: 0, found_100_percent: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_arguments() {
|
||||
// Create false argument parameter
|
||||
let a = Args {
|
||||
character_name: "Bob GZ".to_string(),
|
||||
depth: 77,
|
||||
desperate: false,
|
||||
file_name: "test.toml".to_string(),
|
||||
long: false,
|
||||
recipe_name: "Belladone".to_string(),
|
||||
threads: 11,
|
||||
verbose: 1,
|
||||
};
|
||||
let a2 = a.clone();
|
||||
println!("{:?}", a2);
|
||||
// Test Custom recipe
|
||||
let a3 = crate::io::Args::parse_from([
|
||||
"ultraman",
|
||||
"-r",
|
||||
"recipe",
|
||||
"-c",
|
||||
"dan",
|
||||
"-f",
|
||||
"bigfile.toml",
|
||||
"-d",
|
||||
"45",
|
||||
"-t",
|
||||
"4",
|
||||
"-D",
|
||||
"-l",
|
||||
"-vvv",
|
||||
]);
|
||||
let _ = Args::parse_from(["-V"]);
|
||||
let _ = Args::parse_from(["-H"]);
|
||||
assert_eq!(a3.recipe_name, "recipe");
|
||||
assert_eq!(a3.character_name, "dan");
|
||||
assert_eq!(a3.file_name, "bigfile.toml");
|
||||
assert_eq!(a3.verbose, 3);
|
||||
assert_eq!(a3.depth, 45);
|
||||
assert_eq!(a3.threads, 4);
|
||||
assert_eq!(a3.desperate, true);
|
||||
assert_eq!(a3.long, true);
|
||||
|
||||
// Test default parameters
|
||||
let a4 = Args::parse_from(["bobGZ"]);
|
||||
assert_eq!(a4.recipe_name, "default_recipe");
|
||||
assert_eq!(a4.character_name, "default_character");
|
||||
assert_eq!(a4.file_name, "craft.toml");
|
||||
assert_eq!(a4.verbose, 0);
|
||||
assert_eq!(a4.depth, 8);
|
||||
assert_eq!(a4.threads, 4);
|
||||
assert_eq!(a4.desperate, false);
|
||||
assert_eq!(a4.long, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_parameters() {
|
||||
// Test a random config
|
||||
let ar = Args::parse_from([
|
||||
"ultraman",
|
||||
"-r",
|
||||
"recipe",
|
||||
"-c",
|
||||
"dan",
|
||||
"-f",
|
||||
"bigfile.toml",
|
||||
"-d",
|
||||
"45",
|
||||
"-t",
|
||||
"4",
|
||||
"-D",
|
||||
"-l",
|
||||
"-vvv",
|
||||
]);
|
||||
let p = Parameters::from_args(&ar);
|
||||
assert_eq!(p.depth, 11);
|
||||
assert_eq!(p.verbose, 3);
|
||||
assert_eq!(p.threads, 4);
|
||||
assert_eq!(p.desperate, true);
|
||||
assert_eq!(p.byregot_step, 6);
|
||||
|
||||
// Test defaults
|
||||
let ar = Args::parse_from(&["a"]);
|
||||
let p = Parameters::from_args(&ar);
|
||||
assert_eq!(p.depth, 8);
|
||||
assert_eq!(p.verbose, 0);
|
||||
assert_eq!(p.threads, 4);
|
||||
assert_eq!(p.desperate, false);
|
||||
assert_eq!(p.byregot_step, 8);
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
#[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)
|
||||
}
|
||||
570
src/lib.rs
|
|
@ -1,28 +1,129 @@
|
|||
use crate::io::SolverResult;
|
||||
use crate::{
|
||||
craft::Craft,
|
||||
specs::{Recipe,Stats},
|
||||
io::Parameters,
|
||||
};
|
||||
use threadpool::ThreadPool;
|
||||
use std::sync::{Arc,Mutex};
|
||||
//! # Solver bin for FFXIV Crafting in Rust
|
||||
//!
|
||||
//! This project strives to provide a fast, accurate and reliable way to craft
|
||||
//! in FFXIV and obtain HQ results
|
||||
//!
|
||||
//! This project also provides bindings for python to allow hooking it to any form of better GUI/CLI
|
||||
//!
|
||||
//! The project is (for now) self-hosted and hosted on [Github](https://github.com/Dandaedre/xiv_csolver)
|
||||
//!
|
||||
//! ## Getting started
|
||||
//!
|
||||
//! ### Development
|
||||
//!
|
||||
//! #### Rust
|
||||
//! To set up the whole development environment, it is recommended to use cargo-make
|
||||
//!
|
||||
//! Doing so will allow you custom commands to
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo make rebuild
|
||||
//! ```
|
||||
//! To rebuild the whole project
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo make release
|
||||
//! ```
|
||||
//! To generate the release files, bins and libs, package them and make them ready to release
|
||||
//!
|
||||
//! #### Python
|
||||
//!
|
||||
//! It is really recommended to set up a venv to handle the python development
|
||||
//!
|
||||
//! All bindings and the explanation of how to use them can be found in the [`io`](crate::io) module.
|
||||
//!
|
||||
//! ### Features
|
||||
//!
|
||||
//! Use these by running `cargo run/build --features <name of feature>`
|
||||
//!
|
||||
//! - ``no_python`` : Don't build the lib & python bindings (WIP, not fully implemented)
|
||||
//! - ``fast`` : Don't allow some under-optimisation to run (saving global run-time)
|
||||
//! - ``verbose`` : Allow for more debug messages (note that -v(vv) must still be passed to activate them)
|
||||
//!
|
||||
//! ## Regenerating the API Bindings
|
||||
//!
|
||||
//! The python bindings are generated using maturin
|
||||
//!
|
||||
//! ```sh
|
||||
//! cargo install maturin
|
||||
//! maturin develop
|
||||
//! ```
|
||||
//! ## Solving and bias
|
||||
//!
|
||||
//! The solving algorithm used has a very strong bias toward a particular method:
|
||||
//!
|
||||
//! - **Step 1** : Try to push the progression of the craft one step before being finishable
|
||||
//! - **Step 2** : Try to increase the quality as much as possible.
|
||||
//! - **Step 3** : Finish the craft
|
||||
//!
|
||||
//! To account for a lot of possibilities, step one generates all methods to try and finish the craft
|
||||
//! and step two tests all methods to up the quality until all crafting points are depleted
|
||||
//! Doing so ensures by brute force that all permutations are thoroughly tested.
|
||||
//!
|
||||
//! While this method works and is very likely the best method for the current patch,
|
||||
//! a rework of the crafting actions could very well make this method subpar or at least
|
||||
//! on par with another method.
|
||||
//!
|
||||
//! In layman's term, only the groundwork opening is tested and no delicate synthesis spam is tested.
|
||||
//! However, for now, these two crafting techniques remain subpar and discarding them comes at no
|
||||
//! loss for the crafter.
|
||||
//!
|
||||
//! Others algorithm exists and could very well cover all other basis at the expense of runtime.
|
||||
//! We have chosen not to implement them as they (for now) would be very unlikely to uncover anything
|
||||
//! meaningful.
|
||||
//!
|
||||
//! ### Leveling
|
||||
//!
|
||||
//! We have (for now at least) no intention to release a leveling feature to the crafting solver
|
||||
//! However, selecting some spells and buffs and have them disabled could be added as a feature
|
||||
//! hence making a "leveling" option
|
||||
//!
|
||||
//! If it is ever released, this feature is likely to be heavily reliant on the python GUI.
|
||||
//!
|
||||
//!
|
||||
//! ## Contributing
|
||||
//!
|
||||
//! All form of contributions are welcome !
|
||||
//!
|
||||
//! While this project was originally a collab and didn't strive to encompass every need
|
||||
//! of a modern FFXIV crafter, more polish and finish is always welcome.
|
||||
//!
|
||||
//! ## License
|
||||
//!
|
||||
//! The original code was released without a license by [RikaKagurasaka](https://github.com/RikaKagurasaka/xiv_craft_solver)
|
||||
//!
|
||||
//! All this fork's code is released under [Apache-2.0](http://www.apache.org/licenses/LICENSE-2.0)
|
||||
|
||||
#![warn(missing_docs)]
|
||||
|
||||
use crate::craft::Craft;
|
||||
use crate::io::Parameters;
|
||||
use crate::python_bindings::{Info, SolverResult};
|
||||
use crate::specs::{Recipe, Stats};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use threadpool::ThreadPool;
|
||||
|
||||
mod solver;
|
||||
mod specs;
|
||||
pub mod action;
|
||||
pub mod craft;
|
||||
pub mod io;
|
||||
pub mod python_bindings;
|
||||
mod solver;
|
||||
pub mod specs;
|
||||
|
||||
/// 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<Vec<SolverResult>>{
|
||||
pub fn solve_craft<'a>(
|
||||
recipe: Recipe,
|
||||
stats: Stats,
|
||||
params: Parameters,
|
||||
) -> Option<(Vec<SolverResult>, Info)> {
|
||||
// Load the craft with given arguments
|
||||
let craft = Craft::new(recipe,stats,params);
|
||||
let craft = Craft::new(recipe, stats, params);
|
||||
|
||||
// Start a threadpool
|
||||
let pool = ThreadPool::new(params.threads);
|
||||
|
||||
#[cfg(feature = "verbose")]
|
||||
if params.verbose>0{
|
||||
if params.verbose > 0 {
|
||||
println!("[P1] Starting phase 1...");
|
||||
}
|
||||
|
||||
|
|
@ -30,21 +131,33 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti
|
|||
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,r.quality * 100 / r.recipe.quality,r.cp,r.durability);
|
||||
}}
|
||||
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,
|
||||
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
|
||||
let arc_phase2_routes = Arc::new(Mutex::new(Vec::<Craft>::new()));
|
||||
|
||||
for route in phase1_routes {
|
||||
let _phase2_routes = Arc::clone(&arc_phase2_routes);
|
||||
|
||||
pool.execute(move || {
|
||||
if let Some(mut _route) = solver::generate_routes_phase2(route){
|
||||
if let Some(mut _route) = solver::generate_routes_phase2(route) {
|
||||
let mut shared = _phase2_routes.lock().unwrap();
|
||||
shared.append(&mut _route);
|
||||
};
|
||||
|
|
@ -55,146 +168,393 @@ pub fn solve_craft<'a>(recipe: Recipe, stats: Stats, params: Parameters) -> Opti
|
|||
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
|
||||
// Drop on empty results. // TODO: Retry automatically with better parameters
|
||||
if phase2_routes.len() == 0 {
|
||||
// No solutions were found
|
||||
if params.desperate {
|
||||
// But everything was tested
|
||||
return Some((Vec::<SolverResult>::new(), Info::new(0, 0, false)));
|
||||
} else {
|
||||
// And not everything was tested
|
||||
return solve_craft(
|
||||
recipe,
|
||||
stats,
|
||||
Parameters {
|
||||
depth: 11,
|
||||
byregot_step: 6,
|
||||
desperate: true,
|
||||
..params
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 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 > 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
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prune the results for analysis
|
||||
// let mut valid_routes : Vec<Craft> = vec![];
|
||||
let mut valid_solutions: Vec<SolverResult> = vec![];
|
||||
for route in phase2_routes.iter(){
|
||||
if route.quality>=route.recipe.quality{
|
||||
for route in phase2_routes.iter() {
|
||||
if route.quality >= route.recipe.quality {
|
||||
// valid_routes.push(route.clone());
|
||||
valid_solutions.push(SolverResult::from_craft(route,nb_p1,nb_p2,true));
|
||||
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_solutions.len()==0{
|
||||
for route in phase2_routes.iter(){valid_solutions.push(SolverResult::from_craft(route,nb_p1,nb_p2,false));}
|
||||
if valid_solutions.len() == 0 {
|
||||
for route in phase2_routes.iter() {
|
||||
valid_solutions.push(SolverResult::from_craft(route));
|
||||
}
|
||||
}
|
||||
|
||||
Some(valid_solutions)
|
||||
Some((valid_solutions, Info::new(nb_p1, nb_p2, true)))
|
||||
}
|
||||
|
||||
/// Load the config from args and make a craft from it
|
||||
pub fn load_from_config<'a>(recipe_name: &str, file_name: &str, character_name: &str) -> (Recipe,Stats) {
|
||||
pub fn load_from_config<'a>(
|
||||
recipe_name: &str,
|
||||
file_name: &str,
|
||||
character_name: &str,
|
||||
) -> (Recipe, Stats) {
|
||||
//read craft.toml
|
||||
let config: toml::Value = toml::from_str(
|
||||
&std::fs::read_to_string(file_name)
|
||||
.expect(&format!("Can't open {}",file_name))
|
||||
).unwrap();
|
||||
&std::fs::read_to_string(file_name).expect(&format!("Can't open {}", file_name)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let recp = match config.get(recipe_name){
|
||||
let recp = match config.get(recipe_name) {
|
||||
Some(r) => r,
|
||||
None => panic!("Can't find value '{}' in '{}'",recipe_name, file_name)
|
||||
None => panic!("Can't find value '{}' in '{}'", recipe_name, file_name),
|
||||
};
|
||||
|
||||
// Load receipe values
|
||||
let recipe = Recipe {
|
||||
durability: recp
|
||||
.get("durability").expect(&format!("Can't find 'durability' in recipe '{}' on file '{}'",
|
||||
recipe_name,file_name))
|
||||
.as_integer().expect("Can't convert durability as an integer") as u32,
|
||||
.get("durability")
|
||||
.expect(&format!(
|
||||
"Can't find 'durability' in recipe '{}' on file '{}'",
|
||||
recipe_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert durability as an integer") as u32,
|
||||
progress: recp
|
||||
.get("progress").expect(&format!("Can't find 'progress' in recipe '{}' on '{}'",
|
||||
recipe_name,file_name))
|
||||
.as_integer().expect("Can't convert progress as an integer") as u32,
|
||||
.get("progress")
|
||||
.expect(&format!(
|
||||
"Can't find 'progress' in recipe '{}' on '{}'",
|
||||
recipe_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert progress as an integer") as u32,
|
||||
quality: recp
|
||||
.get("quality").expect(&format!("Can't find 'quality' in recipe '{}' on '{}'",
|
||||
recipe_name,file_name))
|
||||
.as_integer().expect("Can't convert quality as an integer") as u32,
|
||||
.get("quality")
|
||||
.expect(&format!(
|
||||
"Can't find 'quality' in recipe '{}' on '{}'",
|
||||
recipe_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert quality as an integer") as u32,
|
||||
progress_divider: recp
|
||||
.get("progress_divider").expect(&format!("Can't find 'progress_divider' in recipe '{}' on '{}'",
|
||||
recipe_name,file_name))
|
||||
.as_integer().expect("Can't convert progress_divider as an integer") as u32,
|
||||
.get("progress_divider")
|
||||
.expect(&format!(
|
||||
"Can't find 'progress_divider' in recipe '{}' on '{}'",
|
||||
recipe_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert progress_divider as an integer")
|
||||
as u32,
|
||||
quality_divider: recp
|
||||
.get("quality_divider").expect(&format!("Can't find 'quality_divider' in recipe '{}' on '{}'",
|
||||
recipe_name,file_name))
|
||||
.as_integer().expect("Can't convert quality_divider as an integer") as u32,
|
||||
.get("quality_divider")
|
||||
.expect(&format!(
|
||||
"Can't find 'quality_divider' in recipe '{}' on '{}'",
|
||||
recipe_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert quality_divider as an integer") as u32,
|
||||
progress_modifier: recp
|
||||
.get("progress_modifier").expect(&format!("Can't find 'progress_modifier' in recipe '{}' on '{}'",
|
||||
recipe_name,file_name))
|
||||
.as_integer().expect("Can't convert progress_modifier as an integer") as u32,
|
||||
.get("progress_modifier")
|
||||
.expect(&format!(
|
||||
"Can't find 'progress_modifier' in recipe '{}' on '{}'",
|
||||
recipe_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert progress_modifier as an integer")
|
||||
as u32,
|
||||
quality_modifier: recp
|
||||
.get("quality_modifier").expect(&format!("Can't find 'quality_modifier' in recipe '{}' on '{}'",
|
||||
recipe_name,file_name))
|
||||
.as_integer().expect("Can't convert quality_modifier as an integer") as u32,
|
||||
.get("quality_modifier")
|
||||
.expect(&format!(
|
||||
"Can't find 'quality_modifier' in recipe '{}' on '{}'",
|
||||
recipe_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert quality_modifier as an integer")
|
||||
as u32,
|
||||
};
|
||||
|
||||
let cfg = match config.get(character_name){
|
||||
let cfg = match config.get(character_name) {
|
||||
Some(c) => c,
|
||||
None => panic!("Can't find '{}' in file '{}'",character_name,file_name),
|
||||
None => panic!("Can't find '{}' in file '{}'", character_name, file_name),
|
||||
};
|
||||
let stats = Stats {
|
||||
craftsmanship: cfg
|
||||
.get("craftsmanship").expect(&format!("Can't find 'craftsmanship' in character '{}' on file '{}'",
|
||||
character_name,file_name))
|
||||
.as_integer().expect("Can't convert craftsmanship as an integer") as u32,
|
||||
.get("craftsmanship")
|
||||
.expect(&format!(
|
||||
"Can't find 'craftsmanship' in character '{}' on file '{}'",
|
||||
character_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert craftsmanship as an integer") as u32,
|
||||
control: cfg
|
||||
.get("control").expect(&format!("Can't find 'control' in character '{}' on file '{}'",
|
||||
character_name,file_name))
|
||||
.as_integer().expect("Can't convert control as an integer") as u32,
|
||||
.get("control")
|
||||
.expect(&format!(
|
||||
"Can't find 'control' in character '{}' on file '{}'",
|
||||
character_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert control as an integer") as u32,
|
||||
max_cp: cfg
|
||||
.get("max_cp").expect(&format!("Can't find 'max_cp' in character '{}' on file '{}'",
|
||||
character_name,file_name))
|
||||
.as_integer().expect("Can't convert max_cp as an integer") as u32,
|
||||
.get("max_cp")
|
||||
.expect(&format!(
|
||||
"Can't find 'max_cp' in character '{}' on file '{}'",
|
||||
character_name, file_name
|
||||
))
|
||||
.as_integer()
|
||||
.expect("Can't convert max_cp as an integer") as u32,
|
||||
};
|
||||
(recipe,stats)
|
||||
(recipe, stats)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
pub fn print_routes<'a>(routes: &Option<(Vec<SolverResult>, Info)>) {
|
||||
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")
|
||||
}
|
||||
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,
|
||||
pub fn find_fast_route<'a>(routes: &'a (Vec<SolverResult>, Info)) -> Option<&'a SolverResult> {
|
||||
let (_routes, _info) = routes;
|
||||
if _routes.len() > 0 {
|
||||
_routes.iter().min_by_key(|key| key.steps)
|
||||
} else {
|
||||
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,
|
||||
}
|
||||
pub fn find_quality_route<'a>(routes: &'a (Vec<SolverResult>, Info)) -> Option<&'a SolverResult> {
|
||||
let (_routes, _info) = routes;
|
||||
_routes.iter().max_by_key(|key| key.quality)
|
||||
}
|
||||
|
||||
/// 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,
|
||||
pub fn find_safe_route(routes: &(Vec<SolverResult>, Info)) -> Option<&SolverResult> {
|
||||
let (_routes, _info) = routes;
|
||||
if _routes.len() > 0 {
|
||||
_routes.iter().max_by_key(|key| key.durability)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
pub fn test_lib_find_route() {
|
||||
// Supposed to find a route for the base craft
|
||||
let mut craft = crate::craft::Craft::two_star();
|
||||
let res = solve_craft(craft.recipe, craft.stats, craft.args);
|
||||
assert!(res.unwrap().0.len() > 2000);
|
||||
|
||||
craft.recipe.progress = 0;
|
||||
let res = solve_craft(craft.recipe, craft.stats, craft.args);
|
||||
println!("{:?}", res);
|
||||
assert!(res.unwrap().0.len() == 0);
|
||||
|
||||
craft.recipe.progress = 100;
|
||||
craft.stats.max_cp = 0;
|
||||
craft.cp = 0;
|
||||
|
||||
let mut res = solve_craft(craft.recipe, craft.stats, craft.args).unwrap();
|
||||
println!("{:?}", res);
|
||||
assert_eq!(res.0.len(), 1);
|
||||
assert_eq!(res.0.pop().unwrap().actions, vec!("basicSynth2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_lib_print_route() {
|
||||
let craft = crate::craft::Craft::two_star();
|
||||
print_routes(&solve_craft(craft.recipe, craft.stats, craft.args));
|
||||
print_routes(&None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_lib_best_solutions() {
|
||||
let craft = crate::craft::Craft::two_star();
|
||||
let routes = solve_craft(craft.recipe, craft.stats, craft.args).unwrap();
|
||||
// assert!(find_fast_route(&(None)).is_none());
|
||||
// assert!(find_quality_route(&None).is_none());
|
||||
// assert!(find_safe_route(&None).is_none());
|
||||
|
||||
assert!(find_fast_route(&((vec![], Info::default()))).is_none());
|
||||
assert!(find_quality_route(&((vec![], Info::default()))).is_none());
|
||||
assert!(find_safe_route(&((vec![], Info::default()))).is_none());
|
||||
|
||||
let sol = find_fast_route(&routes).unwrap();
|
||||
assert_eq!(sol.steps, 17);
|
||||
assert_eq!(sol.quality, 11129);
|
||||
assert_eq!(sol.progression, 3750);
|
||||
assert_eq!(sol.durability, 0);
|
||||
assert_eq!(sol.cp, 7);
|
||||
assert_eq!(routes.1.step1_solutions, 9);
|
||||
assert_eq!(routes.1.step2_solutions, 21193);
|
||||
assert_eq!(routes.1.found_100_percent, true);
|
||||
assert_eq!(
|
||||
sol.actions,
|
||||
vec!(
|
||||
"muscleMemory",
|
||||
"manipulation",
|
||||
"veneration",
|
||||
"wasteNot2",
|
||||
"groundwork",
|
||||
"delicateSynthesis",
|
||||
"delicateSynthesis",
|
||||
"innovation",
|
||||
"preparatoryTouch",
|
||||
"preparatoryTouch",
|
||||
"preparatoryTouch",
|
||||
"preparatoryTouch",
|
||||
"innovation",
|
||||
"basicTouch",
|
||||
"standardTouch",
|
||||
"greatStrides",
|
||||
"byregotsBlessing",
|
||||
"basicSynth2"
|
||||
)
|
||||
);
|
||||
|
||||
let sol = find_quality_route(&routes).unwrap();
|
||||
assert_eq!(sol.steps, 23);
|
||||
assert_eq!(sol.quality, 12032);
|
||||
assert_eq!(sol.progression, 3675);
|
||||
assert_eq!(sol.durability, -5);
|
||||
assert_eq!(sol.cp, 3);
|
||||
assert_eq!(routes.1.step1_solutions, 9);
|
||||
assert_eq!(routes.1.step2_solutions, 21193);
|
||||
assert_eq!(routes.1.found_100_percent, true);
|
||||
assert_eq!(
|
||||
sol.actions,
|
||||
vec!(
|
||||
"muscleMemory",
|
||||
"manipulation",
|
||||
"veneration",
|
||||
"groundwork",
|
||||
"prudentSynthesis",
|
||||
"innovation",
|
||||
"prudentTouch",
|
||||
"basicTouch",
|
||||
"standardTouch",
|
||||
"advancedTouch",
|
||||
"manipulation",
|
||||
"innovation",
|
||||
"prudentTouch",
|
||||
"basicTouch",
|
||||
"standardTouch",
|
||||
"advancedTouch",
|
||||
"innovation",
|
||||
"basicTouch",
|
||||
"standardTouch",
|
||||
"advancedTouch",
|
||||
"greatStrides",
|
||||
"innovation",
|
||||
"byregotsBlessing",
|
||||
"basicSynth2"
|
||||
)
|
||||
);
|
||||
|
||||
let sol = find_safe_route(&routes).unwrap();
|
||||
assert_eq!(sol.steps, 22);
|
||||
assert_eq!(sol.quality, 11161);
|
||||
assert_eq!(sol.progression, 3675);
|
||||
assert_eq!(sol.durability, 10);
|
||||
assert_eq!(sol.cp, 4);
|
||||
assert_eq!(routes.1.step1_solutions, 9);
|
||||
assert_eq!(routes.1.step2_solutions, 21193);
|
||||
assert_eq!(routes.1.found_100_percent, true);
|
||||
assert_eq!(
|
||||
sol.actions,
|
||||
vec!(
|
||||
"muscleMemory",
|
||||
"manipulation",
|
||||
"veneration",
|
||||
"groundwork",
|
||||
"carefulSynthesis",
|
||||
"prudentTouch",
|
||||
"innovation",
|
||||
"prudentTouch",
|
||||
"prudentTouch",
|
||||
"prudentTouch",
|
||||
"prudentTouch",
|
||||
"manipulation",
|
||||
"innovation",
|
||||
"prudentTouch",
|
||||
"basicTouch",
|
||||
"standardTouch",
|
||||
"advancedTouch",
|
||||
"innovation",
|
||||
"basicTouch",
|
||||
"standardTouch",
|
||||
"greatStrides",
|
||||
"byregotsBlessing",
|
||||
"basicSynth2"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_load_from_config() {
|
||||
load_from_config("default_recipe", "craft.toml", "default_character");
|
||||
}
|
||||
|
||||
#[should_panic]
|
||||
#[test]
|
||||
pub fn test_bad_config_filename() {
|
||||
load_from_config("default_recipe", "nocrafto.toml", "default_character");
|
||||
}
|
||||
|
||||
#[should_panic]
|
||||
#[test]
|
||||
pub fn test_bad_config_recipename() {
|
||||
load_from_config("bad_recipe", "craft.toml", "default_character");
|
||||
}
|
||||
#[should_panic]
|
||||
#[test]
|
||||
pub fn test_bad_config_charname() {
|
||||
load_from_config("default_recipe", "craft.toml", "bad_character");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,337 @@
|
|||
#[cfg(not(feature="no_python"))]
|
||||
//! The binding module
|
||||
//! It contains the python bindings, and the structs
|
||||
//! needed to hold all parameters needed at runtime
|
||||
//!
|
||||
//! Making the bindings a build feature is a WIP
|
||||
|
||||
use crate::Craft;
|
||||
#[cfg(not(feature = "no_python"))]
|
||||
use crate::Parameters;
|
||||
use core::fmt::Display;
|
||||
use pyo3::prelude::*;
|
||||
|
||||
/// A final stripped down version of a craft
|
||||
/// used for final print and talking with python
|
||||
#[derive(Debug)]
|
||||
#[pyclass]
|
||||
pub struct SolverResult {
|
||||
/// The number of steps this particular craft takes
|
||||
#[pyo3(get)]
|
||||
pub steps: u32,
|
||||
/// The quality obtained at the end of the craft (absolute value)
|
||||
#[pyo3(get)]
|
||||
pub quality: u32,
|
||||
/// The amount of progression obtained at the end of the craft (absolute value)
|
||||
#[pyo3(get)]
|
||||
pub progression: u32,
|
||||
/// The remaining durability at the end of this craft
|
||||
#[pyo3(get)]
|
||||
pub durability: i32,
|
||||
/// The remaining crafting points at the end of this craft
|
||||
#[pyo3(get)]
|
||||
pub cp: i32,
|
||||
/// The total amount of crafting points the crafter had available (Deprecated)
|
||||
#[pyo3(get)]
|
||||
pub total_cp: u32,
|
||||
/// The total amount of progression needed to finish the craft (Deprecated)
|
||||
#[pyo3(get)]
|
||||
pub total_progression: u32,
|
||||
/// The total quality needed to make this craft 100% HQ (Deprecated)
|
||||
#[pyo3(get)]
|
||||
pub total_quality: u32,
|
||||
/// The total durability for this craft (Deprecated)
|
||||
#[pyo3(get)]
|
||||
pub total_durability: u32,
|
||||
/// The list of actions, as a string
|
||||
#[pyo3(get)]
|
||||
pub actions: Vec<String>,
|
||||
// /// The amount of solutions found during the first step of the solving (Used for debug) (Deprecated)
|
||||
// #[pyo3(get)]
|
||||
// pub step1_solutions: usize,
|
||||
// /// The amount of solutions found at the end of the second step of solving (Used for debug) (Deprecated)
|
||||
// #[pyo3(get)]
|
||||
// pub step2_solutions: usize,
|
||||
// #[pyo3(get)]
|
||||
// /// Wether a 100% HQ solution was found (Deprecated)
|
||||
// pub found_100_percent: bool,
|
||||
}
|
||||
|
||||
/// Global info on the execution
|
||||
#[derive(Debug)]
|
||||
#[pyclass]
|
||||
pub struct Info {
|
||||
/// The amount of solutions found during the first step of the solving (Used for debug) (Deprecated)
|
||||
#[pyo3(get)]
|
||||
pub step1_solutions: usize,
|
||||
/// The amount of solutions found at the end of the second step of solving (Used for debug) (Deprecated)
|
||||
#[pyo3(get)]
|
||||
pub step2_solutions: usize,
|
||||
#[pyo3(get)]
|
||||
/// Wether a 100% HQ solution was found (Deprecated)
|
||||
pub found_100_percent: bool,
|
||||
}
|
||||
|
||||
/// Solution information, contains information about the execution
|
||||
impl Info {
|
||||
/// Make a new information struct
|
||||
pub fn new(
|
||||
step1_solutions: usize,
|
||||
step2_solutions: usize,
|
||||
found_100_percent: bool,
|
||||
// params: &'Parameters
|
||||
) -> Self {
|
||||
Self {
|
||||
step1_solutions,
|
||||
step2_solutions,
|
||||
found_100_percent,
|
||||
}
|
||||
}
|
||||
|
||||
/// Default value of the info, only used for debug purposes
|
||||
pub fn default() -> Self {
|
||||
Self {
|
||||
step1_solutions: 0,
|
||||
step2_solutions: 0,
|
||||
found_100_percent: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Pretty display for SolverResult
|
||||
impl Display for SolverResult {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
||||
write!(f, "{:?}", self.actions)
|
||||
}
|
||||
}
|
||||
|
||||
impl SolverResult {
|
||||
/// Create a SolverResult from a solution
|
||||
/// Using this returns a solution, usable by Python
|
||||
pub fn from_craft(craft: &Craft) -> SolverResult {
|
||||
let mut actions = craft
|
||||
.actions
|
||||
.iter()
|
||||
.map(|action| format!("{}", action.short_name))
|
||||
.collect::<Vec<String>>();
|
||||
// Todo: Stop adding these by hand
|
||||
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,
|
||||
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 {
|
||||
/// Default method to create an empty solution, only used for debug purposes
|
||||
/// to test wether the import worked
|
||||
/// ```py
|
||||
/// import xiv_csolver_lib
|
||||
/// print(xiv_csolver_lib.default())
|
||||
/// ```
|
||||
#[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()],
|
||||
cp: 0,
|
||||
total_cp: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Implement a pretty_print method
|
||||
/// Mainly used for debug purposes
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
////// Python Bindings //////
|
||||
|
||||
/// A Python module implemented in Rust.
|
||||
#[cfg(not(feature = "no_python"))]
|
||||
#[pymodule]
|
||||
fn xiv_csolver_lib(_py: Python, m: &PyModule) -> PyResult<()> {
|
||||
m.add_function(wrap_pyfunction!(test_result, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(test_final_results, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(test_info, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(solve_from_python, m)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A test result, useful for debugging, all values are set to zero as per the
|
||||
/// [`default`](crate::python_bindings::SolverResult::default())
|
||||
/// ```
|
||||
/// # use xiv_csolver_lib::python_bindings::SolverResult;
|
||||
/// SolverResult {
|
||||
/// 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()],
|
||||
/// cp: 0,
|
||||
/// total_cp: 0,
|
||||
/// };
|
||||
/// ```
|
||||
#[cfg(not(feature = "no_python"))]
|
||||
#[pyfunction]
|
||||
pub fn test_result() -> SolverResult {
|
||||
SolverResult::default()
|
||||
}
|
||||
|
||||
/// A test info, useful for debugging, all values are set to zero as per the
|
||||
/// [`default`](crate::python_bindings::Info::default())
|
||||
/// ```
|
||||
/// # use xiv_csolver_lib::python_bindings::Info;
|
||||
/// Info {
|
||||
/// step1_solutions: 0,
|
||||
/// step2_solutions: 0,
|
||||
/// found_100_percent: false,
|
||||
/// };
|
||||
/// ```
|
||||
#[cfg(not(feature = "no_python"))]
|
||||
#[pyfunction]
|
||||
pub fn test_info() -> Info {
|
||||
Info::default()
|
||||
}
|
||||
|
||||
/// A test result array, useful for debugging, all values are set to zero as per the
|
||||
/// [`default`](crate::python_bindings::Info::default())
|
||||
/// ```
|
||||
/// # use xiv_csolver_lib::python_bindings::{Info};
|
||||
/// # use xiv_csolver_lib::python_bindings::SolverResult;
|
||||
/// (
|
||||
/// vec![SolverResult::default(), SolverResult::default()],
|
||||
/// Info::default(),
|
||||
/// );
|
||||
/// ```
|
||||
#[cfg(not(feature = "no_python"))]
|
||||
#[pyfunction]
|
||||
pub fn test_final_results() -> (Vec<SolverResult>, Info) {
|
||||
(
|
||||
vec![SolverResult::default(), SolverResult::default()],
|
||||
Info::default(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Create a stat struct stats with the base values
|
||||
#[cfg(not(feature = "no_python"))]
|
||||
use crate::{solve_craft, Recipe, Stats};
|
||||
|
||||
/// Solve a craft from parameters given by python
|
||||
/// The values are all obtained by a `&PyAny`, wich must guaranty that several attributes are
|
||||
/// accesible by `__getattr__`
|
||||
///
|
||||
/// ```python
|
||||
/// import xiv_craft_solver, rich
|
||||
///
|
||||
/// class FeedingClass:
|
||||
/// 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
|
||||
/// crafting_feeder = FeedingClass()
|
||||
/// rich.inspect(xiv_csolver_lib.solve_from_python(crafting_feeder))
|
||||
/// ```
|
||||
|
||||
#[cfg(not(feature = "no_python"))]
|
||||
#[pyfunction]
|
||||
pub fn solve_from_python(
|
||||
py: Python<'_>,
|
||||
values: &PyAny,
|
||||
) -> PyResult<Option<(Vec<SolverResult>, Info)>> {
|
||||
// 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()"));
|
||||
py.allow_threads(move || {
|
||||
let res = solve_craft(recipe, stats, param);
|
||||
Ok(res)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use crate::python_bindings::{test_final_results, test_info, test_result};
|
||||
|
||||
#[test]
|
||||
pub fn test_function_call() {
|
||||
test_final_results();
|
||||
test_info();
|
||||
test_result();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
161
src/solver.rs
|
|
@ -1,47 +1,84 @@
|
|||
use std::collections::VecDeque;
|
||||
use std::ops::Not;
|
||||
use crate::action::{Action, ACTIONS};
|
||||
use crate::craft::Craft;
|
||||
use crate::specs::Success;
|
||||
use std::collections::VecDeque;
|
||||
use std::ops::Not;
|
||||
|
||||
macro_rules! action_vec {
|
||||
($($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>> {
|
||||
if craft.success != Success::Pending { return vec![None]; }
|
||||
pub fn next_action_picker_1<'a>(craft: &Craft<'a>) -> Vec<Option<&'a Action>> {
|
||||
if craft.success != Success::Pending {
|
||||
return vec![None];
|
||||
}
|
||||
let mut available_actions = Vec::<Option<&'a Action>>::new();
|
||||
let mut forbidden_actions = Vec::<Option<&'a Action>>::new();
|
||||
|
||||
// Optimize the first three steps for massive time save
|
||||
if craft.step_count == 0 { return action_vec![ACTIONS.muscle_memory]; }
|
||||
if craft.step_count == 1 { return action_vec![ACTIONS.manipulation]; }
|
||||
// Optimize the first four steps for massive time save
|
||||
if craft.step_count == 0 {
|
||||
return action_vec![ACTIONS.muscle_memory];
|
||||
}
|
||||
if craft.step_count == 1 {
|
||||
return action_vec![ACTIONS.manipulation];
|
||||
}
|
||||
|
||||
// Prune some actions if not requested by --long
|
||||
if craft.step_count == 2 { return action_vec![/*ACTIONS.waste_not, ACTIONS.waste_not_ii, */ACTIONS.veneration]; }
|
||||
if craft.step_count == 3 { available_actions.append(&mut action_vec![ACTIONS.waste_not_ii/*,ACTIONS.waste_not*/]) }
|
||||
if craft.step_count == 2 {
|
||||
return action_vec![/* ACTIONS.waste_not, ACTIONS.waste_not_ii, */ ACTIONS.veneration];
|
||||
}
|
||||
if craft.step_count == 3 {
|
||||
available_actions.append(&mut action_vec![
|
||||
ACTIONS.waste_not_ii /* ,ACTIONS.waste_not */
|
||||
])
|
||||
}
|
||||
|
||||
// Groundwork mostly for wn / mm
|
||||
if craft.buffs.waste_not > 0 || craft.buffs.muscle_memory > 0 { available_actions.append(&mut action_vec![ACTIONS.groundwork]) }
|
||||
|
||||
if craft.buffs.waste_not > 0 || craft.buffs.muscle_memory > 0 {
|
||||
available_actions.append(&mut action_vec![ACTIONS.groundwork])
|
||||
}
|
||||
|
||||
// Forbidding actions depending on buffs
|
||||
if craft.buffs.muscle_memory > 0 { forbidden_actions.append(&mut action_vec![ACTIONS.basic_synthesis,ACTIONS.careful_synthesis,ACTIONS.prudent_synthesis,ACTIONS.delicate_synthesis]) }
|
||||
if craft.buffs.waste_not > 0 { forbidden_actions.append(&mut action_vec![ACTIONS.prudent_synthesis]) }
|
||||
available_actions.append(&mut action_vec![ACTIONS.basic_synthesis,ACTIONS.careful_synthesis,ACTIONS.prudent_synthesis,ACTIONS.delicate_synthesis]);
|
||||
|
||||
if craft.buffs.muscle_memory > 0 {
|
||||
forbidden_actions.append(&mut action_vec![
|
||||
ACTIONS.basic_synthesis,
|
||||
ACTIONS.careful_synthesis,
|
||||
ACTIONS.prudent_synthesis,
|
||||
ACTIONS.delicate_synthesis
|
||||
])
|
||||
}
|
||||
if craft.buffs.waste_not > 0 {
|
||||
forbidden_actions.append(&mut action_vec![ACTIONS.prudent_synthesis])
|
||||
}
|
||||
available_actions.append(&mut action_vec![
|
||||
ACTIONS.basic_synthesis,
|
||||
ACTIONS.careful_synthesis,
|
||||
ACTIONS.prudent_synthesis,
|
||||
ACTIONS.delicate_synthesis
|
||||
]);
|
||||
|
||||
// ACTIONS.groundwork for the --pls
|
||||
if craft.args.desperate{
|
||||
if craft.args.desperate {
|
||||
available_actions.append(&mut action_vec![ACTIONS.groundwork]);
|
||||
available_actions.append(&mut action_vec![ACTIONS.masters_mend]);
|
||||
}
|
||||
|
||||
// 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 && craft.buffs.waste_not == 0 {
|
||||
available_actions.append(&mut action_vec![ACTIONS.waste_not_ii, ACTIONS.waste_not])
|
||||
};
|
||||
|
||||
// Pruning the actions with the forbidden ones
|
||||
let mut result_actions = Vec::<Option<&'a Action>>::new();
|
||||
for action in available_actions {
|
||||
if !forbidden_actions.contains(&action) && action.unwrap().can_use(&craft) && result_actions.iter().any(|x| x.unwrap() == action.unwrap()).not() {
|
||||
if !forbidden_actions.contains(&action)
|
||||
&& action.unwrap().can_use(&craft)
|
||||
&& result_actions
|
||||
.iter()
|
||||
.any(|x| x.unwrap() == action.unwrap())
|
||||
.not()
|
||||
{
|
||||
result_actions.push(action);
|
||||
}
|
||||
}
|
||||
|
|
@ -49,7 +86,6 @@ pub fn next_action_picker_1<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
|
|||
result_actions
|
||||
}
|
||||
|
||||
|
||||
/// Find all routes that can finish in one more action
|
||||
pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec<Craft<'a>> {
|
||||
let mut queue = Vec::new();
|
||||
|
|
@ -57,23 +93,25 @@ pub fn generate_routes_phase1<'a>(craft: Craft<'a>) -> Vec<Craft<'a>> {
|
|||
let mut routes = Vec::new();
|
||||
while !queue.is_empty() {
|
||||
let craft = queue.pop().unwrap();
|
||||
for action in next_action_picker_1(& craft) {
|
||||
for action in next_action_picker_1(&craft) {
|
||||
let mut craft = craft.clone();
|
||||
|
||||
match action{
|
||||
match action {
|
||||
Some(a) => craft.run_action(a),
|
||||
None => break,
|
||||
};
|
||||
|
||||
let remaining_prog = (craft.recipe.progress as f32 - craft.progression as f32) / craft.get_base_progression() as f32;
|
||||
let remaining_prog = (craft.recipe.progress as f32 - craft.progression as f32)
|
||||
/ craft.get_base_progression() as f32;
|
||||
if remaining_prog <= 2.0 {
|
||||
if remaining_prog <= 0.0 {
|
||||
continue;
|
||||
} else if 0.0 < remaining_prog && remaining_prog <= 1.2 {
|
||||
// pass // Will finish with basicSynth2 (free)
|
||||
} else if 1.2 < remaining_prog && remaining_prog <= 1.2 {
|
||||
craft.cp -= 7; // Will finish with carefulSynthesis (7cp)
|
||||
} else if 1.2 < remaining_prog && remaining_prog <= 2.0 {
|
||||
// TODO: Test replacing this value with 1.8 that should be the correct value but hasnt be tested
|
||||
// } else if 1.2 < remaining_prog && remaining_prog <= 1.4 {
|
||||
// craft.cp -= 7; // Will finish with carefulSynthesis (7cp)
|
||||
} else if 1.4 < remaining_prog && remaining_prog <= 2.0 {
|
||||
craft.cp -= 12; // Will finish with observe+focusedSynthesis (12cp)
|
||||
}
|
||||
craft.durability -= 10; // Save the final step, since we always aim to end with -5dur, it doesn't matter
|
||||
|
|
@ -85,33 +123,46 @@ 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
|
||||
// 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
|
||||
if craft.step_count < craft.args.depth { queue.push(craft); }
|
||||
if craft.step_count < craft.args.depth {
|
||||
queue.push(craft);
|
||||
}
|
||||
}
|
||||
}
|
||||
routes
|
||||
}
|
||||
|
||||
|
||||
/// Find the list of authorised actions for this step
|
||||
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];
|
||||
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 forbidden_actions = Vec::new();
|
||||
if craft.success != Success::Pending { return vec![None]; }
|
||||
if craft.success != Success::Pending {
|
||||
return vec![None];
|
||||
}
|
||||
if craft.buffs.innovation > 0 {
|
||||
forbidden_actions.push(&ACTIONS.innovation);
|
||||
} else {
|
||||
if craft.buffs.inner_quiet >= 2 {
|
||||
forbidden_actions.append(&mut vec![&ACTIONS.basic_touch,
|
||||
&ACTIONS.standard_touch,
|
||||
&ACTIONS.advanced_touch,
|
||||
&ACTIONS.trained_finesse,
|
||||
&ACTIONS.prudent_touch,
|
||||
&ACTIONS.preparatory_touch,
|
||||
&ACTIONS.byregot_blessing]);
|
||||
forbidden_actions.append(&mut vec![
|
||||
&ACTIONS.basic_touch,
|
||||
&ACTIONS.standard_touch,
|
||||
&ACTIONS.advanced_touch,
|
||||
&ACTIONS.trained_finesse,
|
||||
&ACTIONS.prudent_touch,
|
||||
&ACTIONS.preparatory_touch,
|
||||
&ACTIONS.byregot_blessing,
|
||||
]);
|
||||
}
|
||||
available_actions.push(&ACTIONS.innovation);
|
||||
}
|
||||
if craft.buffs.manipulation == 0 && craft.buffs.basic_touch == 0 && craft.buffs.standard_touch == 0 && craft.buffs.inner_quiet < 8 {
|
||||
if craft.buffs.manipulation == 0
|
||||
&& craft.buffs.basic_touch == 0
|
||||
&& craft.buffs.standard_touch == 0
|
||||
&& craft.buffs.inner_quiet < 8
|
||||
{
|
||||
available_actions.push(&ACTIONS.manipulation);
|
||||
}
|
||||
if craft.buffs.waste_not > 0 {
|
||||
|
|
@ -129,8 +180,9 @@ pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
|
|||
available_actions.push(&ACTIONS.advanced_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)
|
||||
if craft.buffs.inner_quiet >= craft.args.byregot_step { // 10
|
||||
|
||||
if craft.buffs.inner_quiet >= craft.args.byregot_step {
|
||||
// 10
|
||||
available_actions.push(&ACTIONS.trained_finesse);
|
||||
available_actions.push(&ACTIONS.great_strides);
|
||||
}
|
||||
|
|
@ -141,10 +193,15 @@ pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
|
|||
available_actions.push(&ACTIONS.byregot_blessing);
|
||||
}
|
||||
}
|
||||
// if craft.durability + 30 < craft.recipe.durability as i32{
|
||||
// available_actions.push(&ACTIONS.masters_mend);
|
||||
// }
|
||||
let mut final_actions: Vec<Option<&Action>> = Vec::new();
|
||||
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
|
@ -154,8 +211,7 @@ pub fn next_action_phase_2<'a>(craft: & Craft<'a>) -> Vec<Option<&'a Action>> {
|
|||
/// 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();
|
||||
|
||||
// Todo: Return a vec of relevant functions, instead of the most quality one
|
||||
|
||||
let mut top_route: Craft<'a> = craft.clone(); // Default route, no hq on that one
|
||||
let mut top_routes: Vec<Craft<'a>> = vec![];
|
||||
|
||||
|
|
@ -164,18 +220,21 @@ pub fn generate_routes_phase2<'a>(craft: Craft<'a>) -> Option<Vec<Craft<'a>>> {
|
|||
while !queue.is_empty() {
|
||||
let _craft = queue.pop_front().unwrap();
|
||||
for action in next_action_phase_2(&_craft) {
|
||||
if _craft.success != Success::Pending || action.is_none() || !action.unwrap().can_use(&_craft) {
|
||||
if _craft.success != Success::Pending
|
||||
|| action.is_none()
|
||||
|| !action.unwrap().can_use(&_craft)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut craft = _craft.clone();
|
||||
craft.run_action(action.unwrap());
|
||||
if action.unwrap() == &ACTIONS.byregot_blessing {
|
||||
#[cfg(not(feature="fast"))]
|
||||
if top_route.quality>=craft.recipe.quality{
|
||||
top_routes.push(craft.clone()); // Me memory
|
||||
#[cfg(not(feature = "fast"))]
|
||||
if top_route.quality >= craft.recipe.quality {
|
||||
top_routes.push(craft.clone()); // Me memory
|
||||
}
|
||||
if top_route.quality < craft.quality {
|
||||
#[cfg(feature="fast")]
|
||||
#[cfg(feature = "fast")]
|
||||
top_routes.push(craft.clone());
|
||||
top_route = craft;
|
||||
}
|
||||
|
|
@ -187,4 +246,6 @@ pub fn generate_routes_phase2<'a>(craft: Craft<'a>) -> Option<Vec<Craft<'a>>> {
|
|||
// Let's not forget the best result
|
||||
top_routes.push(top_route);
|
||||
Some(top_routes)
|
||||
}
|
||||
}
|
||||
|
||||
mod test_solver;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,391 @@
|
|||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
pub fn test_first_step() {
|
||||
let mut craft = crate::craft::Craft::two_star();
|
||||
// Try a failed craft
|
||||
craft.success = crate::specs::Success::Failure;
|
||||
let vact = next_action_picker_1(&craft);
|
||||
assert_eq!(vact, vec![None]);
|
||||
craft.success = crate::specs::Success::Pending;
|
||||
|
||||
// Try the first 4 steps
|
||||
let vact = next_action_picker_1(&craft);
|
||||
assert_eq!(vact, action_vec![ACTIONS.muscle_memory]);
|
||||
craft.run_action(&ACTIONS.muscle_memory);
|
||||
|
||||
let vact = next_action_picker_1(&craft);
|
||||
assert_eq!(vact, action_vec![ACTIONS.manipulation]);
|
||||
craft.run_action(&ACTIONS.manipulation);
|
||||
|
||||
let vact = next_action_picker_1(&craft);
|
||||
assert_eq!(vact, action_vec![ACTIONS.veneration]);
|
||||
craft.run_action(&ACTIONS.veneration);
|
||||
|
||||
let vact = next_action_picker_1(&craft);
|
||||
assert_eq!(vact, action_vec![ACTIONS.waste_not_ii, ACTIONS.groundwork]);
|
||||
craft.run_action(&ACTIONS.waste_not_ii);
|
||||
|
||||
// Try the steps 5-8, deterministically
|
||||
let vact = next_action_picker_1(&craft);
|
||||
assert_eq!(vact, action_vec![ACTIONS.groundwork]);
|
||||
craft.run_action(&ACTIONS.careful_synthesis);
|
||||
|
||||
let vact = next_action_picker_1(&craft);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![
|
||||
ACTIONS.groundwork,
|
||||
ACTIONS.basic_synthesis,
|
||||
ACTIONS.careful_synthesis,
|
||||
ACTIONS.delicate_synthesis
|
||||
]
|
||||
);
|
||||
craft.run_action(&ACTIONS.careful_synthesis);
|
||||
|
||||
let vact = next_action_picker_1(&craft);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![
|
||||
ACTIONS.groundwork,
|
||||
ACTIONS.basic_synthesis,
|
||||
ACTIONS.careful_synthesis,
|
||||
ACTIONS.delicate_synthesis
|
||||
]
|
||||
);
|
||||
craft.run_action(&ACTIONS.careful_synthesis);
|
||||
|
||||
let vact = next_action_picker_1(&craft);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![
|
||||
ACTIONS.groundwork,
|
||||
ACTIONS.basic_synthesis,
|
||||
ACTIONS.careful_synthesis,
|
||||
ACTIONS.delicate_synthesis
|
||||
]
|
||||
);
|
||||
craft.run_action(&ACTIONS.careful_synthesis);
|
||||
|
||||
// Check odd parameters
|
||||
craft.buffs.waste_not = 0;
|
||||
craft.progression = 0;
|
||||
let vact = next_action_picker_1(&craft);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![
|
||||
ACTIONS.basic_synthesis,
|
||||
ACTIONS.careful_synthesis,
|
||||
ACTIONS.prudent_synthesis,
|
||||
ACTIONS.delicate_synthesis
|
||||
]
|
||||
);
|
||||
craft.run_action(&ACTIONS.delicate_synthesis);
|
||||
|
||||
let vact = next_action_picker_1(&craft);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![
|
||||
ACTIONS.basic_synthesis,
|
||||
ACTIONS.careful_synthesis,
|
||||
ACTIONS.prudent_synthesis,
|
||||
ACTIONS.delicate_synthesis,
|
||||
ACTIONS.waste_not_ii,
|
||||
ACTIONS.waste_not
|
||||
]
|
||||
);
|
||||
|
||||
craft.args.desperate = true;
|
||||
let vact = next_action_picker_1(&craft);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![
|
||||
ACTIONS.basic_synthesis,
|
||||
ACTIONS.careful_synthesis,
|
||||
ACTIONS.prudent_synthesis,
|
||||
ACTIONS.delicate_synthesis,
|
||||
ACTIONS.groundwork,
|
||||
ACTIONS.masters_mend,
|
||||
ACTIONS.waste_not_ii,
|
||||
ACTIONS.waste_not
|
||||
]
|
||||
);
|
||||
assert_eq!(craft.progression, 250);
|
||||
assert_eq!(craft.quality, 266);
|
||||
assert_eq!(craft.cp, 317);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_routes_p1() {
|
||||
let craft = crate::craft::Craft::two_star();
|
||||
let mut routes1 = generate_routes_phase1(craft);
|
||||
|
||||
for route in routes1.iter() {
|
||||
println!("{:?}", route.actions);
|
||||
}
|
||||
// Literrally any change will break it
|
||||
// An eq should be implmented to just check a vector of vector versus a route
|
||||
assert_eq!(routes1.len(), 9);
|
||||
let route = routes1.pop().unwrap();
|
||||
assert_eq!(
|
||||
route.actions,
|
||||
vec![
|
||||
&ACTIONS.muscle_memory,
|
||||
&ACTIONS.manipulation,
|
||||
&ACTIONS.veneration,
|
||||
&ACTIONS.waste_not_ii,
|
||||
&ACTIONS.groundwork,
|
||||
&ACTIONS.delicate_synthesis,
|
||||
&ACTIONS.delicate_synthesis
|
||||
]
|
||||
);
|
||||
|
||||
let route = routes1.pop().unwrap();
|
||||
assert_eq!(
|
||||
route.actions,
|
||||
vec![
|
||||
&ACTIONS.muscle_memory,
|
||||
&ACTIONS.manipulation,
|
||||
&ACTIONS.veneration,
|
||||
&ACTIONS.waste_not_ii,
|
||||
&ACTIONS.groundwork,
|
||||
&ACTIONS.delicate_synthesis,
|
||||
&ACTIONS.basic_synthesis,
|
||||
]
|
||||
);
|
||||
|
||||
let route = routes1.pop().unwrap();
|
||||
assert_eq!(
|
||||
route.actions,
|
||||
vec![
|
||||
&ACTIONS.muscle_memory,
|
||||
&ACTIONS.manipulation,
|
||||
&ACTIONS.veneration,
|
||||
&ACTIONS.waste_not_ii,
|
||||
&ACTIONS.groundwork,
|
||||
&ACTIONS.careful_synthesis
|
||||
]
|
||||
);
|
||||
|
||||
let route = routes1.pop().unwrap();
|
||||
assert_eq!(
|
||||
route.actions,
|
||||
vec![
|
||||
&ACTIONS.muscle_memory,
|
||||
&ACTIONS.manipulation,
|
||||
&ACTIONS.veneration,
|
||||
&ACTIONS.waste_not_ii,
|
||||
&ACTIONS.groundwork,
|
||||
&ACTIONS.basic_synthesis
|
||||
]
|
||||
);
|
||||
|
||||
let route = routes1.pop().unwrap();
|
||||
assert_eq!(
|
||||
route.actions,
|
||||
vec![
|
||||
&ACTIONS.muscle_memory,
|
||||
&ACTIONS.manipulation,
|
||||
&ACTIONS.veneration,
|
||||
&ACTIONS.groundwork,
|
||||
&ACTIONS.delicate_synthesis,
|
||||
&ACTIONS.delicate_synthesis
|
||||
]
|
||||
);
|
||||
|
||||
let route = routes1.pop().unwrap();
|
||||
assert_eq!(
|
||||
route.actions,
|
||||
vec![
|
||||
&ACTIONS.muscle_memory,
|
||||
&ACTIONS.manipulation,
|
||||
&ACTIONS.veneration,
|
||||
&ACTIONS.groundwork,
|
||||
&ACTIONS.delicate_synthesis,
|
||||
&ACTIONS.basic_synthesis
|
||||
]
|
||||
);
|
||||
|
||||
let route = routes1.pop().unwrap();
|
||||
assert_eq!(
|
||||
route.actions,
|
||||
vec![
|
||||
&ACTIONS.muscle_memory,
|
||||
&ACTIONS.manipulation,
|
||||
&ACTIONS.veneration,
|
||||
&ACTIONS.groundwork,
|
||||
&ACTIONS.prudent_synthesis
|
||||
]
|
||||
);
|
||||
|
||||
let route = routes1.pop().unwrap();
|
||||
assert_eq!(
|
||||
route.actions,
|
||||
vec![
|
||||
&ACTIONS.muscle_memory,
|
||||
&ACTIONS.manipulation,
|
||||
&ACTIONS.veneration,
|
||||
&ACTIONS.groundwork,
|
||||
&ACTIONS.careful_synthesis
|
||||
]
|
||||
);
|
||||
|
||||
let route = routes1.pop().unwrap();
|
||||
assert_eq!(
|
||||
route.actions,
|
||||
vec![
|
||||
&ACTIONS.muscle_memory,
|
||||
&ACTIONS.manipulation,
|
||||
&ACTIONS.veneration,
|
||||
&ACTIONS.groundwork,
|
||||
&ACTIONS.basic_synthesis
|
||||
]
|
||||
);
|
||||
|
||||
let route = routes1.pop();
|
||||
assert!(route.is_none());
|
||||
}
|
||||
|
||||
// Test Custom routes (None and basic synthesis)
|
||||
#[test]
|
||||
pub fn test_custom_p1_routes() {
|
||||
// None route, no more actions
|
||||
let mut craft = crate::craft::Craft::zero_star();
|
||||
craft.success = crate::specs::Success::Failure;
|
||||
let routes1 = generate_routes_phase1(craft.clone());
|
||||
assert!(routes1.is_empty());
|
||||
}
|
||||
|
||||
// Test step 2 route-finding
|
||||
#[test]
|
||||
pub fn test_second_step() {
|
||||
let mut craft = crate::craft::Craft::two_star();
|
||||
craft.cp = 10000;
|
||||
let mut routes1 = generate_routes_phase1(craft);
|
||||
let mut craft2 = routes1.pop().unwrap();
|
||||
let vact = next_action_phase_2(&craft2);
|
||||
assert_eq!(vact, action_vec![ACTIONS.innovation]);
|
||||
craft2.run_action(&ACTIONS.innovation);
|
||||
|
||||
let vact = next_action_phase_2(&craft2);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![ACTIONS.basic_touch, ACTIONS.preparatory_touch]
|
||||
);
|
||||
craft2.run_action(&ACTIONS.basic_touch);
|
||||
|
||||
let vact = next_action_phase_2(&craft2);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![ACTIONS.preparatory_touch, ACTIONS.standard_touch]
|
||||
);
|
||||
craft2.run_action(&ACTIONS.standard_touch);
|
||||
|
||||
let vact = next_action_phase_2(&craft2);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![ACTIONS.preparatory_touch, ACTIONS.advanced_touch]
|
||||
);
|
||||
craft2.run_action(&ACTIONS.advanced_touch);
|
||||
|
||||
let vact = next_action_phase_2(&craft2);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![
|
||||
ACTIONS.basic_touch,
|
||||
ACTIONS.preparatory_touch,
|
||||
ACTIONS.manipulation
|
||||
]
|
||||
);
|
||||
craft2.run_action(&ACTIONS.manipulation);
|
||||
|
||||
let vact = next_action_phase_2(&craft2);
|
||||
assert_eq!(vact, action_vec![ACTIONS.innovation]);
|
||||
craft2.run_action(&ACTIONS.innovation);
|
||||
|
||||
let vact = next_action_phase_2(&craft2);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![ACTIONS.basic_touch, ACTIONS.prudent_touch]
|
||||
);
|
||||
craft2.run_action(&ACTIONS.basic_touch);
|
||||
|
||||
let vact = next_action_phase_2(&craft2);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![ACTIONS.prudent_touch, ACTIONS.standard_touch]
|
||||
);
|
||||
craft2.run_action(&ACTIONS.prudent_touch);
|
||||
|
||||
let vact = next_action_phase_2(&craft2);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![ACTIONS.basic_touch, ACTIONS.prudent_touch]
|
||||
);
|
||||
craft2.run_action(&ACTIONS.prudent_touch);
|
||||
|
||||
let vact = next_action_phase_2(&craft2);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![ACTIONS.basic_touch, ACTIONS.prudent_touch]
|
||||
);
|
||||
craft2.run_action(&ACTIONS.prudent_touch);
|
||||
|
||||
let vact = next_action_phase_2(&craft2);
|
||||
assert_eq!(vact, action_vec![ACTIONS.innovation]);
|
||||
craft2.run_action(&ACTIONS.innovation);
|
||||
|
||||
let vact = next_action_phase_2(&craft2);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![ACTIONS.basic_touch, ACTIONS.prudent_touch]
|
||||
);
|
||||
craft2.run_action(&ACTIONS.prudent_touch);
|
||||
|
||||
let vact = next_action_phase_2(&craft2);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![
|
||||
ACTIONS.basic_touch,
|
||||
ACTIONS.prudent_touch,
|
||||
ACTIONS.trained_finesse,
|
||||
ACTIONS.great_strides
|
||||
]
|
||||
);
|
||||
craft2.run_action(&ACTIONS.great_strides);
|
||||
|
||||
let vact = next_action_phase_2(&craft2);
|
||||
assert_eq!(
|
||||
vact,
|
||||
action_vec![
|
||||
ACTIONS.basic_touch,
|
||||
ACTIONS.prudent_touch,
|
||||
ACTIONS.byregot_blessing
|
||||
]
|
||||
);
|
||||
|
||||
craft2.run_action(&ACTIONS.byregot_blessing);
|
||||
craft2.success = crate::specs::Success::Success;
|
||||
assert_eq!(next_action_phase_2(&craft2), vec![None]);
|
||||
assert_eq!(craft2.progression, 3750);
|
||||
assert_eq!(craft2.quality, 9899);
|
||||
assert_eq!(craft2.cp, 9322);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_generate_routes_p2() {
|
||||
let craft = crate::craft::Craft::two_star();
|
||||
let mut routes1 = generate_routes_phase1(craft);
|
||||
let craft1 = routes1.pop().unwrap();
|
||||
let routes2 = generate_routes_phase2(craft1);
|
||||
assert_eq!(routes2.unwrap().len(), 241);
|
||||
|
||||
// Any modification on the solving will break this test, same as before,
|
||||
// maybe having a range of expected solution instead is the way to go.
|
||||
|
||||
// Nonetheless the solver test will add qualitative testing so some
|
||||
// results will be thoughrouly checked
|
||||
|
||||
// Maybe sampling a handful results and expect them to always exits could also work
|
||||
}
|
||||
181
src/specs.rs
|
|
@ -1,56 +1,106 @@
|
|||
use std::fmt::{Debug};
|
||||
//! This modules instanciate all the tools needed to load and use the solver
|
||||
|
||||
use std::fmt::Debug;
|
||||
use strum_macros::EnumIter;
|
||||
|
||||
|
||||
/// The recipe to craft
|
||||
/// On some websites the fields are instead called
|
||||
/// [Progress, quality, durability, progress difficulty, quality difficulty, extra progress difficulty, extra quality difficulty]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Recipe {
|
||||
/// The recipe durability (also called solidity) (35, 40, 70 or 80 usually)
|
||||
pub durability: u32,
|
||||
/// The total recipe progress needed
|
||||
pub progress: u32,
|
||||
/// The total recipe quality
|
||||
pub quality: u32,
|
||||
/// How much the progress is hard to set,
|
||||
/// it's an (hidden) extra progress multiplier,
|
||||
/// inflicting a -10% to -30% to starred recipes
|
||||
/// Also called `progress_difficulty`
|
||||
pub progress_divider: u32,
|
||||
/// The same (hidden) difficulty multiplier, for quality
|
||||
/// Also called `progress_difficulty`
|
||||
pub quality_divider: u32,
|
||||
/// Modifies how much the base stats are affecting the craft progress
|
||||
/// Also called `progress_extra_difficulty`
|
||||
pub progress_modifier: u32,
|
||||
/// Modifies how much the base stats are affectif the craft quality
|
||||
/// Also called `quality_extra_difficulty`
|
||||
pub quality_modifier: u32,
|
||||
}
|
||||
|
||||
|
||||
/// The craftsman stats
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Stats {
|
||||
/// The craftsmanship, influences the progress
|
||||
pub craftsmanship: u32,
|
||||
/// The control, inluences the quality
|
||||
pub control: u32,
|
||||
/// The amount of cp, ressource used for actions
|
||||
pub max_cp: u32,
|
||||
}
|
||||
|
||||
/// The buffs available for the crafter
|
||||
#[derive(Debug, Clone, Copy, PartialEq, EnumIter)]
|
||||
pub enum Buff {
|
||||
/// Gain a stack of Inner Quiet with every increase in quality, up to a maximum of 10.
|
||||
/// Grants a 10% bonus to the efficiency of Touch actions for each stack.
|
||||
InnerQuiet,
|
||||
/// Reduces loss of durability by 50%.
|
||||
WasteNot,
|
||||
/// Increases the efficiency of next Touch action by 100%.
|
||||
GreatStrides,
|
||||
/// Increases efficiency of Touch actions by 50%.
|
||||
Innovation,
|
||||
/// Increases efficiency of Synthesis actions by 50%.
|
||||
Veneration,
|
||||
/// Restores 5 points of durability after each step.
|
||||
Manipulation,
|
||||
/// Increases progress.
|
||||
/// Efficiency: 300%
|
||||
/// Success Rate: 100%
|
||||
/// Additional Effect: Efficiency of your next Synthesis action is increased by 100%
|
||||
/// Available only on the first step.
|
||||
/// Additional effect is active for five steps.
|
||||
MuscleMemory,
|
||||
// v Hidden v
|
||||
/// (Hidden) Combo with Standart touch costs 18 cp.
|
||||
BasicTouch,
|
||||
/// (Hidden) Combo with Advanced touch costs 18 cp.
|
||||
StandardTouch,
|
||||
/// (Hidden) Do nothing for one step.
|
||||
Observe,
|
||||
}
|
||||
|
||||
/// Keeps track of all the durations remaining on all buffs
|
||||
/// Also called buff tracker in the docs
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct BuffState {
|
||||
/// Caps at 10 for a 100% extra efficiency in quality increase
|
||||
pub inner_quiet: u8,
|
||||
/// Lasts for four steps if Waste not was used, height if Waste Not II was.
|
||||
pub waste_not: u8,
|
||||
/// Effect active for three steps, dissipates after a quality action is used.
|
||||
pub great_strides: u8,
|
||||
/// Lasts four steps
|
||||
pub innovation: u8,
|
||||
/// Lasts four steps.
|
||||
pub veneration: u8,
|
||||
/// Lasts height steps
|
||||
pub manipulation: u8,
|
||||
/// Lasts five steps, dissipate after a progression action is used.
|
||||
pub muscle_memory: u8,
|
||||
/// Lasts one step
|
||||
pub basic_touch: u8,
|
||||
/// Lasts one step
|
||||
pub standard_touch: u8,
|
||||
/// Lasts one step
|
||||
pub observe: u8,
|
||||
}
|
||||
|
||||
impl BuffState {
|
||||
/// Default state of buffs (all at zero) as per the beggining of craft
|
||||
pub fn default() -> Self {
|
||||
Self {
|
||||
inner_quiet: 0,
|
||||
|
|
@ -66,6 +116,7 @@ impl BuffState {
|
|||
}
|
||||
}
|
||||
|
||||
/// Remove the given buff from the buff tracker
|
||||
pub fn remove(&mut self, buff: Buff) {
|
||||
match buff {
|
||||
Buff::InnerQuiet => self.inner_quiet = 0,
|
||||
|
|
@ -81,6 +132,8 @@ impl BuffState {
|
|||
}
|
||||
}
|
||||
|
||||
/// Apply the given buff to the buff tracker for `value` steps
|
||||
/// In the case of Inner Quiet, it inseads adds one to the stack counter
|
||||
pub fn apply(&mut self, buff: Buff, value: u8) {
|
||||
match buff {
|
||||
Buff::InnerQuiet => {
|
||||
|
|
@ -98,25 +151,127 @@ impl BuffState {
|
|||
Buff::MuscleMemory => self.muscle_memory = value,
|
||||
Buff::BasicTouch => self.basic_touch = value,
|
||||
Buff::StandardTouch => self.standard_touch = value,
|
||||
Buff::Observe => self.standard_touch = value,
|
||||
Buff::Observe => self.observe = value,
|
||||
}
|
||||
}
|
||||
|
||||
/// Tick downs the remaining duration of all buffs, if up
|
||||
pub fn tick(&mut self) {
|
||||
if self.waste_not > 0 { self.waste_not -= 1; }
|
||||
if self.great_strides > 0 { self.great_strides -= 1; }
|
||||
if self.innovation > 0 { self.innovation -= 1; }
|
||||
if self.veneration > 0 { self.veneration -= 1; }
|
||||
if self.manipulation > 0 { self.manipulation -= 1; }
|
||||
if self.muscle_memory > 0 { self.muscle_memory -= 1; }
|
||||
if self.basic_touch > 0 { self.basic_touch -= 1; }
|
||||
if self.standard_touch > 0 { self.standard_touch -= 1; }
|
||||
if self.waste_not > 0 {
|
||||
self.waste_not -= 1;
|
||||
}
|
||||
if self.great_strides > 0 {
|
||||
self.great_strides -= 1;
|
||||
}
|
||||
if self.innovation > 0 {
|
||||
self.innovation -= 1;
|
||||
}
|
||||
if self.veneration > 0 {
|
||||
self.veneration -= 1;
|
||||
}
|
||||
if self.manipulation > 0 {
|
||||
self.manipulation -= 1;
|
||||
}
|
||||
if self.muscle_memory > 0 {
|
||||
self.muscle_memory -= 1;
|
||||
}
|
||||
if self.basic_touch > 0 {
|
||||
self.basic_touch -= 1;
|
||||
}
|
||||
if self.standard_touch > 0 {
|
||||
self.standard_touch -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
/// State the craft is in, used to keep track of wether the craft
|
||||
/// is to be worked on, added to the success vector or discarded
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Success {
|
||||
/// Pending success and therefor still ongoing
|
||||
Pending,
|
||||
/// Finised, not ongoing and finished without breaking (Doens't take quality into account)
|
||||
Success,
|
||||
/// Finised because of lack of remaining durability
|
||||
Failure,
|
||||
}
|
||||
|
||||
// Test unit
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
// Test default values
|
||||
use pretty_assertions::assert_eq;
|
||||
use strum::IntoEnumIterator;
|
||||
|
||||
#[test]
|
||||
pub fn test_structs() {
|
||||
format!(
|
||||
"{:?}",
|
||||
crate::specs::Recipe {
|
||||
durability: 0,
|
||||
progress: 0,
|
||||
progress_divider: 0,
|
||||
progress_modifier: 0,
|
||||
quality: 0,
|
||||
quality_divider: 0,
|
||||
quality_modifier: 0,
|
||||
}
|
||||
.clone()
|
||||
);
|
||||
|
||||
format!(
|
||||
"{:?}",
|
||||
crate::specs::Stats {
|
||||
craftsmanship: 0,
|
||||
control: 0,
|
||||
max_cp: 0,
|
||||
}
|
||||
.clone()
|
||||
);
|
||||
|
||||
let iq = crate::specs::Buff::InnerQuiet;
|
||||
assert_eq!(crate::specs::Buff::InnerQuiet, iq);
|
||||
for buff in crate::specs::Buff::iter() {
|
||||
format!("{:?}", buff);
|
||||
}
|
||||
format!("{:?}", crate::specs::BuffState::default().clone());
|
||||
|
||||
let sc = crate::specs::Success::Pending;
|
||||
assert!(crate::specs::Success::Pending == sc);
|
||||
assert!(crate::specs::Success::Success != sc);
|
||||
format!("{:?}", sc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn test_buffstate() {
|
||||
let mut bbs = crate::specs::BuffState::default();
|
||||
for buff in crate::specs::Buff::iter() {
|
||||
bbs.apply(buff, 2);
|
||||
}
|
||||
assert_eq!(bbs.inner_quiet, 2);
|
||||
assert_eq!(bbs.waste_not, 2);
|
||||
assert_eq!(bbs.great_strides, 2);
|
||||
assert_eq!(bbs.innovation, 2);
|
||||
assert_eq!(bbs.veneration, 2);
|
||||
assert_eq!(bbs.manipulation, 2);
|
||||
assert_eq!(bbs.muscle_memory, 2);
|
||||
assert_eq!(bbs.basic_touch, 2);
|
||||
assert_eq!(bbs.standard_touch, 2);
|
||||
assert_eq!(bbs.observe, 2);
|
||||
bbs.apply(crate::specs::Buff::InnerQuiet, 0);
|
||||
bbs.apply(crate::specs::Buff::Innovation, 5);
|
||||
assert_eq!(bbs.inner_quiet, 0);
|
||||
assert_eq!(bbs.innovation, 5);
|
||||
bbs.apply(crate::specs::Buff::InnerQuiet, 2);
|
||||
bbs.apply(crate::specs::Buff::InnerQuiet, 1);
|
||||
assert_eq!(bbs.inner_quiet, 3);
|
||||
bbs.tick();
|
||||
assert_eq!(bbs.inner_quiet, 3);
|
||||
assert_eq!(bbs.innovation, 4);
|
||||
for buff in crate::specs::Buff::iter() {
|
||||
bbs.remove(buff);
|
||||
}
|
||||
assert_eq!(bbs.inner_quiet, 0);
|
||||
assert_eq!(bbs.innovation, 0);
|
||||
}
|
||||
}
|
||||
|
|
|
|||