| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408 |
- import {cachedFetchJSON} from './cache';
- import {setupPopover} from './popover';
- const BUY = new Set([
- // definitely buy
- 'C', 'FLX', 'H', 'H2O', 'HAL', 'HCP', 'HE', 'LST', 'MG', 'N', 'NA', 'NCS', 'NS', 'O', 'PE', 'PG', 'S', 'TCL', 'THF',
- // maybe buy
- 'AIR', 'AU', 'BE', 'BRM', 'BOR', 'BTS', 'CU', 'FAN', 'FC', 'FE', 'HCC', 'HD', 'LDI', 'LI', 'MFK', 'MWF',
- 'REA', 'RG', 'RGO', 'ROM', 'SFK', 'SI', 'STL', 'TCO', 'TPU',
- // import
- 'AAR', 'AWF', 'CAP', 'CF', 'RAD',
- // skip
- 'LFE', 'LHP', 'MFE', 'SFE', 'SSC',
- ])
- const blueprint = {
- 'FFC': 1,
- 'FSE': 1,
- 'LFE': 2,
- 'MFE': 2,
- 'RCT': 1,
- 'SFE': 1,
- 'LCB': 1,
- 'MFL': 1,
- 'MSL': 1,
- 'LHP': 94,
- 'SSC': 128,
- 'BR1': 1,
- 'CQM': 1,
- }
- const shipbuilders = [
- 'CraftsmanThirteen',
- 'EvoV',
- 'MapReduce',
- 'SurvivorBob',
- 'TRUEnterprises',
- ];
- const main = document.querySelector('main.shipbuilding')!;
- (async () => {
- setupPopover();
- main.innerHTML = 'loading...';
- try {
- await render();
- } catch (e) {
- main.innerHTML = e instanceof Error ? e.message : String(e);
- }
- })();
- async function render() {
- const [allPrices, recipes, buildingList, knownCompanies, companyProductionById] = await Promise.all([
- cachedFetchJSON('https://refined-prun.github.io/refined-prices/all.json') as Promise<RawPrice[]>,
- recipeForMats(),
- cachedFetchJSON('https://api.prunplanner.org/data/buildings/') as Promise<Building[]>,
- cachedFetchJSON('https://pmmg-products.github.io/reports/data/knownCompanies.json') as Promise<Record<string, {Username: string}>>,
- pmmgMonthlyReport(),
- ]);
- const prices = Object.fromEntries(allPrices.filter((price) => price.ExchangeCode === 'IC1')
- .map((price) => [price.MaterialTicker, price]));
- const buildings = Object.fromEntries(buildingList.map((b) => [b.building_ticker, b]));
- const production: Production = {};
- const extract: Record<string, number> = {};
- const buy: Record<string, number> = {};
- const analysisNodes: AnalysisNode[] = [];
- let cost = 0;
- for (const [mat, amount] of Object.entries(blueprint)) {
- const { cost: matCost, node } = analyzeMat(mat, amount, production, extract, buy, prices, recipes);
- cost += matCost;
- analysisNodes.push(node);
- }
- // requiredMats = buy + production
- const requiredMats: Record<string, number> = {...buy};
- for (const buildingProduction of Object.values(production))
- for (const [mat, amount] of Object.entries(buildingProduction))
- requiredMats[mat] = (requiredMats[mat] ?? 0) + amount;
- const expertiseGroups: Record<string, string[]> = {};
- for (const building of buildingList) {
- if (!(building.building_ticker in production))
- continue;
- if (!expertiseGroups[building.expertise])
- expertiseGroups[building.expertise] = [];
- expertiseGroups[building.expertise].push(building.building_ticker);
- }
- main.innerHTML = '';
- main.append(
- renderAnalysis(analysisNodes),
- element('p', {textContent: `total cost: ${formatWhole(cost)}`}),
- renderProduction(expertiseGroups, production, prices, recipes, buildings),
- renderMatList('extract', extract),
- renderMatList('buy', buy),
- renderShipbuilders(requiredMats, knownCompanies, companyProductionById),
- );
- }
- function renderMatList(header: string, mats: Record<string, number>): HTMLElement {
- const section = element('section');
- section.append(element('h2', {textContent: header}));
- const matsSorted = Object.entries(mats).sort(([a], [b]) => a.localeCompare(b));
- section.append(element('p', {
- textContent: matsSorted.map(([mat, amount]) => `${formatAmount(amount)}x${mat}`).join(', '),
- }));
- return section;
- }
- async function pmmgMonthlyReport(): Promise<PMMGCompanyProduction> {
- const constants = await fetch('https://raw.githubusercontent.com/PMMG-Products/pmmg-products.github.io/main/reports/src/staticData/constants.ts')
- .then((res) => res.text());
- const match = constants.match(/export const months = \[(.*?)\];/s);
- if (!match)
- throw new Error('failed to parse PMMG months');
- const months = match[1].split(',').map((m) => m.trim().replace(/^"|"$/g, ''));
- const latestMonth = months.at(-1);
- if (!latestMonth)
- throw new Error('missing PMMG month');
- const report = await cachedFetchJSON(`https://pmmg-products.github.io/reports/data/company-data-${latestMonth}.json`);
- return report['individual'];
- }
- function renderShipbuilders(requiredMats: Record<string, number>,
- knownCompanies: Record<string, {Username: string}>, companyProductionById: PMMGCompanyProduction): HTMLElement {
- const matTickers = Object.keys(requiredMats).sort();
- const shipbuilderSet = new Set(shipbuilders);
- const shipbuildersById: Record<string, string> = {};
- for (const [companyId, company] of Object.entries(knownCompanies))
- if (shipbuilderSet.has(company.Username))
- shipbuildersById[companyId] = company.Username;
- const missingShipbuilders = shipbuilders
- .filter((username) => !Object.values(shipbuildersById).includes(username));
- if (missingShipbuilders.length > 0)
- return element('h3', {textContent: `missing shipbuilders in PMMG report: ${missingShipbuilders.join(', ')}`});
- const section = element('section');
- section.append(element('h2', {textContent: 'shipbuilders'}));
- const table = element('table');
- const header = element('tr');
- header.append(element('th', {textContent: 'mat'}));
- header.append(element('th', {textContent: 'amount'}));
- for (const username of Object.values(shipbuildersById))
- header.append(element('th', {textContent: username}));
- table.append(header);
- for (const mat of matTickers) {
- const row = element('tr');
- row.append(element('td', {textContent: mat}));
- row.append(element('td', {textContent: formatAmount(requiredMats[mat])}));
- for (const companyId of Object.keys(shipbuildersById)) {
- const makes = mat in companyProductionById[companyId];
- row.append(element('td', {textContent: makes ? '' : 'x'}));
- }
- table.append(row);
- }
- section.append(table);
- return section;
- }
- async function recipeForMats(): Promise<Record<string, Recipe>> {
- const allRecipes: Recipe[] = await cachedFetchJSON('https://api.prunplanner.org/data/recipes/');
- const matRecipes: Record<string, Recipe[]> = {}; // all ways to make a mat
- for (const recipe of allRecipes)
- for (const output of recipe.outputs) {
- const recipes = matRecipes[output.material_ticker];
- if (recipes)
- recipes.push(recipe);
- else
- matRecipes[output.material_ticker] = [recipe];
- }
- const matRecipe: Record<string, Recipe> = {}; // mats for which there's only one recipe to make
- for (const [mat, recipes] of Object.entries(matRecipes))
- if (recipes.length === 1)
- matRecipe[mat] = recipes[0];
- return matRecipe;
- }
- function analyzeMat(mat: string, amount: number, production: Production, extract: Record<string, number>, buy: Record<string, number>,
- prices: Record<string, RawPrice>, recipes: Record<string, Recipe>): { cost: number, node: AnalysisNode } {
- const price = prices[mat];
- if (!price)
- throw new Error(`missing price for ${mat}`);
- const traded = price.AverageTraded30D ?? 0;
- if (BUY.has(mat)) {
- const matPrice = price.VWAP30D ?? price.Ask;
- if (matPrice == null) throw new Error(`missing ask price for ${mat}`);
- buy[mat] = (buy[mat] ?? 0) + amount;
- return {
- cost: matPrice * amount,
- node: { text: `${formatAmount(amount)}x${mat} buy: ${formatAmount(matPrice)}, daily traded ${formatFixed(traded, 1)}`, children: [] },
- };
- }
- const recipe = recipes[mat];
- if (!recipe) {
- extract[mat] = (extract[mat] ?? 0) + amount;
- return { cost: 0, node: { text: `${formatAmount(amount)}x${mat} extract`, children: [] } };
- }
- const building = recipe.building_ticker;
- if (!production[building])
- production[building] = {};
- production[building][mat] = (production[building][mat] ?? 0) + amount;
- const liquid = traded > amount * 2 ? 'liquid' : 'not liquid';
- let totalCost = 0;
- const children: AnalysisNode[] = [];
- for (const inputMat of recipe.inputs) {
- const inputAmount = inputMat.material_amount * amount / recipe.outputs[0].material_amount;
- const {cost, node} = analyzeMat(inputMat.material_ticker, inputAmount, production, extract, buy, prices, recipes);
- totalCost += cost;
- children.push(node);
- }
- children.push({ text: `cost: ${formatWhole(totalCost)}`, children: [] });
- return {
- cost: totalCost,
- node: { text: `${formatAmount(amount)}x${mat} make (${building}, ${liquid})`, children },
- };
- }
- function renderAnalysis(nodes: AnalysisNode[]): HTMLElement {
- const section = element('section');
- for (const node of nodes)
- section.append(renderAnalysisNode(node));
- return section;
- }
- function renderAnalysisNode(node: AnalysisNode, level = 0): HTMLElement {
- let el;
- if (node.children.length === 0) {
- el = element('div', {textContent: node.text, className: 'analysis-node'});
- } else {
- el = element('details', {className: 'analysis-node', open: level > 0});
- el.append(element('summary', {textContent: node.text}));
- for (const child of node.children)
- el.append(renderAnalysisNode(child, level + 1));
- }
- if (level === 0)
- el.classList.add('root');
- return el;
- }
- const WORKER_CONSUMPTION: Record<'pioneers' | 'settlers' | 'technicians' | 'engineers' | 'scientists', Record<string, number>> = {
- pioneers: {'COF': 0.5, 'DW': 4, 'RAT': 4, 'OVE': 0.5, 'PWO': 0.2},
- settlers: {'DW': 5, 'RAT': 6, 'KOM': 1, 'EXO': 0.5, 'REP': 0.2, 'PT': 0.5},
- technicians: {'DW': 7.5, 'RAT': 7, 'ALE': 1, 'MED': 0.5, 'SC': 0.1, 'HMS': 0.5, 'SCN': 0.1},
- engineers: {'DW': 10, 'MED': 0.5, 'GIN': 1, 'FIM': 7, 'VG': 0.2, 'HSS': 0.2, 'PDA': 0.1},
- scientists: {'DW': 10, 'MED': 0.5, 'WIN': 1, 'MEA': 7, 'NST': 0.1, 'LC': 0.2, 'WS': 0.05},
- };
- function buildingDailyCost(building: Building, prices: Record<string, RawPrice>): number {
- let cost = 0;
- for (const [workerType, mats] of Object.entries(WORKER_CONSUMPTION)) {
- const workers = building[workerType as keyof typeof WORKER_CONSUMPTION];
- for (const [mat, per100] of Object.entries(mats)) {
- const price = prices[mat].VWAP30D;
- if (price == null) throw new Error(`no price for ${mat}`);
- cost += price * workers * per100 / 100;
- }
- }
- return cost;
- }
- function renderProduction(expertiseGroups: Record<string, string[]>, production: Production, prices: Record<string, RawPrice>,
- recipes: Record<string, Recipe>, buildings: Record<string, Building>): HTMLElement {
- const section = element('section');
- section.append(element('h2', {textContent: 'production'}));
- // mat → list of {outputMat, expertise, amount} that consume it as an input
- const matConsumers: Record<string, {downstreamMat: string, expertise: string, amount: number}[]> = {};
- for (const [expertise, productionBuildings] of Object.entries(expertiseGroups)) {
- for (const building of productionBuildings) {
- for (const [mat, totalAmount] of Object.entries(production[building])) {
- const recipe = recipes[mat];
- const outputPerRun = recipe.outputs.find((o) => o.material_ticker === mat)!.material_amount;
- for (const input of recipe.inputs) {
- const ticker = input.material_ticker;
- if (!matConsumers[ticker])
- matConsumers[ticker] = [];
- const amount = input.material_amount * totalAmount / outputPerRun;
- matConsumers[ticker].push({downstreamMat: mat, expertise, amount});
- }
- }
- }
- }
- let totalConsumablesCost = 0;
- for (const [expertise, productionBuildings] of Object.entries(expertiseGroups)) {
- section.append(element('h3', {textContent: expertise.toLocaleLowerCase()}));
- const shipTo: Record<string, Record<string, number>> = {};
- for (const building of productionBuildings) {
- const buildingMats = element('div');
- const mats = Object.entries(production[building]);
- let buildingMins = 0;
- for (const [index, [mat, amount]] of mats.entries()) {
- const traded = prices[mat]?.AverageTraded30D ?? 0;
- const span = element('span', {textContent: `${formatAmount(amount)}x${mat}`});
- span.style.color = traded > amount * 2 ? '#0cc' : '#c70';
- const consumers = matConsumers[mat];
- if (consumers) {
- span.dataset.tooltip = consumers
- .map((c) => `${formatAmount(c.amount)}x${mat} → ${c.downstreamMat} (${c.expertise.toLocaleLowerCase()})`)
- .join('\n');
- for (const consumer of consumers) {
- if (consumer.expertise == expertise) // we aren't shipping it anywhere
- continue;
- if (!shipTo[consumer.expertise])
- shipTo[consumer.expertise] = {};
- shipTo[consumer.expertise][mat] = (shipTo[consumer.expertise][mat] ?? 0) + consumer.amount;
- }
- }
- buildingMats.append(span);
- if (index < mats.length - 1)
- buildingMats.append(document.createTextNode(' '));
- const recipe = recipes[mat];
- const outputPerRun = recipe.outputs.find((o) => o.material_ticker === mat)!.material_amount;
- buildingMins += amount / outputPerRun * (recipe.time_ms / 1000 / 60);
- }
- const numBuildings = buildingMins / (24*60) / 5 / 1.605; // one ship every 5 days, 160.5% efficiency
- const consumablesCost = buildingDailyCost(buildings[building], prices) * Math.round(Math.max(1, numBuildings));
- totalConsumablesCost += consumablesCost;
- const buildingRow = element('div', {className: 'building-row',
- textContent: `${formatFixed(numBuildings, 1)}x${building} (${formatWhole(consumablesCost)}/d)`});
- buildingRow.append(buildingMats);
- section.append(buildingRow);
- }
- const shipToDetails = element('details');
- shipToDetails.append(element('summary', {textContent: 'ship to'}));
- for (const [expertise, mats] of Object.entries(shipTo)) {
- const shipToRow = element('div', {textContent: expertise.toLocaleLowerCase() + ': '});
- shipToRow.textContent += Object.entries(mats).map(([mat, amount]) => `${amount}x${mat}`).join(' ');
- shipToDetails.append(shipToRow);
- }
- section.append(shipToDetails);
- }
- section.append(element('h4', {textContent: `total consumables cost: ${formatWhole(totalConsumablesCost)}/day,
- ${formatWhole(totalConsumablesCost * 5)}/ship`}));
- return section;
- }
- function element<K extends keyof HTMLElementTagNameMap>(tagName: K,
- properties: Partial<HTMLElementTagNameMap[K]> = {}): HTMLElementTagNameMap[K] {
- const node = document.createElement(tagName);
- Object.assign(node, properties);
- return node;
- }
- function formatAmount(n: number): string {
- return n.toLocaleString(undefined, {maximumFractionDigits: 3});
- }
- function formatFixed(n: number, digits: number): string {
- return n.toLocaleString(undefined, {
- minimumFractionDigits: digits,
- maximumFractionDigits: digits,
- });
- }
- function formatWhole(n: number): string {
- return n.toLocaleString(undefined, {maximumFractionDigits: 0});
- }
- interface AnalysisNode {
- text: string
- children: AnalysisNode[]
- }
- interface Recipe {
- recipe_name: string
- building_ticker: string
- inputs: RecipeMat[]
- outputs: RecipeMat[]
- time_ms: number
- }
- interface RecipeMat {
- material_ticker: string
- material_amount: number
- }
- interface RawPrice {
- MaterialTicker: string
- ExchangeCode: string
- Ask: number | null
- AverageTraded30D: number | null
- VWAP30D: number | null
- Supply: number
- }
- interface Building {
- building_ticker: string
- expertise: string
- pioneers: number
- settlers: number
- technicians: number
- engineers: number
- scientists: number
- }
- type PMMGCompanyProduction = Record<string, Record<string, {amount: number}>>;
- type Production = Record<string, Record<string, number>>;
|