export const INVENTORY_SLOTS = 32; export const EQUIPMENT_SLOTS = Object.freeze([ "head", "chest", "legs", "boots", "weapon", "offhand", "ring", "bracelet", "amulet" ]); import { attachOrigins, mergeOriginLists, normalizeOrigins, splitOrigins } from "./origin.js"; import { stackRulesFor } from "./stackRules.js"; import { BLANK_CHEQUE_CARRY_CAP, ItemId, itemDefinition } from "../definitions/items.js"; import { normalizeChargeStack } from "./charges.js"; /** Stack counts can exceed 32-bit range (coin stacks up to 999B). */ export function stackQuantity (value) { const n = Number(value); if (!Number.isFinite(n) || n <= 0) { return 0; } const q = Math.floor(n); return Number.isSafeInteger(q) ? q : 0; } export function emptySlots (count = INVENTORY_SLOTS) { return Array.from({ length: count }, () => null); } export function emptyEquipment () { const slots = {}; for (const slot of EQUIPMENT_SLOTS) { slots[slot] = null; } return { slots }; } export function cloneStack (stack) { return stack ? structuredClone(stack) : null; } /** One item from a stack, preserving a single origin slice (for equip). */ export function singleItemFromStack (stack) { if (!stack) { return null; } const split = splitOrigins(normalizeOrigins(stack), 1); return { itemId: stack.itemId, quantity: 1, instance: stack.instance ? cloneStack(stack.instance) : null, origins: split.taken }; } export function potionStackIdentity (instance) { if (!instance || instance.kind !== "potion") { return null; } const effectKey = instance.effectKey ?? (instance.effect ? JSON.stringify(instance.effect) : ""); const fill = Math.max(1, Math.min(5, instance.fillLevel | 0 || 4)); return `${instance.potionKey ?? ""}|${effectKey}|${fill}`; } /** Dye stacks merge when RGB and remaining uses match exactly. */ export function dyeStackIdentity (instance) { if (!instance || instance.kind !== "dye" || !instance.color) { return null; } const fill = Math.max(1, Math.min(5, instance.fillLevel | 0 || 4)); return [ Math.round((instance.color.r ?? 0) * 1000), Math.round((instance.color.g ?? 0) * 1000), Math.round((instance.color.b ?? 0) * 1000), fill ].join(","); } export function stacksMatch (left, right, definition, { inVault = false } = {}) { if (!left || !right || left.itemId !== right.itemId) { return false; } const rules = stackRulesFor(definition, { inVault }); if (rules.uniqueInstance) { return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null); } if (definition?.potion) { const a = potionStackIdentity(left.instance); const b = potionStackIdentity(right.instance); return a != null && a === b; } if (definition?.dye) { const a = dyeStackIdentity(left.instance); const b = dyeStackIdentity(right.instance); return a != null && a === b; } if (left.instance != null || right.instance != null) { return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null); } return rules.stackable; } function stackPayload (stack, quantity, origins) { return { itemId: stack.itemId, quantity, instance: stack.instance ?? null, origins: origins.map((entry) => ({ origin: entry.origin ?? null, quantity: stackQuantity(entry.quantity) })).filter((entry) => entry.quantity > 0) }; } export function insertStack (slots, stack, definition, options = {}) { if (!stack || stack.quantity <= 0) { return { ok: true, slots: slots.map(cloneStack), remainder: 0 }; } const rules = stackRulesFor(definition, options); const next = slots.map(cloneStack); let remaining = stackQuantity(stack.quantity); let pendingOrigins = normalizeOrigins(stack); if (rules.stackable && !rules.uniqueInstance) { for (const slot of next) { if (!slot || !stacksMatch(slot, stack, definition, options)) { continue; } const space = rules.maxStackSize - stackQuantity(slot.quantity); if (space <= 0) { continue; } const add = Math.min(space, remaining); const split = splitOrigins(pendingOrigins, add); slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken); slot.quantity = stackQuantity(slot.quantity) + add; if (stack.instance != null && slot.instance == null) { slot.instance = cloneStack(stack.instance); } delete slot.origin; pendingOrigins = split.remain; remaining -= add; if (remaining === 0) { return { ok: true, slots: next, remainder: 0 }; } } } for (let i = 0; i < next.length; i++) { if (next[i]) { continue; } const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize; const amount = rules.stackable && !rules.uniqueInstance ? Math.min(remaining, cap) : 1; const split = splitOrigins(pendingOrigins, amount); next[i] = stackPayload(stack, amount, split.taken); pendingOrigins = split.remain; remaining -= amount; if (remaining === 0) { return { ok: true, slots: next, remainder: 0 }; } if (!rules.stackable || rules.uniqueInstance) { break; } } return { ok: false, slots, remainder: remaining }; } export function takeFromSlot (slots, slotIndex, quantity = null) { const next = slots.map(cloneStack); const slot = next[slotIndex]; if (!slot) { return { ok: false, slots, taken: null }; } const maxQty = stackQuantity(slot.quantity); const amount = quantity == null ? maxQty : Math.min(maxQty, Math.max(1, stackQuantity(quantity))); if (amount <= 0) { return { ok: false, slots, taken: null }; } const split = splitOrigins(normalizeOrigins(slot), amount); const taken = stackPayload(slot, amount, split.taken); if (amount >= maxQty) { next[slotIndex] = null; } else { slot.quantity = maxQty - amount; slot.origins = split.remain; delete slot.origin; } return { ok: true, slots: next, taken }; } /** * Move or merge a bag stack from one slot into another (same bag). * Empty target → move. Matching stackable → merge into target. Else → swap. */ export function moveInventorySlot (slots, fromIndex, toIndex) { const next = (slots ?? emptySlots()).map(cloneStack); const from = fromIndex | 0; const to = toIndex | 0; if (from === to) { return { ok: true, slots: next, changed: false }; } if (from < 0 || to < 0 || from >= next.length || to >= next.length) { return { ok: false, slots, reason: "Invalid slot." }; } const source = next[from]; if (!source || stackQuantity(source.quantity) <= 0) { return { ok: false, slots, reason: "That inventory slot is empty." }; } const dest = next[to]; if (!dest) { next[to] = source; next[from] = null; return { ok: true, slots: next, changed: true }; } const def = itemDefinition(source.itemId); if (stacksMatch(source, dest, def)) { const rules = stackRulesFor(def); if (rules.stackable && !rules.uniqueInstance) { const space = rules.maxStackSize === Number.POSITIVE_INFINITY ? stackQuantity(source.quantity) : Math.max(0, rules.maxStackSize - stackQuantity(dest.quantity)); if (space > 0) { const add = Math.min(space, stackQuantity(source.quantity)); const split = splitOrigins(normalizeOrigins(source), add); dest.origins = mergeOriginLists(normalizeOrigins(dest), split.taken); dest.quantity = stackQuantity(dest.quantity) + add; if (source.instance != null && dest.instance == null) { dest.instance = cloneStack(source.instance); } delete dest.origin; const remainQty = stackQuantity(source.quantity) - add; if (remainQty <= 0) { next[from] = null; } else { source.quantity = remainQty; source.origins = split.remain; delete source.origin; } return { ok: true, slots: next, changed: true }; } } } next[from] = dest; next[to] = source; return { ok: true, slots: next, changed: true }; } /** * Spend one fill charge from a potion/dye slot without losing the leftover bottle. * Single bottles always mutate in place (or become an empty bottle). Multi-stacks * peel one bottle and re-insert the reduced fill; tries both split orderings so a * matching stack can absorb either side. Never mutates the input slots array. * * @returns {{ ok: true, slots, exhausted: boolean, instance: object } | { ok: false, reason: string }} */ export function consumeFillCharge (slots, slotIndex, { kind = null, itemId = null, definition = null, returnEmptyItemId = null } = {}) { const index = slotIndex | 0; const source = slots?.[index]; if (!source || stackQuantity(source.quantity) <= 0) { return { ok: false, reason: "empty" }; } if (itemId != null && source.itemId !== itemId) { return { ok: false, reason: "wrong-item" }; } if (kind != null && source.instance?.kind !== kind) { return { ok: false, reason: "wrong-item" }; } const def = definition ?? itemDefinition(source.itemId); if (!def) { return { ok: false, reason: "unknown" }; } const fill = Math.max(1, Math.min(5, source.instance?.fillLevel | 0 || 4)); const qty = stackQuantity(source.quantity); const usedInstance = cloneStack(source.instance) ?? { kind, fillLevel: fill }; if (qty === 1) { const next = slots.map(cloneStack); if (fill <= 1) { next[index] = null; if (returnEmptyItemId) { const emptyDef = itemDefinition(returnEmptyItemId); const emptyStack = attachOrigins({ itemId: returnEmptyItemId, quantity: 1, origins: normalizeOrigins(source) }); const inserted = insertStack(next, emptyStack, emptyDef); if (!inserted.ok || inserted.remainder > 0) { return { ok: false, reason: "space" }; } return { ok: true, slots: inserted.slots, exhausted: true, instance: usedInstance }; } return { ok: true, slots: next, exhausted: true, instance: usedInstance }; } next[index].instance = { ...next[index].instance, fillLevel: fill - 1 }; return { ok: true, slots: next, exhausted: false, instance: usedInstance }; } // Multi-stack: try leaving the remainder in place, then the reduced bottle in place. const reducedFirst = tryPeelFillCharge(slots, index, fill, def, returnEmptyItemId, false); if (reducedFirst.ok) { return { ...reducedFirst, instance: usedInstance }; } const remainderFirst = tryPeelFillCharge(slots, index, fill, def, returnEmptyItemId, true); if (remainderFirst.ok) { return { ...remainderFirst, instance: usedInstance }; } return { ok: false, reason: "space" }; } function tryPeelFillCharge (slots, index, fill, def, returnEmptyItemId, remainderStaysInSlot) { const peeled = takeFromSlot(slots, index, 1); if (!peeled.ok || !peeled.taken) { return { ok: false }; } if (fill <= 1) { if (!returnEmptyItemId) { return { ok: true, slots: peeled.slots, exhausted: true }; } const emptyDef = itemDefinition(returnEmptyItemId); const emptyStack = attachOrigins({ itemId: returnEmptyItemId, quantity: 1, origins: normalizeOrigins(peeled.taken) }); const inserted = insertStack(peeled.slots, emptyStack, emptyDef); if (!inserted.ok || inserted.remainder > 0) { return { ok: false }; } return { ok: true, slots: inserted.slots, exhausted: true }; } const reduced = { itemId: peeled.taken.itemId, quantity: 1, instance: { ...cloneStack(peeled.taken.instance), fillLevel: fill - 1 }, origins: peeled.taken.origins }; const remainder = peeled.slots[index] ? cloneStack(peeled.slots[index]) : null; if (!remainderStaysInSlot) { const inserted = insertStack(peeled.slots, reduced, def); if (!inserted.ok || inserted.remainder > 0) { return { ok: false }; } return { ok: true, slots: inserted.slots, exhausted: false }; } // Put reduced bottle back in the original slot; re-home the untouched remainder. const next = peeled.slots.map(cloneStack); next[index] = stackPayload(reduced, 1, normalizeOrigins(reduced)); if (!remainder) { return { ok: true, slots: next, exhausted: false }; } const inserted = insertStack(next, remainder, def); if (!inserted.ok || inserted.remainder > 0) { return { ok: false }; } return { ok: true, slots: inserted.slots, exhausted: false }; } /** Like insertStack, but grows the slot array when capacity runs out (vault). */ export function insertStackGrowable (slots, stack, definition) { if (!stack || stack.quantity <= 0) { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; } let next = (slots ?? []).map(cloneStack); let remaining = stackQuantity(stack.quantity); let pendingOrigins = normalizeOrigins(stack); const rules = stackRulesFor(definition, { inVault: true }); if (rules.stackable && !rules.uniqueInstance) { for (const slot of next) { if (!slot || !stacksMatch(slot, stack, definition, { inVault: true })) { continue; } const space = rules.maxStackSize - stackQuantity(slot.quantity); if (space <= 0) { continue; } const add = Math.min(space, remaining); const split = splitOrigins(pendingOrigins, add); slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken); slot.quantity = stackQuantity(slot.quantity) + add; if (stack.instance != null && slot.instance == null) { slot.instance = cloneStack(stack.instance); } delete slot.origin; pendingOrigins = split.remain; remaining -= add; if (remaining === 0) { return { ok: true, slots: next, remainder: 0 }; } } } while (remaining > 0) { const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize; const amount = rules.stackable && !rules.uniqueInstance ? Math.min(remaining, cap) : 1; const split = splitOrigins(pendingOrigins, amount); next.push(stackPayload(stack, amount, split.taken)); pendingOrigins = split.remain; remaining -= amount; if (!rules.stackable || rules.uniqueInstance) { break; } } return { ok: remaining === 0, slots: next, remainder: remaining }; } /** Take `quantity` of matching goods from slots (any slots). Vault may compact; inventory should pass `{ compact: false }`. */ export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null, compact = true }) { let remaining = Math.max(0, stackQuantity(quantity)); if (!remaining) { return { ok: false, slots, taken: null }; } const next = (slots ?? []).map(cloneStack); const takenOrigins = []; for (let i = 0; i < next.length && remaining > 0; i++) { const slot = next[i]; if (!slot || slot.itemId !== itemId) { continue; } if (instance != null) { if (JSON.stringify(slot.instance ?? null) !== JSON.stringify(instance)) { continue; } } const amount = Math.min(stackQuantity(slot.quantity), remaining); const split = splitOrigins(normalizeOrigins(slot), amount); takenOrigins.push(...split.taken); if (amount >= stackQuantity(slot.quantity)) { next[i] = null; } else { slot.quantity = stackQuantity(slot.quantity) - amount; slot.origins = split.remain; delete slot.origin; } remaining -= amount; } if (remaining > 0) { return { ok: false, slots, taken: null }; } return { ok: true, slots: compact ? next.filter((slot) => slot) : next, taken: attachOrigins({ itemId, quantity: stackQuantity(quantity), instance: instance ?? null, origins: mergeOriginLists([], takenOrigins) }) }; } export function countItemInSlots (slots, itemId) { let total = 0; for (const slot of slots ?? []) { if (slot?.itemId === itemId) { total += stackQuantity(slot.quantity); } } return total; } export function countCoinsInSlots (slots) { return countItemInSlots(slots, ItemId.coins); } /** Remove coin quantity from bag slots (FIFO across coin stacks). */ export function takeCoinsFromSlots (slots, amount) { let remaining = stackQuantity(amount); if (!remaining) { return { ok: true, slots: (slots ?? []).map(cloneStack) }; } if (countCoinsInSlots(slots) < remaining) { return { ok: false, slots: (slots ?? []).map(cloneStack) }; } let next = (slots ?? []).map(cloneStack); for (let i = 0; i < next.length && remaining > 0; i++) { if (!next[i] || next[i].itemId !== ItemId.coins) { continue; } const taken = takeFromSlot(next, i, remaining); if (!taken.ok) { continue; } next = taken.slots; remaining -= stackQuantity(taken.taken?.quantity); } return { ok: remaining === 0, slots: next }; } /** Add coin stacks, splitting at max stack size (999B). */ export function addCoinsToSlots (slots, amount, { growable = false } = {}) { const def = itemDefinition(ItemId.coins); if (!def || amount <= 0) { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; } let next = (slots ?? []).map(cloneStack); if (!growable && next.length < INVENTORY_SLOTS) { const padded = emptySlots(); for (let i = 0; i < next.length; i++) { padded[i] = next[i]; } next = padded; } let remaining = stackQuantity(amount); const insert = growable ? insertStackGrowable : insertStack; while (remaining > 0) { const chunk = Math.min(remaining, def.maxStackSize ?? 99); const result = insert(next, attachOrigins({ itemId: ItemId.coins, quantity: chunk }), def); next = result.slots; const placed = chunk - (result.remainder ?? 0); remaining -= placed; if (!result.ok || result.remainder > 0) { return { ok: false, slots: next, remainder: remaining }; } } return { ok: true, slots: next, remainder: 0 }; } /** Convert legacy currency counters into coin stacks. */ export function migrateBagCoins (bag) { let inventory = bag.inventory ?? emptySlots(); let vault = bag.vault ?? []; if (bag.currency > 0) { const added = addCoinsToSlots(inventory, stackQuantity(bag.currency), { growable: false }); inventory = added.slots; } if (bag.vaultCurrency > 0) { const added = addCoinsToSlots(vault, stackQuantity(bag.vaultCurrency), { growable: true }); vault = added.slots; } return { ...bag, inventory, vault, currency: 0, vaultCurrency: 0 }; } export function migrateInheritanceCoins (inheritance) { if (!inheritance?.currency) { return inheritance; } const added = addCoinsToSlots(inheritance.slots ?? emptySlots(), stackQuantity(inheritance.currency), { growable: true }); return { ...inheritance, slots: added.slots, currency: 0 }; } /** Trim excess blank cheques in inventory (e.g. after legacy saves or bugs). */ export function normalizeInventorySlots (slots) { const capped = capItemTotalInSlots(slots ?? emptySlots(), ItemId.blankCheque, BLANK_CHEQUE_CARRY_CAP); return capped.map((slot) => normalizeChargeStack(slot)); } export function capItemTotalInSlots (slots, itemId, cap) { const next = (slots ?? []).map(cloneStack); let total = countItemInSlots(next, itemId); if (total <= cap) { return next; } let toRemove = total - cap; for (let i = next.length - 1; i >= 0 && toRemove > 0; i--) { const slot = next[i]; if (!slot || slot.itemId !== itemId) { continue; } const beforeQty = stackQuantity(slot.quantity); const drop = Math.min(beforeQty, toRemove); const { remain } = splitOrigins(normalizeOrigins({ ...slot, quantity: beforeQty }), drop); slot.quantity = beforeQty - drop; slot.origins = remain; delete slot.origin; toRemove -= drop; if (slot.quantity <= 0) { next[i] = null; } } return next; } export function normalizeVault (raw) { if (Array.isArray(raw)) { return { slots: raw.map((slot) => normalizeChargeStack(cloneStack(slot))), reserved: [] }; } return { slots: (raw?.slots ?? []).map((slot) => normalizeChargeStack(cloneStack(slot))), reserved: (raw?.reserved ?? []).map((slot) => normalizeChargeStack(cloneStack(slot))) }; } export function serializeVault (vault) { const normalized = normalizeVault(vault); return { slots: publicSlots(normalized.slots), reserved: publicSlots(normalized.reserved) }; } export function publicSlots (slots) { return (slots ?? emptySlots()).map((slot) => { if (!slot) { return null; } const payload = attachOrigins(cloneStack(slot)); const next = { itemId: payload.itemId, quantity: payload.quantity, origins: payload.origins, instance: payload.instance ?? null }; // Cheque reservations keep chequeId so redeem can match the paper to vault goods. if (payload.chequeId != null) { next.chequeId = payload.chequeId; } return next; }); } export function publicEquipment (equipment) { const slots = {}; for (const slot of EQUIPMENT_SLOTS) { slots[slot] = equipment?.slots?.[slot] ? cloneStack(equipment.slots[slot]) : null; } return { slots }; }