/** * Shop / tooltip pricing from seedValue and optional player-market last sale. * Matches design ยง27.6 โ€” lerp toward lastTradePrice over shopPriceLerpDurationMs. */ import { ItemId, itemDefinition, ITEM_DEFINITIONS } from "../definitions/items.js"; import { ItemCategory } from "../definitions/itemCategories.js"; import { DEFAULT_WORLD_SETTINGS } from "../protocol/constants.js"; import { chargeFractionRemaining } from "../items/charges.js"; export function lerp (a, b, t) { return a + (b - a) * t; } /** Normalize sparse itemId โ†’ seed overrides from world settings. */ export function normalizeItemSeedValues (raw) { const out = {}; if (!raw || typeof raw !== "object") { return out; } for (const [key, value] of Object.entries(raw)) { const itemId = Number(key); if (!Number.isInteger(itemId) || itemId <= 0 || !itemDefinition(itemId)) { continue; } const seed = Math.round(Number(value)); if (!Number.isFinite(seed)) { continue; } const defSeed = Math.max(1, Number(itemDefinition(itemId)?.seedValue) || 1); const next = Math.max(1, seed); // Only store overrides that differ from the item definition default. if (next !== defSeed) { out[String(itemId)] = next; } } return out; } /** Effective world seed for an item (override or definition). */ export function effectiveSeedValue (itemId, settings = null) { const def = itemDefinition(itemId); const defSeed = Math.max(1, Number(def?.seedValue) || 1); const overrides = settings?.itemSeedValues; if (!overrides || typeof overrides !== "object") { return defSeed; } const key = String(itemId | 0); if (!Object.prototype.hasOwnProperty.call(overrides, key) && !Object.prototype.hasOwnProperty.call(overrides, itemId | 0)) { return defSeed; } const raw = overrides[key] ?? overrides[itemId | 0]; const seed = Math.round(Number(raw)); if (!Number.isFinite(seed)) { return defSeed; } return Math.max(1, seed); } /** * @param {object|null} lastSale `{ lastTradePrice, lastTradeAt, priceFrom }` * @param {object|null} settings world settings (reads itemSeedValues + lerp duration) * @returns {number} Internal market value โ€” may be fractional while lerping. */ export function undiscountedMarketValue ( itemId, lastSale = null, now = Date.now(), lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs, settings = null ) { const seed = effectiveSeedValue(itemId, settings); if (!lastSale?.lastTradeAt || lastSale.lastTradePrice == null) { return seed; } const duration = Math.max( 1, Number(lerpDurationMs) || Number(settings?.shopPriceLerpDurationMs) || DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs ); const t = Math.min(1, Math.max(0, (now - lastSale.lastTradeAt) / duration)); const from = lastSale.priceFrom != null ? Number(lastSale.priceFrom) : seed; const to = Number(lastSale.lastTradePrice); if (!Number.isFinite(from) || !Number.isFinite(to)) { return seed; } return lerp(from, to, t); } /** Integer coins for display and transactions (ceil of a market-derived float). */ export function marketValueAsCoins (value) { const n = Number(value); if (!Number.isFinite(n) || n <= 0) { return 1; } return Math.max(1, Math.ceil(n)); } /** * Player-facing / transactional market value (integer coins). * Internal lerp in {@link undiscountedMarketValue} may still be fractional. */ export function undiscountedMarketCoins ( itemId, lastSale = null, now = Date.now(), lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs, settings = null ) { return marketValueAsCoins( undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) ); } /** Integer shop purchase price (player buying catalog stock). */ export function shopUnitPrice (itemId, { lastSale = null, now = Date.now(), lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs, hiddenDiscount = 1, settings = null } = {}) { const undiscounted = undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings); const discount = Math.min(1, Math.max(0.01, Number(hiddenDiscount) || 1)); return marketValueAsCoins(undiscounted * discount); } /** NPC pays the player this much when buying (50% of market). */ export function shopBuyFromPlayerPrice (itemId, { lastSale = null, now = Date.now(), lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs, settings = null, stack = null } = {}) { const frac = stack ? chargeFractionRemaining(stack) : 1; return marketValueAsCoins( undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 0.5 * frac ); } /** Resale price for goods the NPC bought from players today (120% of market). */ export function shopBoughtResalePrice (itemId, { lastSale = null, now = Date.now(), lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs, settings = null, stack = null } = {}) { const frac = stack ? chargeFractionRemaining(stack) : 1; return marketValueAsCoins( undiscountedMarketValue(itemId, lastSale, now, lerpDurationMs, settings) * 1.2 * frac ); } /** * Editor / tooltip snapshot for one item. * `marketKnown` is true when a last-sale record exists; otherwise market equals seed. */ export function itemPriceSnapshot (itemId, { settings = null, lastSale = null, now = Date.now(), hiddenDiscount = 1 } = {}) { const def = itemDefinition(itemId); if (!def) { return null; } const lerpDurationMs = settings?.shopPriceLerpDurationMs ?? DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs; const seedValue = effectiveSeedValue(itemId, settings); const marketKnown = !!(lastSale?.lastTradeAt && lastSale.lastTradePrice != null); const marketValue = undiscountedMarketCoins(itemId, lastSale, now, lerpDurationMs, settings); const shopPrice = shopUnitPrice(itemId, { lastSale, now, lerpDurationMs, hiddenDiscount, settings }); return { itemId: def.itemId, displayName: def.displayName ?? String(def.itemId), key: def.key ?? String(def.itemId), definitionSeedValue: Math.max(1, Number(def.seedValue) || 1), seedValue, marketValue, marketKnown, shopPrice }; } /** All items with a price row for the base-prices editor. */ export function listPricedItems () { return Object.values(ITEM_DEFINITIONS) .filter((def) => def?.itemId != null && def.seedValue != null) .map((def) => ({ itemId: def.itemId, displayName: def.displayName ?? String(def.itemId), key: def.key ?? String(def.itemId), definitionSeedValue: Math.max(1, Number(def.seedValue) || 1) })) .sort((a, b) => a.displayName.localeCompare(b.displayName)); } /** NPC shops sell ingredients (and items explicitly flagged) in their catalog. */ export function canSellInNpcShop (itemId) { const def = itemDefinition(itemId); if (!def) { return false; } if (def.npcShopAllowed === false) { return false; } if (def.npcShopAllowed === true) { return true; } return def.category === ItemCategory.ingredient || def.category === "ingredient"; } /** * What a buysItems shopkeeper will purchase from a player bag slot. * All transferable goods except blank cheques (and coins). * Filled cheques are sold as their reserved goods (+ admin fee). */ export function canPlayerSellToNpc (stack) { if (!stack?.itemId) { return false; } const itemId = stack.itemId | 0; if (itemId === ItemId.blankCheque || itemId === ItemId.coins) { return false; } // Recipes are nearly free to scribe; NPC buyback would mint free coins. if (itemId === ItemId.recipePaper) { return false; } if (itemId === ItemId.filledCheque) { const instance = stack.instance; if (instance?.kind !== "filled-cheque") { return false; } const goodsId = instance.itemId | 0; return goodsId > 0 && !!itemDefinition(goodsId) && goodsId !== ItemId.coins; } return !!itemDefinition(itemId); } /** Administrative fee rate when selling a filled cheque to an NPC. */ export const CHEQUE_SHOP_ADMIN_FEE_RATE = 0.05; /** Fee deducted from cheque shop payout (5% of base, rounded up). */ export function shopChequeAdminFee (basePayout) { const base = Math.max(0, Math.round(Number(basePayout)) || 0); if (base <= 0) { return 0; } return Math.ceil(base * CHEQUE_SHOP_ADMIN_FEE_RATE); } /** * Quote for selling one bag unit (or one filled cheque) to a buysItems NPC. * @returns {null | { * isCheque: boolean, * goodsItemId: number, * goodsQuantity: number, * unitPrice: number, * baseTotal: number, * adminFee: number, * payout: number * }} */ export function resolveShopSellQuote (stack, { lastSale = null, now = Date.now(), lerpDurationMs = DEFAULT_WORLD_SETTINGS.shopPriceLerpDurationMs, settings = null, quantity = 1 } = {}) { if (!canPlayerSellToNpc(stack)) { return null; } if ((stack.itemId | 0) === ItemId.filledCheque) { const goodsItemId = stack.instance.itemId | 0; const goodsQuantity = Math.max(1, stack.instance.quantity | 0); const unitPrice = shopBuyFromPlayerPrice(goodsItemId, { lastSale, now, lerpDurationMs, settings }); const baseTotal = unitPrice * goodsQuantity; const adminFee = shopChequeAdminFee(baseTotal); return { isCheque: true, goodsItemId, goodsQuantity, unitPrice, baseTotal, adminFee, payout: Math.max(0, baseTotal - adminFee) }; } const goodsItemId = stack.itemId | 0; const goodsQuantity = Math.max(1, Math.min(stack.quantity | 0 || 1, quantity | 0 || 1)); const unitPrice = shopBuyFromPlayerPrice(goodsItemId, { lastSale, now, lerpDurationMs, settings, stack }); const baseTotal = unitPrice * goodsQuantity; return { isCheque: false, goodsItemId, goodsQuantity, unitPrice, baseTotal, adminFee: 0, payout: baseTotal }; } /** Items suggested for default NPC shop catalogs (ingredients + npcShopAllowed). */ export function listNpcShopSellableItems () { return Object.values(ITEM_DEFINITIONS) .filter((def) => canSellInNpcShop(def.itemId)) .map((def) => ({ itemId: def.itemId, displayName: def.displayName ?? String(def.itemId), key: def.key ?? String(def.itemId) })) .sort((a, b) => a.displayName.localeCompare(b.displayName)); } /** Calendar day key used for midnight shop restock (server local time). */ export function shopRestockDayKey (now = Date.now()) { const date = new Date(now); const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, "0"); const day = String(date.getDate()).padStart(2, "0"); return `${year}-${month}-${day}`; }