shipbuilding.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import {cachedFetchJSON} from './cache';
  2. const buy = new Set([
  3. // definitely buy
  4. 'C', 'FLX', 'H', 'H2O', 'HAL', 'HCP', 'HE', 'LST', 'MG', 'N', 'NA', 'NCS', 'NS', 'O', 'PE', 'PG', 'S', 'TCL', 'THF',
  5. // maybe buy
  6. 'AU', 'BRM', 'CU', 'FE', 'LI', 'RG', 'ROM', 'SI', 'TI',
  7. // skip
  8. 'LFE', 'LHP', 'MFE', 'SFE', 'SSC',
  9. ])
  10. const blueprint = {
  11. 'FFC': 1,
  12. 'FSE': 1,
  13. 'LFE': 2,
  14. 'MFE': 2,
  15. 'QCR': 1,
  16. 'SFE': 1,
  17. 'LCB': 1,
  18. 'MFL': 1,
  19. 'MSL': 1,
  20. 'LHP': 94,
  21. 'SSC': 128,
  22. 'BR1': 1,
  23. 'CQM': 1,
  24. }
  25. render();
  26. async function render() {
  27. const main = document.querySelector('main.shipbuilding');
  28. if (!main)
  29. throw new Error('missing shipbuilding container');
  30. main.innerHTML = '<p>Loading...</p>';
  31. const [allPrices, recipes, buildings] = await Promise.all([
  32. cachedFetchJSON('https://refined-prun.github.io/refined-prices/all.json') as Promise<RawPrice[]>,
  33. recipeForMats(),
  34. cachedFetchJSON('https://api.prunplanner.org/data/buildings/') as Promise<Building[]>,
  35. ]);
  36. const prices = Object.fromEntries(allPrices.filter((price) => price.ExchangeCode === 'IC1')
  37. .map((price) => [price.MaterialTicker, price]));
  38. const production: Production = {};
  39. const analysisNodes: AnalysisNode[] = [];
  40. let cost = 0;
  41. for (const [mat, amount] of Object.entries(blueprint)) {
  42. const { cost: matCost, node } = analyzeMat(mat, amount, production, prices, recipes);
  43. cost += matCost;
  44. analysisNodes.push(node);
  45. }
  46. const expertiseGroups: Record<string, string[]> = {};
  47. for (const building of buildings) {
  48. if (!(building.building_ticker in production))
  49. continue;
  50. if (!expertiseGroups[building.expertise])
  51. expertiseGroups[building.expertise] = [];
  52. expertiseGroups[building.expertise].push(building.building_ticker);
  53. }
  54. main.innerHTML = '';
  55. main.append(
  56. renderAnalysis(analysisNodes),
  57. element('p', {textContent: `total cost: ${formatWhole(cost)}`}),
  58. renderProduction(expertiseGroups, production, prices),
  59. );
  60. }
  61. async function recipeForMats(): Promise<Record<string, Recipe>> {
  62. const allRecipes: Recipe[] = await cachedFetchJSON('https://api.prunplanner.org/data/recipes/');
  63. const matRecipes: Record<string, Recipe[]> = {}; // all ways to make a mat
  64. for (const recipe of allRecipes)
  65. for (const output of recipe.outputs) {
  66. const recipes = matRecipes[output.material_ticker];
  67. if (recipes)
  68. recipes.push(recipe);
  69. else
  70. matRecipes[output.material_ticker] = [recipe];
  71. }
  72. const matRecipe: Record<string, Recipe> = {}; // mats for which there's only one recipe to make
  73. for (const [mat, recipes] of Object.entries(matRecipes))
  74. if (recipes.length === 1)
  75. matRecipe[mat] = recipes[0];
  76. return matRecipe;
  77. }
  78. function analyzeMat(mat: string, amount: number, production: Production,
  79. prices: Record<string, RawPrice>, recipes: Record<string, Recipe>): { cost: number, node: AnalysisNode } {
  80. const price = prices[mat];
  81. if (!price)
  82. throw new Error(`missing price for ${mat}`);
  83. const traded = price.AverageTraded30D ?? 0;
  84. if (buy.has(mat)) {
  85. if (price.Ask == null)
  86. throw new Error(`missing ask price for ${mat}`);
  87. return {
  88. cost: price.Ask * amount,
  89. node: { text: `${formatAmount(amount)}x${mat} buy: ${formatAmount(price.Ask)}, daily traded ${formatFixed(traded, 1)}`, children: [] },
  90. };
  91. }
  92. const recipe = recipes[mat];
  93. if (!recipe)
  94. return { cost: 0, node: { text: `${formatAmount(amount)}x${mat} make (unknown recipe)`, children: [] } };
  95. const building = recipe.building_ticker;
  96. if (!production[building])
  97. production[building] = {};
  98. production[building][mat] = (production[building][mat] ?? 0) + amount;
  99. const liquid = traded > amount * 2 ? 'liquid' : 'not liquid';
  100. let totalCost = 0;
  101. const children: AnalysisNode[] = [];
  102. for (const inputMat of recipe.inputs) {
  103. const inputAmount = inputMat.material_amount * amount / recipe.outputs[0].material_amount;
  104. const { cost, node } = analyzeMat(inputMat.material_ticker, inputAmount, production, prices, recipes);
  105. totalCost += cost;
  106. children.push(node);
  107. }
  108. children.push({ text: `cost: ${formatWhole(totalCost)}`, children: [] });
  109. return {
  110. cost: totalCost,
  111. node: { text: `${formatAmount(amount)}x${mat} make (${building}, ${liquid})`, children },
  112. };
  113. }
  114. function renderAnalysis(nodes: AnalysisNode[]): HTMLElement {
  115. const section = element('section');
  116. for (const node of nodes)
  117. section.append(renderAnalysisNode(node));
  118. return section;
  119. }
  120. function renderAnalysisNode(node: AnalysisNode, level = 0): HTMLElement {
  121. if (node.children.length === 0) {
  122. const div = element('div', {textContent: node.text, className: 'analysis-node'});
  123. return div;
  124. }
  125. const details = element('details', {className: 'analysis-node'});
  126. details.open = true;
  127. const summary = element('summary', {textContent: node.text});
  128. details.append(summary);
  129. for (const child of node.children)
  130. details.append(renderAnalysisNode(child, level + 1));
  131. return details;
  132. }
  133. function renderProduction(expertiseGroups: Record<string, string[]>, production: Production,
  134. prices: Record<string, RawPrice>): HTMLElement {
  135. const section = element('section');
  136. section.append(element('h2', {textContent: 'production'}));
  137. for (const [expertise, buildings] of Object.entries(expertiseGroups)) {
  138. section.append(element('h3', {textContent: expertise}));
  139. for (const building of buildings) {
  140. const buildingRow = element('div', {className: 'building-row', textContent: building});
  141. const buildingMats = element('div');
  142. const mats = Object.entries(production[building]);
  143. for (const [index, [mat, amount]] of mats.entries()) {
  144. const traded = prices[mat]?.AverageTraded30D ?? 0;
  145. const span = element('span', {
  146. textContent: `${formatAmount(amount)}x${mat}`,
  147. });
  148. span.style.color = traded > amount * 2 ? '#6c6' : '#c66';
  149. buildingMats.append(span);
  150. if (index < mats.length - 1)
  151. buildingMats.append(document.createTextNode(' '));
  152. }
  153. buildingRow.append(buildingMats);
  154. section.append(buildingRow);
  155. }
  156. }
  157. return section;
  158. }
  159. function element<K extends keyof HTMLElementTagNameMap>(tagName: K,
  160. properties: Partial<HTMLElementTagNameMap[K]> = {}): HTMLElementTagNameMap[K] {
  161. const node = document.createElement(tagName);
  162. Object.assign(node, properties);
  163. return node;
  164. }
  165. function formatAmount(n: number): string {
  166. return n.toLocaleString(undefined, {maximumFractionDigits: 3});
  167. }
  168. function formatFixed(n: number, digits: number): string {
  169. return n.toLocaleString(undefined, {
  170. minimumFractionDigits: digits,
  171. maximumFractionDigits: digits,
  172. });
  173. }
  174. function formatWhole(n: number): string {
  175. return n.toLocaleString(undefined, {maximumFractionDigits: 0});
  176. }
  177. interface AnalysisNode {
  178. text: string
  179. children: AnalysisNode[]
  180. }
  181. interface Recipe {
  182. recipe_name: string
  183. building_ticker: string
  184. inputs: RecipeMat[]
  185. outputs: RecipeMat[]
  186. time_ms: number
  187. }
  188. interface RecipeMat {
  189. material_ticker: string
  190. material_amount: number
  191. }
  192. interface RawPrice {
  193. MaterialTicker: string
  194. ExchangeCode: string
  195. Ask: number | null
  196. AverageTraded30D: number | null
  197. Supply: number
  198. }
  199. interface Building {
  200. building_ticker: string
  201. expertise: string
  202. }
  203. type Production = Record<string, Record<string, number>>;