pyoe2-craftpath 0.5.1

A tool for Path of Exile 2 to find the best craftpaths based on the categories: *most likely, most efficient and cheapest*, between a starting item and a target item.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use num_format::{Locale, ToFormattedString};

#[cfg(feature = "python")]
use crate::api::calculator::DynStatisticAnalyzerPaths;
use crate::{
    api::{
        calculator::{self, Calculator, GroupRoute, ItemRoute, StatisticAnalyzerPaths},
        currency::CraftCurrencyList,
        provider::{
            item_info::ItemInfoProvider,
            market_prices::{MarketPriceProvider, PriceInDivines, PriceKind},
        },
        types::{
            AffixClassEnum, AffixLocationEnum, AffixSpecifier, AffixTierLevelBoundsEnum,
            BaseItemId, THashSet,
        },
    },
    calc::statistics::presets::statistic_analyzer_currency_group_presets::StatisticAnalyzerCurrencyGroupPreset,
    utils::fraction_utils::Fraction,
};
use std::fmt::Write;

impl ItemRoute {
    pub fn locate_group<'a>(
        &self,
        calculated_groups: &'a Vec<GroupRoute>,
    ) -> Option<&'a GroupRoute> {
        let curr = self
            .route
            .iter()
            .map(|e| e.currency_list.clone())
            .collect::<Vec<CraftCurrencyList>>();

        let found = calculated_groups
            .iter()
            .find(|test| test.group.as_slice() == curr.as_slice());

        found
    }

    pub fn to_pretty_string(
        &self,
        item_provider: &ItemInfoProvider,
        market_provider: &MarketPriceProvider,
        unique_path_statistic_analyzer: &dyn StatisticAnalyzerPaths,
        calculator: &Calculator,
        calculated_groups: Option<&Vec<GroupRoute>>,
    ) -> String {
        let mut out = String::new();

        if let Some(group) = calculated_groups {
            let found = self.locate_group(&group);

            match found {
                Some(e) => writeln!(
                    &mut out,
                    "{}",
                    e.to_pretty_string(
                        &item_provider,
                        &market_provider,
                        StatisticAnalyzerCurrencyGroupPreset::CurrencyGroupChance
                            .get_instance()
                            .0
                            .as_ref()
                    )
                )
                .unwrap(),
                None => writeln!(&mut out, "Group info could not be parsed.").unwrap(),
            };
        }

        let start_item = &calculator.starting_item;

        write!(
            &mut out,
            "{}",
            start_item.to_pretty_string(&item_provider, false)
        )
        .unwrap();

        let cost_per_1 = unique_path_statistic_analyzer.calculate_cost_per_craft(
            &self
                .route
                .iter()
                .map(|e| e.currency_list.clone())
                .collect::<Vec<CraftCurrencyList>>(),
            &item_provider,
            &market_provider,
        );

        let tries_for_60 =
            unique_path_statistic_analyzer.calculate_tries_needed_for_60_percent(&self);
        let cost_per_60 =
            PriceInDivines::new((tries_for_60 as f64) * cost_per_1.get_divine_value());

        writeln!(
            &mut out,
            "Exact Chance: {:.5}% | Tries needed for 60%: {} | Cost per Craft: {} | Cost for 60%: {}{}",
            (*self.chance.get_raw_value()) * 100_f64,
            tries_for_60.to_formatted_string(&Locale::en),
            format!(
                "{} EX",
                (market_provider
                    .currency_convert(&cost_per_1, &PriceKind::Exalted)
                    .ceil() as u64)
                    .to_formatted_string(&Locale::en)
            ),
            format!(
                "{} EX",
                (market_provider
                    .currency_convert(&cost_per_60, &PriceKind::Exalted)
                    .ceil() as u64)
                    .to_formatted_string(&Locale::en)
            ),
            match unique_path_statistic_analyzer.format_display_more_info(
                &self,
                &item_provider,
                &market_provider
            ) {
                Some(e) => e,
                None => "".to_string(),
            }
        )
        .unwrap();

        writeln!(
            out,
            "0. Starting with ...{}",
            if start_item.affixes.is_empty() {
                " nothing :3".to_string()
            } else {
                "".to_string()
            }
        )
        .unwrap();

        for affix in &start_item.affixes {
            print_affix(
                &mut out,
                Some(0),
                affix,
                None,
                item_provider,
                true,
                &calculator.starting_item.base_id,
                false,
            );
        }

        let mut prev_affixes = start_item.affixes.clone();
        let mut prev_rarity = start_item.rarity.clone();
        let mut temporary_affixes: THashSet<AffixSpecifier> = THashSet::default();

        for (i, path) in self.route.iter().enumerate() {
            let item: &calculator::ItemMatrixNode =
                calculator.matrix.get(&path.item_matrix_id).unwrap();
            let new_affixes = &item.item.snapshot.affixes;
            let new_rarity = &item.item.snapshot.rarity;

            let added: THashSet<_> = new_affixes.difference(&prev_affixes).collect();
            let removed: THashSet<_> = prev_affixes.difference(&new_affixes).collect();
            let temporary = item.item.meta.mark_for_essence_only;

            writeln!(
                out,
                "{}. Apply {}{}",
                i + 1,
                path.currency_list
                    .list
                    .iter()
                    .map(|e| {
                        let currency_value = market_provider
                            .try_lookup_currency_in_divines_default_if_fail(&e, &item_provider);
                        let currency_value_ex = market_provider
                            .currency_convert(&currency_value, &PriceKind::Exalted)
                            .ceil() as u32;

                        format!(
                            "{} ({} EX)",
                            e.get_item_name(&item_provider),
                            currency_value_ex.to_formatted_string(&Locale::en)
                        )
                    })
                    .collect::<Vec<String>>()
                    .join(" + "),
                match temporary {
                    true => " [TEMP]",
                    false => "",
                }
            )
            .unwrap();

            for affix in removed.iter() {
                print_affix(
                    &mut out,
                    Some(i + 1),
                    affix,
                    Some(path.chance),
                    item_provider,
                    false,
                    &calculator.starting_item.base_id,
                    temporary_affixes.contains(&affix),
                );

                temporary_affixes.remove(affix);
            }

            for affix in added.iter() {
                if temporary {
                    temporary_affixes.insert((*affix).clone());
                }

                print_affix(
                    &mut out,
                    Some(i + 1),
                    affix,
                    Some(path.chance),
                    item_provider,
                    true,
                    &calculator.starting_item.base_id,
                    temporary,
                );
            }

            if start_item.allowed_sockets != item.item.snapshot.allowed_sockets {
                print_socket_change(
                    &mut out,
                    i + 1,
                    start_item
                        .allowed_sockets
                        .abs_diff(item.item.snapshot.allowed_sockets),
                    Some(path.chance),
                    item_provider,
                    &calculator.starting_item.base_id,
                );
            }

            if new_rarity != &prev_rarity {
                writeln!(
                    &mut out,
                    "{}. \t! Rarity {:?} -> {:?}",
                    i + 1,
                    prev_rarity,
                    new_rarity
                )
                .unwrap();
            }

            if item.item.snapshot.corrupted {
                writeln!(
                    &mut out,
                    "{}. \t! Corrupted - ensure maximum quality and wanted affixes prior to applying a Vaal Orb, since corrupted items CAN NOT be modified further.",
                    i + 1
                )
                .unwrap();
            }

            prev_affixes = new_affixes.clone();
            prev_rarity = new_rarity.clone();
        }

        out
    }
}

