shipbuilding.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. import {cachedFetchJSON} from './cache';
  2. import {setupPopover} from './popover';
  3. const BUY = new Set([
  4. // definitely buy
  5. 'C', 'FLX', 'H', 'H2O', 'HAL', 'HCP', 'HE', 'LST', 'MG', 'N', 'NA', 'NCS', 'NS', 'O', 'PE', 'PG', 'S', 'TCL', 'THF',
  6. // maybe buy
  7. 'AIR', 'AU', 'BE', 'BRM', 'BOR', 'BTS', 'CU', 'FAN', 'FC', 'FE', 'HCC', 'HD', 'LDI', 'LI', 'MFK', 'MWF',
  8. 'REA', 'RG', 'RGO', 'ROM', 'SFK', 'SI', 'STL', 'TCO', 'TPU',
  9. // import
  10. 'AAR', 'AWF', 'CAP', 'CF', 'RAD',
  11. // skip
  12. 'LFE', 'LHP', 'MFE', 'SFE', 'SSC',
  13. ])
  14. const blueprint = {
  15. 'FFC': 1,
  16. 'FSE': 1,
  17. 'LFE': 2,
  18. 'MFE': 2,
  19. 'RCT': 1,
  20. 'SFE': 1,
  21. 'LCB': 1,
  22. 'MFL': 1,
  23. 'MSL': 1,
  24. 'LHP': 94,
  25. 'SSC': 128,
  26. 'BR1': 1,
  27. 'CQM': 1,
  28. }
  29. const apiKey = document.querySelector('#api-key') as HTMLInputElement;
  30. {
  31. const storedApiKey = localStorage.getItem('punoted-api-key');
  32. if (storedApiKey)
  33. apiKey.value = storedApiKey;
  34. }
  35. document.querySelector('#fetch')!.addEventListener('click', render);
  36. const renderTarget = document.querySelector('div#shipbuilding')!;
  37. async function render() {
  38. const loader = document.querySelector('#loader') as HTMLElement;
  39. loader.style.display = 'block';
  40. try {
  41. await _render();
  42. if (apiKey.value)
  43. localStorage.setItem('punoted-api-key', apiKey.value);
  44. } catch (e) {
  45. renderTarget.innerHTML = e instanceof Error ? e.message : String(e);
  46. }
  47. loader.style.display = 'none';
  48. }
  49. setupPopover();
  50. render();
  51. async function _render() {
  52. const [allPrices, recipes, buildingList, storage] = await Promise.all([
  53. cachedFetchJSON('https://refined-prun.github.io/refined-prices/all.json') as Promise<RawPrice[]>,
  54. recipeForMats(),
  55. cachedFetchJSON('https://api.prunplanner.org/data/buildings/') as Promise<Building[]>,
  56. fetchStorage(),
  57. ]);
  58. const prices = Object.fromEntries(allPrices.filter((price) => price.ExchangeCode === 'IC1')
  59. .map((price) => [price.MaterialTicker, price]));
  60. const buildings = Object.fromEntries(buildingList.map((b) => [b.building_ticker, b]));
  61. const production: Production = {};
  62. const extract: Record<string, number> = {};
  63. const buy: Record<string, number> = {};
  64. const analysisNodes: AnalysisNode[] = [];
  65. let cost = 0;
  66. for (const [mat, amount] of Object.entries(blueprint)) {
  67. const node = analyzeMat(mat, amount, production, extract, buy, prices, recipes, storage);
  68. cost += node.cost;
  69. analysisNodes.push(node);
  70. }
  71. // requiredMats = buy + production
  72. const requiredMats: Record<string, number> = {...buy};
  73. for (const buildingProduction of Object.values(production))
  74. for (const [mat, amount] of Object.entries(buildingProduction))
  75. requiredMats[mat] = (requiredMats[mat] ?? 0) + amount;
  76. const expertiseGroups: Record<string, string[]> = {};
  77. for (const building of buildingList) {
  78. if (!(building.building_ticker in production))
  79. continue;
  80. if (!expertiseGroups[building.expertise])
  81. expertiseGroups[building.expertise] = [];
  82. expertiseGroups[building.expertise].push(building.building_ticker);
  83. }
  84. renderTarget.innerHTML = '';
  85. renderTarget.append(
  86. renderAnalysis(analysisNodes),
  87. element('p', {textContent: `total cost: ${formatWhole(cost)}`}),
  88. renderProduction(expertiseGroups, production, prices, recipes, buildings),
  89. renderMatList('extract', extract),
  90. renderMatList('buy', buy),
  91. );
  92. }
  93. function renderMatList(header: string, mats: Record<string, number>): HTMLElement {
  94. const section = element('section');
  95. section.append(element('h2', {textContent: header}));
  96. const matsSorted = Object.entries(mats).sort(([a], [b]) => a.localeCompare(b));
  97. section.append(element('p', {
  98. textContent: matsSorted.map(([mat, amount]) => `${formatAmount(amount)}x${mat}`).join(', '),
  99. }));
  100. return section;
  101. }
  102. async function recipeForMats(): Promise<Record<string, Recipe>> {
  103. const allRecipes: Recipe[] = await cachedFetchJSON('https://api.prunplanner.org/data/recipes/');
  104. const matRecipes: Record<string, Recipe[]> = {}; // all ways to make a mat
  105. for (const recipe of allRecipes)
  106. for (const output of recipe.outputs) {
  107. const recipes = matRecipes[output.material_ticker];
  108. if (recipes)
  109. recipes.push(recipe);
  110. else
  111. matRecipes[output.material_ticker] = [recipe];
  112. }
  113. const matRecipe: Record<string, Recipe> = {}; // mats for which there's only one recipe to make
  114. for (const [mat, recipes] of Object.entries(matRecipes))
  115. if (recipes.length === 1)
  116. matRecipe[mat] = recipes[0];
  117. return matRecipe;
  118. }
  119. function analyzeMat(mat: string, amount: number, production: Production, extract: Record<string, number>, buy: Record<string, number>,
  120. prices: Record<string, RawPrice>, recipes: Record<string, Recipe>, storage: Record<string, number>): AnalysisNode {
  121. const price = prices[mat];
  122. if (!price)
  123. throw new Error(`missing price for ${mat}`);
  124. const traded = price.AverageTraded30D ?? 0;
  125. const inStorage = storage[mat] ?? 0;
  126. if (BUY.has(mat)) {
  127. const matPrice = price.VWAP30D ?? price.Ask;
  128. if (matPrice == null) throw new Error(`missing ask price for ${mat}`);
  129. buy[mat] = (buy[mat] ?? 0) + amount;
  130. return {
  131. ticker: mat,
  132. amount,
  133. inStorage,
  134. acquisition: `buy: ${formatAmount(matPrice)}, daily traded ${formatFixed(traded, 1)}`,
  135. children: [],
  136. cost: matPrice * amount,
  137. };
  138. }
  139. const recipe = recipes[mat];
  140. if (!recipe) {
  141. extract[mat] = (extract[mat] ?? 0) + amount;
  142. return {ticker: mat, amount, inStorage, acquisition: `extract`, children: [], cost: 0};
  143. }
  144. const building = recipe.building_ticker;
  145. if (!production[building])
  146. production[building] = {};
  147. production[building][mat] = (production[building][mat] ?? 0) + amount;
  148. const liquid = traded > amount * 2 ? 'liquid' : 'not liquid';
  149. let totalCost = 0;
  150. const children: AnalysisNode[] = [];
  151. for (const inputMat of recipe.inputs) {
  152. const inputAmount = inputMat.material_amount * amount / recipe.outputs[0].material_amount;
  153. const node = analyzeMat(inputMat.material_ticker, inputAmount, production, extract, buy, prices, recipes, storage);
  154. totalCost += node.cost;
  155. children.push(node);
  156. }
  157. return {
  158. ticker: mat,
  159. amount,
  160. inStorage,
  161. acquisition: `make (${building}, ${liquid})`,
  162. children,
  163. cost: totalCost,
  164. };
  165. }
  166. function renderAnalysis(nodes: AnalysisNode[]): HTMLElement {
  167. const section = element('section');
  168. for (const node of nodes)
  169. section.append(renderAnalysisNode(node));
  170. return section;
  171. }
  172. function renderAnalysisNode(node: AnalysisNode, level = 0): HTMLElement {
  173. const amountText = element('span', {textContent: `${formatAmount(node.amount)}x${node.ticker} `});
  174. const storageText = element('span', {textContent: `(${formatAmount(node.inStorage)})`});
  175. const percent = Math.min(node.inStorage / node.amount, 1);
  176. storageText.style.color = `color-mix(in xyz, #0aa ${percent * 100}%, #f80 )`;
  177. const acquisitionText = element('span', {textContent: ' ' + node.acquisition});
  178. let el;
  179. if (node.children.length === 0) {
  180. el = element('div', {className: 'analysis-node'});
  181. el.append(amountText, storageText, acquisitionText);
  182. } else {
  183. el = element('details', {className: 'analysis-node', open: level > 0 && percent < 1});
  184. const summary = element('summary');
  185. summary.append(amountText, storageText, acquisitionText);
  186. el.append(summary);
  187. for (const child of node.children)
  188. el.append(renderAnalysisNode(child, level + 1));
  189. el.append(document.createTextNode(`total cost: ${formatWhole(node.cost)}`));
  190. }
  191. if (level === 0)
  192. el.classList.add('root');
  193. return el;
  194. }
  195. const WORKER_CONSUMPTION: Record<'pioneers' | 'settlers' | 'technicians' | 'engineers' | 'scientists', Record<string, number>> = {
  196. pioneers: {'COF': 0.5, 'DW': 4, 'RAT': 4, 'OVE': 0.5, 'PWO': 0.2},
  197. settlers: {'DW': 5, 'RAT': 6, 'KOM': 1, 'EXO': 0.5, 'REP': 0.2, 'PT': 0.5},
  198. technicians: {'DW': 7.5, 'RAT': 7, 'ALE': 1, 'MED': 0.5, 'SC': 0.1, 'HMS': 0.5, 'SCN': 0.1},
  199. engineers: {'DW': 10, 'MED': 0.5, 'GIN': 1, 'FIM': 7, 'VG': 0.2, 'HSS': 0.2, 'PDA': 0.1},
  200. scientists: {'DW': 10, 'MED': 0.5, 'WIN': 1, 'MEA': 7, 'NST': 0.1, 'LC': 0.2, 'WS': 0.05},
  201. };
  202. function buildingDailyCost(building: Building, prices: Record<string, RawPrice>): number {
  203. let cost = 0;
  204. for (const [workerType, mats] of Object.entries(WORKER_CONSUMPTION)) {
  205. const workers = building[workerType as keyof typeof WORKER_CONSUMPTION];
  206. for (const [mat, per100] of Object.entries(mats)) {
  207. const price = prices[mat].VWAP30D;
  208. if (price == null) throw new Error(`no price for ${mat}`);
  209. cost += price * workers * per100 / 100;
  210. }
  211. }
  212. return cost;
  213. }
  214. function renderProduction(expertiseGroups: Record<string, string[]>, production: Production, prices: Record<string, RawPrice>,
  215. recipes: Record<string, Recipe>, buildings: Record<string, Building>): HTMLElement {
  216. const section = element('section');
  217. section.append(element('h2', {textContent: 'production'}));
  218. // mat → list of {outputMat, expertise, amount} that consume it as an input
  219. const matConsumers: Record<string, {downstreamMat: string, expertise: string, amount: number}[]> = {};
  220. for (const [expertise, productionBuildings] of Object.entries(expertiseGroups)) {
  221. for (const building of productionBuildings) {
  222. for (const [mat, totalAmount] of Object.entries(production[building])) {
  223. const recipe = recipes[mat];
  224. const outputPerRun = recipe.outputs.find((o) => o.material_ticker === mat)!.material_amount;
  225. for (const input of recipe.inputs) {
  226. const ticker = input.material_ticker;
  227. if (!matConsumers[ticker])
  228. matConsumers[ticker] = [];
  229. const amount = input.material_amount * totalAmount / outputPerRun;
  230. matConsumers[ticker].push({downstreamMat: mat, expertise, amount});
  231. }
  232. }
  233. }
  234. }
  235. let totalConsumablesCost = 0;
  236. for (const [expertise, productionBuildings] of Object.entries(expertiseGroups)) {
  237. section.append(element('h3', {textContent: expertise.toLocaleLowerCase()}));
  238. const shipTo: Record<string, Record<string, number>> = {};
  239. for (const building of productionBuildings) {
  240. const buildingMats = element('div');
  241. const mats = Object.entries(production[building]);
  242. let buildingMins = 0;
  243. for (const [index, [mat, amount]] of mats.entries()) {
  244. const traded = prices[mat]?.AverageTraded30D ?? 0;
  245. const span = element('span', {textContent: `${formatAmount(amount)}x${mat}`});
  246. span.style.color = traded > amount * 2 ? '#0cc' : '#c70';
  247. const consumers = matConsumers[mat];
  248. if (consumers) {
  249. span.dataset.tooltip = consumers
  250. .map((c) => `${formatAmount(c.amount)}x${mat} → ${c.downstreamMat} (${c.expertise.toLocaleLowerCase()})`)
  251. .join('\n');
  252. for (const consumer of consumers) {
  253. if (consumer.expertise == expertise) // we aren't shipping it anywhere
  254. continue;
  255. if (!shipTo[consumer.expertise])
  256. shipTo[consumer.expertise] = {};
  257. shipTo[consumer.expertise][mat] = (shipTo[consumer.expertise][mat] ?? 0) + consumer.amount;
  258. }
  259. }
  260. buildingMats.append(span);
  261. if (index < mats.length - 1)
  262. buildingMats.append(document.createTextNode(' '));
  263. const recipe = recipes[mat];
  264. const outputPerRun = recipe.outputs.find((o) => o.material_ticker === mat)!.material_amount;
  265. buildingMins += amount / outputPerRun * (recipe.time_ms / 1000 / 60);
  266. }
  267. const numBuildings = buildingMins / (24*60) / 5 / 1.605; // one ship every 5 days, 160.5% efficiency
  268. const consumablesCost = buildingDailyCost(buildings[building], prices) * Math.round(Math.max(1, numBuildings));
  269. totalConsumablesCost += consumablesCost;
  270. const buildingRow = element('div', {className: 'building-row',
  271. textContent: `${formatFixed(numBuildings, 1)}x${building} (${formatWhole(consumablesCost)}/d)`});
  272. buildingRow.append(buildingMats);
  273. section.append(buildingRow);
  274. }
  275. const shipToDetails = element('details');
  276. shipToDetails.append(element('summary', {textContent: 'ship to'}));
  277. for (const [expertise, mats] of Object.entries(shipTo)) {
  278. const shipToRow = element('div', {textContent: expertise.toLocaleLowerCase() + ': '});
  279. shipToRow.textContent += Object.entries(mats).map(([mat, amount]) => `${amount}x${mat}`).join(' ');
  280. shipToDetails.append(shipToRow);
  281. }
  282. section.append(shipToDetails);
  283. }
  284. section.append(element('h4', {textContent: `total consumables cost: ${formatWhole(totalConsumablesCost)}/day,
  285. ${formatWhole(totalConsumablesCost * 5)}/ship`}));
  286. return section;
  287. }
  288. async function fetchStorage(): Promise<Record<string, number>> {
  289. if (!apiKey.value)
  290. return {};
  291. const users = await fetch('https://api.punoted.net/v1/storages/', {headers: {'X-Data-Token': apiKey.value}})
  292. .then((r) => r.json()) as PUNUserStore[];
  293. const items: Record<string, number> = {};
  294. for (const user of users)
  295. for (const storage of user.Storages)
  296. for (const item of storage.StorageItems)
  297. items[item.MaterialTicker] = (items[item.MaterialTicker] ?? 0) + item.MaterialAmount;
  298. return items;
  299. }
  300. function element<K extends keyof HTMLElementTagNameMap>(tagName: K,
  301. properties: Partial<HTMLElementTagNameMap[K]> = {}): HTMLElementTagNameMap[K] {
  302. const node = document.createElement(tagName);
  303. Object.assign(node, properties);
  304. return node;
  305. }
  306. function formatAmount(n: number): string {
  307. return n.toLocaleString(undefined, {maximumFractionDigits: 3});
  308. }
  309. function formatFixed(n: number, digits: number): string {
  310. return n.toLocaleString(undefined, {
  311. minimumFractionDigits: digits,
  312. maximumFractionDigits: digits,
  313. });
  314. }
  315. function formatWhole(n: number): string {
  316. return n.toLocaleString(undefined, {maximumFractionDigits: 0});
  317. }
  318. interface AnalysisNode {
  319. ticker: string
  320. amount: number
  321. inStorage: number
  322. acquisition: string
  323. children: AnalysisNode[]
  324. cost: number
  325. }
  326. interface Recipe {
  327. recipe_name: string
  328. building_ticker: string
  329. inputs: RecipeMat[]
  330. outputs: RecipeMat[]
  331. time_ms: number
  332. }
  333. interface RecipeMat {
  334. material_ticker: string
  335. material_amount: number
  336. }
  337. interface RawPrice {
  338. MaterialTicker: string
  339. ExchangeCode: string
  340. Ask: number | null
  341. AverageTraded30D: number | null
  342. VWAP30D: number | null
  343. Supply: number
  344. }
  345. interface Building {
  346. building_ticker: string
  347. expertise: string
  348. pioneers: number
  349. settlers: number
  350. technicians: number
  351. engineers: number
  352. scientists: number
  353. }
  354. interface PUNUserStore {
  355. Storages: Array<{
  356. StorageItems: Array<{
  357. MaterialTicker: string
  358. MaterialAmount: number
  359. }>
  360. }>
  361. }
  362. type Production = Record<string, Record<string, number>>;