-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.rs
443 lines (388 loc) · 14.3 KB
/
main.rs
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use colored::Colorize;
use num_rational::Rational32;
use num_traits::ToPrimitive;
use rayon::prelude::*;
use serde::{Serialize, Serializer};
use structopt::StructOpt;
use std::collections::HashMap;
use std::path::PathBuf;
mod api;
mod crafting;
mod request;
#[cfg(test)]
mod tests;
const VALID_DISCIPLINES: &[&str] = &[
"Armorsmith",
"Artificer",
"Chef",
"Huntsman",
"Jeweler",
"Leatherworker",
"Scribe",
"Tailor",
"Weaponsmith",
];
const ITEM_STACK_SIZE: i32 = 250; // GW2 uses a "stack size" of 250
#[derive(StructOpt, Debug)]
struct Opt {
/// Include timegated recipes such as Deldrimor Steel Ingot
#[structopt(short = "t", long)]
include_timegated: bool,
/// Include recipes that require Piles of Bloodstone Dust, Dragonite Ore or Empyreal Fragments
#[structopt(short = "a", long)]
include_ascended: bool,
/// Output the full list of profitable recipes to this CSV file
#[structopt(short, long, parse(from_os_str))]
output_csv: Option<PathBuf>,
/// Print a shopping list of ingredients for the given item id
item_id: Option<u32>,
/// Limit the maximum number of items produced for a recipe
#[structopt(short, long)]
count: Option<i32>,
/// Only show items craftable by this discipline or comma-separated list of disciplines (e.g. -d=Weaponsmith,Armorsmith)
#[structopt(short = "d", long = "disciplines", use_delimiter = true)]
filter_disciplines: Option<Vec<String>>,
}
#[derive(Debug, Serialize)]
struct OutputRow {
name: String,
disciplines: String,
item_id: u32,
recipe_id: u32,
total_profit: i32,
number_required: i32,
profit_per_item: i32,
crafting_steps: i32,
profit_per_step: i32,
#[serde(serialize_with = "serialize_rational32_to_f64")]
profit_on_cost: Rational32,
}
fn serialize_rational32_to_f64<S>(value: &Rational32, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
const PRECISION: f64 = 1000.0;
serializer.serialize_f64((PRECISION * value.to_f64().unwrap_or(0.0)).round() / PRECISION)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let opt = Opt::from_args();
let filter_disciplines = opt.filter_disciplines.filter(|v| !v.is_empty());
if let Some(filter_disciplines) = &filter_disciplines {
for discipline in filter_disciplines {
if !VALID_DISCIPLINES.contains(&discipline.as_str()) {
return Err(format!(
"Invalid discipline: {} (valid values are {})",
discipline,
VALID_DISCIPLINES.join(", ")
)
.into());
}
}
}
let recipes_path = "recipes.bin";
let items_path = "items.bin";
println!("Loading recipes");
let recipes: Vec<api::Recipe> =
request::ensure_paginated_cache(recipes_path, "recipes").await?;
println!("Loaded {} recipes", recipes.len());
println!("Loading items");
let items: Vec<api::Item> = request::ensure_paginated_cache(items_path, "items").await?;
println!("Loaded {} items", items.len());
let recipes_map = vec_to_map(recipes, |x| x.output_item_id);
let items_map = vec_to_map(items, |x| x.id);
let crafting_options = crafting::CraftingOptions {
include_timegated: opt.include_timegated,
include_ascended: opt.include_ascended,
count: opt.count,
};
if let Some(item_id) = opt.item_id {
let item = items_map.get(&item_id).expect("Item not found");
let mut ingredient_ids = vec![];
collect_ingredient_ids(item_id, &recipes_map, &mut ingredient_ids);
let mut request_listing_item_ids = vec![item_id];
request_listing_item_ids.extend(ingredient_ids);
request_listing_item_ids.sort_unstable();
request_listing_item_ids.dedup();
let tp_listings = request::fetch_item_listings(&request_listing_item_ids).await?;
let tp_listings_map = vec_to_map(tp_listings, |x| x.id);
let mut purchased_ingredients = Default::default();
let profitable_item = crafting::calculate_crafting_profit(
item_id,
&recipes_map,
&items_map,
&tp_listings_map,
Some(&mut purchased_ingredients),
&crafting::CraftingOptions {
include_timegated: true,
include_ascended: true,
..crafting_options
},
);
let profitable_item = if let Some(item) = profitable_item {
item
} else {
println!("Item is not profitable to craft");
return Ok(());
};
println!("============");
println!(
"Shopping list for {} x {} = {} profit ({} / step)",
profitable_item.count,
&item.name,
copper_to_string(profitable_item.profit.to_integer()),
profitable_item.profit_per_crafting_step().to_integer()
);
println!("============");
for ((ingredient_id, ingredient_source), ingredient_count_ratio) in &purchased_ingredients {
let ingredient_count = ingredient_count_ratio.ceil().to_integer();
let ingredient_count_msg = if ingredient_count > ITEM_STACK_SIZE {
let stack_count = ingredient_count / ITEM_STACK_SIZE;
let remainder = ingredient_count % ITEM_STACK_SIZE;
let remainder_msg = if remainder != 0 {
format!(" + {}", remainder)
} else {
"".to_string()
};
format!(
"{} ({} x {}{})",
ingredient_count, stack_count, ITEM_STACK_SIZE, remainder_msg
)
} else {
ingredient_count.to_string()
};
println!(
"{} {}{}",
ingredient_count_msg,
items_map
.get(ingredient_id)
.map(|item| item.name.as_ref())
.unwrap_or("???"),
if *ingredient_source == crafting::Source::Vendor {
" (vendor)"
} else {
""
}
);
}
return Ok(());
}
println!("Loading trading post prices");
let tp_prices: Vec<api::Price> = request::request_paginated("commerce/prices").await?;
println!("Loaded {} trading post prices", tp_prices.len());
let mut tp_prices_map = vec_to_map(tp_prices, |x| x.id);
tp_prices_map.get_mut(&49429).unwrap().sells.unit_price = 6333;
let mut profitable_item_ids = vec![];
let mut ingredient_ids = vec![];
for (item_id, recipe) in &recipes_map {
if let Some(item) = items_map.get(item_id) {
// we cannot sell restricted items
if item.is_restricted() {
continue;
}
}
if let Some(filter_disciplines) = &filter_disciplines {
let mut has_discipline = false;
for discipline in filter_disciplines {
if recipe.disciplines.iter().any(|s| s == discipline) {
has_discipline = true;
break;
}
}
if !has_discipline {
continue;
}
}
// some items are craftable and have no listed restrictions but are still not listable on tp
// e.g. 39417, 79557
// conversely, some items have a NoSell flag but are listable on the trading post
// e.g. 66917
let tp_prices = match tp_prices_map.get(item_id) {
Some(tp_prices) if tp_prices.sells.quantity > 0 => tp_prices,
_ => continue,
};
if let Some(crafting::EstimatedCraftingCost {
source: crafting::Source::Crafting,
cost: crafting_cost,
}) = crafting::calculate_estimated_min_crafting_cost(
*item_id,
&recipes_map,
&items_map,
&tp_prices_map,
&crafting_options,
) {
if tp_prices.effective_buy_price() > crafting_cost {
profitable_item_ids.push(*item_id);
collect_ingredient_ids(*item_id, &recipes_map, &mut ingredient_ids);
}
}
}
println!("Loading detailed trading post listings");
let mut request_listing_item_ids = vec![];
request_listing_item_ids.extend(&profitable_item_ids);
request_listing_item_ids.extend(ingredient_ids);
request_listing_item_ids.sort_unstable();
request_listing_item_ids.dedup();
let tp_listings = request::fetch_item_listings(&request_listing_item_ids).await?;
println!(
"Loaded {} detailed trading post listings",
tp_listings.len()
);
let tp_listings_map = vec_to_map(tp_listings, |x| x.id);
let mut profitable_items: Vec<_> = profitable_item_ids
.par_iter()
.filter_map(|item_id| {
let mut ingredient_ids = vec![*item_id];
collect_ingredient_ids(*item_id, &recipes_map, &mut ingredient_ids);
let mut tp_listings_map_for_item: HashMap<u32, _> = HashMap::new();
for id in ingredient_ids {
debug_assert!(request_listing_item_ids.contains(&id));
if let Some(listing) = tp_listings_map.get(&id).cloned() {
tp_listings_map_for_item.insert(id, listing);
}
}
crafting::calculate_crafting_profit(
*item_id,
&recipes_map,
&items_map,
&tp_listings_map_for_item,
None,
&crafting_options,
)
})
.collect();
profitable_items.sort_unstable_by_key(|item| item.profit);
let mut csv_writer = if let Some(path) = opt.output_csv {
Some(csv::Writer::from_path(path)?)
} else {
None
};
let mut line_colors = [
colored::Color::Red,
colored::Color::Green,
colored::Color::Yellow,
colored::Color::Magenta,
colored::Color::Cyan,
]
.iter()
.cycle();
let header = format!(
"{:<50} {:<15} {:<15} {:<15} {:>15} {:>15} {:>15} {:>15} {:>15} {:>15}",
"Name",
"Disciplines",
"Item id",
"Recipe id",
"Total profit",
"No. required",
"Profit / item",
"Crafting steps",
"Profit / step",
"Profit on cost",
);
println!("{}", header);
println!("{}", "=".repeat(header.len()));
for profitable_item in &profitable_items {
// Only required when prices are cached.
// Profit may end up being 0, since potential profitable items are selected based
// on cached prices, but the actual profit is calculated using detailed listings and
// prices may have changed since they were cached.
if profitable_item.count == 0 {
continue;
}
let item_id = profitable_item.id;
let name = items_map
.get(&item_id)
.map(|item| item.name.as_ref())
.unwrap_or("???");
let recipe = recipes_map.get(&item_id).expect("Missing recipe");
let output_row = OutputRow {
name: name.to_string(),
disciplines: recipe
.disciplines
.iter()
.map(|s| {
if &s[..1] == "A" {
// take 1st and 3rd characters to distinguish armorer/artificer
format!("{}{}", &s[..1], &s[2..3])
} else {
s[..1].to_string()
}
})
.collect::<Vec<_>>()
.join("/"),
item_id,
recipe_id: recipe.id,
total_profit: profitable_item.profit.to_integer(),
number_required: profitable_item.count,
profit_per_item: profitable_item.profit_per_item().to_integer(),
crafting_steps: profitable_item.crafting_steps.ceil().to_integer(),
profit_per_step: profitable_item.profit_per_crafting_step().to_integer(),
profit_on_cost: profitable_item.profit_on_cost(),
};
if let Some(writer) = &mut csv_writer {
writer.serialize(&output_row)?;
}
let line = format!(
"{:<50} {:<15} {:<15} {:<15} {:>15} {:>15} {:>15} {:>15} {:>15} {:>15}",
output_row.name,
output_row.disciplines,
format!("{}", output_row.item_id),
format!("{}", output_row.recipe_id),
copper_to_string(output_row.total_profit),
format!(
"{} item{}",
output_row.number_required,
if output_row.number_required > 1 {
"s"
} else {
""
}
),
format!("{} / item", output_row.profit_per_item),
format!("{} steps", output_row.crafting_steps),
format!("{} / step", output_row.profit_per_step),
format!(
"{}%",
(output_row.profit_on_cost * 100).round().to_integer()
)
);
println!("{}", line.color(*line_colors.next().unwrap()));
}
println!("{}", "=".repeat(header.len()));
println!("{}", header);
println!("{}", "=".repeat(header.len()));
let total_profit: Rational32 = profitable_items.iter().map(|item| item.profit).sum();
println!("Total: {}", copper_to_string(total_profit.to_integer()));
if let Some(writer) = &mut csv_writer {
writer.flush()?;
}
Ok(())
}
fn vec_to_map<T, F>(v: Vec<T>, id_fn: F) -> HashMap<u32, T>
where
F: Fn(&T) -> u32,
{
let mut map = HashMap::default();
for x in v.into_iter() {
map.insert(id_fn(&x), x);
}
map
}
fn collect_ingredient_ids(
item_id: u32,
recipes_map: &HashMap<u32, api::Recipe>,
ids: &mut Vec<u32>,
) {
if let Some(recipe) = recipes_map.get(&item_id) {
for ingredient in &recipe.ingredients {
ids.push(ingredient.item_id);
collect_ingredient_ids(ingredient.item_id, recipes_map, ids);
}
}
}
fn copper_to_string(copper: i32) -> String {
let gold = copper / 10000;
let silver = (copper - gold * 10000) / 100;
let copper = copper - gold * 10000 - silver * 100;
format!("{}.{:02}.{:02}g", gold, silver, copper)
}