shipbuilding.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. 'AIR', 'AU', 'BE', 'BRM', 'BOR', 'BTS', 'CU', 'FAN', 'FC', 'FE', 'HCC', 'HD', 'LDI', 'LI', 'MFK', 'MWF',
  7. 'REA', 'RG', 'RGO', 'ROM', 'SFK', 'SI', 'STL', 'TCO', 'TPU',
  8. // import
  9. 'AAR', 'AWF', 'CAP', 'CF',
  10. // skip
  11. 'LFE', 'LHP', 'MFE', 'SFE', 'SSC',
  12. ])
  13. const blueprint = {
  14. 'FFC': 1,
  15. 'FSE': 1,
  16. 'LFE': 2,
  17. 'MFE': 2,
  18. 'RCT': 1,
  19. 'SFE': 1,
  20. 'LCB': 1,
  21. 'MFL': 1,
  22. 'MSL': 1,
  23. 'LHP': 94,
  24. 'SSC': 128,
  25. 'BR1': 1,
  26. 'CQM': 1,
  27. }
  28. const shipbuilders = [
  29. 'CraftsmanThirteen',
  30. 'EvoV',
  31. 'MapReduce',
  32. 'SurvivorBob',
  33. 'TRUEnterprises',
  34. ];
  35. render();
  36. async function render() {
  37. const main = document.querySelector('main.shipbuilding');
  38. if (!main)
  39. throw new Error('missing shipbuilding container');
  40. main.innerHTML = '<p>Loading...</p>';
  41. const [allPrices, recipes, buildings, knownCompanies, companyProductionById] = await Promise.all([
  42. cachedFetchJSON('https://refined-prun.github.io/refined-prices/all.json') as Promise<RawPrice[]>,
  43. recipeForMats(),
  44. cachedFetchJSON('https://api.prunplanner.org/data/buildings/') as Promise<Building[]>,
  45. cachedFetchJSON('https://pmmg-products.github.io/reports/data/knownCompanies.json') as Promise<Record<string, {Username: string}>>,
  46. pmmgMonthlyReport(),
  47. ]);
  48. const prices = Object.fromEntries(allPrices.filter((price) => price.ExchangeCode === 'IC1')
  49. .map((price) => [price.MaterialTicker, price]));
  50. const production: Production = {};
  51. const extract: Record<string, number> = {};
  52. const buy: Record<string, number> = {};
  53. const analysisNodes: AnalysisNode[] = [];
  54. let cost = 0;
  55. for (const [mat, amount] of Object.entries(blueprint)) {
  56. const { cost: matCost, node } = analyzeMat(mat, amount, production, extract, buy, prices, recipes);
  57. cost += matCost;
  58. analysisNodes.push(node);
  59. }
  60. // requiredMats = buy + production
  61. const requiredMats: Record<string, number> = {...buy};
  62. for (const buildingProduction of Object.values(production))
  63. for (const [mat, amount] of Object.entries(buildingProduction))
  64. requiredMats[mat] = (requiredMats[mat] ?? 0) + amount;
  65. const expertiseGroups: Record<string, string[]> = {};
  66. for (const building of buildings) {
  67. if (!(building.building_ticker in production))
  68. continue;
  69. if (!expertiseGroups[building.expertise])
  70. expertiseGroups[building.expertise] = [];
  71. expertiseGroups[building.expertise].push(building.building_ticker);
  72. }
  73. main.innerHTML = '';
  74. main.append(
  75. renderAnalysis(analysisNodes),
  76. element('p', {textContent: `total cost: ${formatWhole(cost)}`}),
  77. renderProduction(expertiseGroups, production, prices, recipes),
  78. renderMatList('extract', extract),
  79. renderMatList('buy', buy),
  80. renderShipbuilders(requiredMats, knownCompanies, companyProductionById),
  81. );
  82. }
  83. function renderMatList(header: string, mats: Record<string, number>): HTMLElement {
  84. const section = element('section');
  85. section.append(element('h2', {textContent: header}));
  86. const matsSorted = Object.entries(mats).sort(([a], [b]) => a.localeCompare(b));
  87. section.append(element('p', {
  88. textContent: matsSorted.map(([mat, amount]) => `${formatAmount(amount)}x${mat}`).join(', '),
  89. }));
  90. return section;
  91. }
  92. async function pmmgMonthlyReport(): Promise<PMMGCompanyProduction> {
  93. const constants = await fetch('https://raw.githubusercontent.com/PMMG-Products/pmmg-products.github.io/main/reports/src/staticData/constants.ts')
  94. .then((res) => res.text());
  95. const match = constants.match(/export const months = \[(.*?)\];/s);
  96. if (!match)
  97. throw new Error('failed to parse PMMG months');
  98. const months = match[1].split(',').map((m) => m.trim().replace(/^"|"$/g, ''));
  99. const latestMonth = months.at(-1);
  100. if (!latestMonth)
  101. throw new Error('missing PMMG month');
  102. const report = await cachedFetchJSON(`https://pmmg-products.github.io/reports/data/company-data-${latestMonth}.json`);
  103. return report['individual'];
  104. }
  105. function renderShipbuilders(requiredMats: Record<string, number>,
  106. knownCompanies: Record<string, {Username: string}>, companyProductionById: PMMGCompanyProduction): HTMLElement {
  107. const matTickers = Object.keys(requiredMats).sort();
  108. const shipbuilderSet = new Set(shipbuilders);
  109. const shipbuildersById: Record<string, string> = {};
  110. for (const [companyId, company] of Object.entries(knownCompanies))
  111. if (shipbuilderSet.has(company.Username))
  112. shipbuildersById[companyId] = company.Username;
  113. const missingShipbuilders = shipbuilders
  114. .filter((username) => !Object.values(shipbuildersById).includes(username));
  115. if (missingShipbuilders.length > 0)
  116. return element('h3', {textContent: `missing shipbuilders in PMMG report: ${missingShipbuilders.join(', ')}`});
  117. const section = element('section');
  118. section.append(element('h2', {textContent: 'shipbuilders'}));
  119. const table = element('table');
  120. const header = element('tr');
  121. header.append(element('th', {textContent: 'mat'}));
  122. header.append(element('th', {textContent: 'amount'}));
  123. for (const username of Object.values(shipbuildersById))
  124. header.append(element('th', {textContent: username}));
  125. table.append(header);
  126. for (const mat of matTickers) {
  127. const row = element('tr');
  128. row.append(element('td', {textContent: mat}));
  129. row.append(element('td', {textContent: formatAmount(requiredMats[mat])}));
  130. for (const companyId of Object.keys(shipbuildersById)) {
  131. const makes = mat in companyProductionById[companyId];
  132. row.append(element('td', {textContent: makes ? '' : 'x'}));
  133. }
  134. table.append(row);
  135. }
  136. section.append(table);
  137. return section;
  138. }
  139. async function recipeForMats(): Promise<Record<string, Recipe>> {
  140. const allRecipes: Recipe[] = await cachedFetchJSON('https://api.prunplanner.org/data/recipes/');
  141. const matRecipes: Record<string, Recipe[]> = {}; // all ways to make a mat
  142. for (const recipe of allRecipes)
  143. for (const output of recipe.outputs) {
  144. const recipes = matRecipes[output.material_ticker];
  145. if (recipes)
  146. recipes.push(recipe);
  147. else
  148. matRecipes[output.material_ticker] = [recipe];
  149. }
  150. const matRecipe: Record<string, Recipe> = {}; // mats for which there's only one recipe to make
  151. for (const [mat, recipes] of Object.entries(matRecipes))
  152. if (recipes.length === 1)
  153. matRecipe[mat] = recipes[0];
  154. return matRecipe;
  155. }
  156. function analyzeMat(mat: string, amount: number, production: Production, extract: Record<string, number>, buy: Record<string, number>,
  157. prices: Record<string, RawPrice>, recipes: Record<string, Recipe>): { cost: number, node: AnalysisNode } {
  158. const price = prices[mat];
  159. if (!price)
  160. throw new Error(`missing price for ${mat}`);
  161. const traded = price.AverageTraded30D ?? 0;
  162. if (BUY.has(mat)) {
  163. if (price.Ask == null)
  164. throw new Error(`missing ask price for ${mat}`);
  165. buy[mat] = (buy[mat] ?? 0) + amount;
  166. return {
  167. cost: price.Ask * amount,
  168. node: { text: `${formatAmount(amount)}x${mat} buy: ${formatAmount(price.Ask)}, daily traded ${formatFixed(traded, 1)}`, children: [] },
  169. };
  170. }
  171. const recipe = recipes[mat];
  172. if (!recipe) {
  173. extract[mat] = (extract[mat] ?? 0) + amount;
  174. return { cost: 0, node: { text: `${formatAmount(amount)}x${mat} extract`, children: [] } };
  175. }
  176. const building = recipe.building_ticker;
  177. if (!production[building])
  178. production[building] = {};
  179. production[building][mat] = (production[building][mat] ?? 0) + amount;
  180. const liquid = traded > amount * 2 ? 'liquid' : 'not liquid';
  181. let totalCost = 0;
  182. const children: AnalysisNode[] = [];
  183. for (const inputMat of recipe.inputs) {
  184. const inputAmount = inputMat.material_amount * amount / recipe.outputs[0].material_amount;
  185. const {cost, node} = analyzeMat(inputMat.material_ticker, inputAmount, production, extract, buy, prices, recipes);
  186. totalCost += cost;
  187. children.push(node);
  188. }
  189. children.push({ text: `cost: ${formatWhole(totalCost)}`, children: [] });
  190. return {
  191. cost: totalCost,
  192. node: { text: `${formatAmount(amount)}x${mat} make (${building}, ${liquid})`, children },
  193. };
  194. }
  195. function renderAnalysis(nodes: AnalysisNode[]): HTMLElement {
  196. const section = element('section');
  197. for (const node of nodes)
  198. section.append(renderAnalysisNode(node));
  199. return section;
  200. }
  201. function renderAnalysisNode(node: AnalysisNode, level = 0): HTMLElement {
  202. let el;
  203. if (node.children.length === 0) {
  204. el = element('div', {textContent: node.text, className: 'analysis-node'});
  205. } else {
  206. el = element('details', {className: 'analysis-node', open: true});
  207. el.append(element('summary', {textContent: node.text}));
  208. for (const child of node.children)
  209. el.append(renderAnalysisNode(child, level + 1));
  210. }
  211. if (level === 0)
  212. el.classList.add('root');
  213. return el;
  214. }
  215. function renderProduction(expertiseGroups: Record<string, string[]>, production: Production,
  216. prices: Record<string, RawPrice>, recipes: Record<string, Recipe>): HTMLElement {
  217. const section = element('section');
  218. section.append(element('h2', {textContent: 'production'}));
  219. for (const [expertise, buildings] of Object.entries(expertiseGroups)) {
  220. section.append(element('h3', {textContent: expertise}));
  221. for (const building of buildings) {
  222. const buildingMats = element('div');
  223. const mats = Object.entries(production[building]);
  224. let buildingMins = 0;
  225. for (const [index, [mat, amount]] of mats.entries()) {
  226. const traded = prices[mat]?.AverageTraded30D ?? 0;
  227. const span = element('span', {
  228. textContent: `${formatAmount(amount)}x${mat}`,
  229. });
  230. span.style.color = traded > amount * 2 ? '#0cc' : '#c70';
  231. buildingMats.append(span);
  232. if (index < mats.length - 1)
  233. buildingMats.append(document.createTextNode(' '));
  234. const recipe = recipes[mat];
  235. const outputPerRun = recipe.outputs.find((o) => o.material_ticker === mat)!.material_amount;
  236. buildingMins += amount / outputPerRun * (recipe.time_ms / 1000 / 60);
  237. }
  238. const numBuildings = buildingMins / (24*60) / 5 / 1.605; // one ship every 5 days, 160.5% efficiency
  239. const buildingRow = element('div', {className: 'building-row', textContent: `${formatFixed(numBuildings, 1)}x${building}`});
  240. buildingRow.append(buildingMats);
  241. section.append(buildingRow);
  242. }
  243. }
  244. return section;
  245. }
  246. function element<K extends keyof HTMLElementTagNameMap>(tagName: K,
  247. properties: Partial<HTMLElementTagNameMap[K]> = {}): HTMLElementTagNameMap[K] {
  248. const node = document.createElement(tagName);
  249. Object.assign(node, properties);
  250. return node;
  251. }
  252. function formatAmount(n: number): string {
  253. return n.toLocaleString(undefined, {maximumFractionDigits: 3});
  254. }
  255. function formatFixed(n: number, digits: number): string {
  256. return n.toLocaleString(undefined, {
  257. minimumFractionDigits: digits,
  258. maximumFractionDigits: digits,
  259. });
  260. }
  261. function formatWhole(n: number): string {
  262. return n.toLocaleString(undefined, {maximumFractionDigits: 0});
  263. }
  264. interface AnalysisNode {
  265. text: string
  266. children: AnalysisNode[]
  267. }
  268. interface Recipe {
  269. recipe_name: string
  270. building_ticker: string
  271. inputs: RecipeMat[]
  272. outputs: RecipeMat[]
  273. time_ms: number
  274. }
  275. interface RecipeMat {
  276. material_ticker: string
  277. material_amount: number
  278. }
  279. interface RawPrice {
  280. MaterialTicker: string
  281. ExchangeCode: string
  282. Ask: number | null
  283. AverageTraded30D: number | null
  284. Supply: number
  285. }
  286. interface Building {
  287. building_ticker: string
  288. expertise: string
  289. }
  290. type PMMGCompanyProduction = Record<string, Record<string, {amount: number}>>;
  291. type Production = Record<string, Record<string, number>>;