pub fn print_socket_change(
    out: &mut String,
    index: usize,
    current_sockets: u8,
    chance: Option<Fraction>,
    item_provider: &ItemInfoProvider,
    base_id: &BaseItemId,
) {
    let bg = item_provider.lookup_base_group(base_id).unwrap();
    let bg = item_provider.lookup_base_group_definition(&bg).unwrap();

    writeln!(
        out,
        "{}.\t{}{} Socket ({}/{})",
        index,
        if index == 0 { "" } else { "+ " },
        match chance {
            Some(c) => format!("[{} (~{:.3}%)]", c, c.to_f64() * 100_f64).to_string(),
            None => "".to_string(),
        },
        current_sockets,
        bg.max_sockets
    )
    .unwrap();
}

pub fn print_affix(
    out: &mut String,
    index: Option<usize>,
    affix: &AffixSpecifier,
    chance: Option<Fraction>,
    item_provider: &ItemInfoProvider,
    is_added: bool,
    base_id: &BaseItemId,
    is_temporary: bool,
) {
    let affix_def = item_provider.lookup_affix_definition(&affix.affix).unwrap();

    let name = &affix_def.description_template;

    let min_ivl = match affix_def.affix_class {
        AffixClassEnum::Base | AffixClassEnum::Desecrated | AffixClassEnum::Essence => {
            let ilvl = &item_provider
                .lookup_base_item_mods(&base_id)
                .unwrap()
                .get(&affix.affix)
                .unwrap()
                .iter()
                .find(|e| e.0 == &affix.tier.tier)
                .unwrap()
                .1
                .min_item_level;

            format!("ilvl {}", ilvl.get_raw_value()).to_string()
        }
    };

    let more_meta: Vec<Option<String>> = vec![
        match is_temporary {
            true => None,
            false => Some(
                format!(
                    "Tier {}{}",
                    affix.tier.tier.get_raw_value(),
                    match affix.tier.bounds {
                        AffixTierLevelBoundsEnum::Exact => "=",
                        AffixTierLevelBoundsEnum::Minimum => "+",
                    }
                )
                .to_string(),
            ),
        },
        match is_temporary {
            true => None,
            false => Some(min_ivl),
        },
        match affix_def.affix_location {
            AffixLocationEnum::Prefix => Some("Prefix".to_string()),
            AffixLocationEnum::Suffix => Some("Suffix".to_string()),
            _ => None,
        },
        match affix.fractured {
            true => Some("FRAC".to_string()),
            false => None,
        },
        match affix_def.affix_class {
            AffixClassEnum::Base => None,
            AffixClassEnum::Desecrated => Some("Des.".to_string()),
            AffixClassEnum::Essence => Some("Ess.".to_string()),
        },
    ];

    let more_meta = more_meta
        .iter()
        .filter_map(|test| test.clone())
        .collect::<Vec<String>>();

    writeln!(
        out,
        "{}{}[{}{}] '{}'",
        match index {
            Some(i) => format!("{}.\t", i),
            None => "".to_string(),
        },
        match index {
            Some(i) if i != 0 && is_added => "+ ",
            Some(i) if i != 0 && !is_added => "- ",
            _ => "",
        },
        match chance {
            Some(c) => format!("{} (~{:.3}%), ", c, c.to_f64() * 100_f64).to_string(),
            None => "".to_string(),
        },
        match more_meta.is_empty() {
            true => "".to_string(),
            false => format!("{}", more_meta.join(", ")).as_str().to_string(),
        },
        match is_temporary {
            true => format!(
                "any {} (temporary)",
                match affix_def.affix_location {
                    AffixLocationEnum::Prefix => "prefix",
                    AffixLocationEnum::Suffix => "suffix",
                    _ => "???",
                }
            )
            .to_string(),
            false => name.to_string(),
        }
    )
    .unwrap();
}

#[cfg(feature = "python")]
#[cfg_attr(feature = "python", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[cfg_attr(feature = "python", pyo3::prelude::pymethods)]
impl ItemRoute {
    #[pyo3(name = "to_pretty_string")]
    pub fn to_pretty_string_py(
        &self,
        item_provider: &ItemInfoProvider,
        market_provider: &MarketPriceProvider,
        statistic_analyzer: &DynStatisticAnalyzerPaths,
        calculator: &Calculator,
        groups: Option<Vec<GroupRoute>>,
    ) -> String {
        self.to_pretty_string(
            item_provider,
            market_provider,
            statistic_analyzer.0.as_ref(),
            calculator,
            groups.as_ref(),
        )
    }

    #[pyo3(name = "locate_group")]
    pub fn locate_group_py(&self, calculated_groups: Vec<GroupRoute>) -> Option<GroupRoute> {
        self.locate_group(calculated_groups.as_ref()).cloned()
    }
}