import { Component } from "../ecs/components.js"; import { BlockType } from "../../../shared/definitions/tiles.js"; import { ItemId, itemDefinition, itemSpriteName, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js"; import { emptyEquipment, emptySlots, insertStack, publicEquipment, publicSlots, takeFromSlot } from "../../../shared/items/inventory.js"; import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js"; import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; import { randomUUID } from "node:crypto"; export function publicGroundItem (item) { const def = itemDefinition(item.stack?.itemId); return { groundItemId: item.groundItemId, tileX: item.tileX, tileY: item.tileY, itemId: item.stack.itemId, quantity: item.stack.quantity, displayName: def?.displayName ?? "Item", sprite: itemSpriteName(item.stack.itemId, item.stack.instance), expiresAt: item.expiresAt }; } export function bagView (ecs, handle) { return { inventory: publicSlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots()), equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()), currency: ecs.get(handle, Component.currency)?.amount ?? 0, vault: publicSlots(ecs.get(handle, Component.vault)?.slots ?? emptySlots()), vaultCurrency: ecs.get(handle, Component.vault)?.currency ?? 0 }; } export function applyBagView (ecs, handle, bag) { const inventory = ensureInventory(ecs, handle); inventory.slots = publicSlots(bag.inventory ?? emptySlots()); const equipment = ensureEquipment(ecs, handle); const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment()); equipment.slots = nextEquip.slots; let currency = ecs.get(handle, Component.currency); if (!currency) { currency = ecs.add(handle, Component.currency, { amount: 0 }); } currency.amount = bag.currency | 0; const vault = ensureVault(ecs, handle); vault.slots = publicSlots(bag.vault ?? emptySlots()); vault.currency = bag.vaultCurrency | 0; return bagView(ecs, handle); } export function handleItemCommand (world, sessionId, command, now) { switch (command.type) { case "drop-item": return dropItem(world, sessionId, command, now); case "pickup-item": return pickupItem(world, sessionId, command); case "equip-item": return equipItem(world, sessionId, command); case "unequip-item": return unequipItem(world, sessionId, command); case "open-bank": return openBank(world, sessionId, command); case "bank-deposit": return bankMove(world, sessionId, command, "inventory", "vault"); case "bank-withdraw": return bankMove(world, sessionId, command, "vault", "inventory"); case "bank-deposit-money": return bankMoney(world, sessionId, command, "currency", "vault"); case "bank-withdraw-money": return bankMoney(world, sessionId, command, "vault", "currency"); case "claim-inheritance": return claimInheritance(world, sessionId, command); case "write-letter": return writeLetter(world, sessionId, command); case "edit-letter": return editLetter(world, sessionId, command); case "open-letter": return openLetter(world, sessionId, command); default: return null; } } export function expireGroundItems (world, now) { const events = []; for (const item of [...world.groundItems.values()]) { if (item.expiresAt > now) { continue; } removeGroundItem(world, item.groundItemId); events.push({ type: "ground-item-despawn", ...publicGroundItem(item) }); } return events; } export function groundItemsInChunk (world, chunkX, chunkY) { return [...world.groundItems.values()] .filter((item) => tileToChunk(item.tileX) === chunkX && tileToChunk(item.tileY) === chunkY) .map(publicGroundItem); } export function groundItemsInRegion (world, regionX, regionY, tileToRegion) { return [...world.groundItems.values()].filter((item) => tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY ); } export function addGroundItem (world, item) { world.groundItems.set(item.groundItemId, item); const key = tileKey(item.tileX, item.tileY); if (!world.groundByTile.has(key)) { world.groundByTile.set(key, new Set()); } world.groundByTile.get(key).add(item.groundItemId); } export function removeGroundItem (world, groundItemId) { const item = world.groundItems.get(groundItemId); if (!item) { return null; } world.groundItems.delete(groundItemId); const key = tileKey(item.tileX, item.tileY); world.groundByTile.get(key)?.delete(groundItemId); return item; } export function replaceGroundItems (world, items) { world.groundItems.clear(); world.groundByTile.clear(); for (const item of items ?? []) { addGroundItem(world, item); } } export function setGroundItemsForRegion (world, regionX, regionY, items, tileToRegion) { for (const item of [...world.groundItems.values()]) { if (tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY) { removeGroundItem(world, item.groundItemId); } } for (const item of items ?? []) { addGroundItem(world, item); } } function dropItem (world, sessionId, command, now) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const taken = takeFromSlot(inventory.slots, command.slotIndex, command.quantity ?? null); if (!taken.ok) { throw userError("That inventory slot is empty."); } inventory.slots = taken.slots; const position = world.ecs.get(handle, Component.position); const item = { groundItemId: command.groundItemId, tileX: position.tileX, tileY: position.tileY, stack: taken.taken, droppedAt: now, expiresAt: now + (world.settings.groundItemDespawnDurationMs ?? 600_000), source: "player-drop", droppedByCharacterId: command.characterId }; addGroundItem(world, item); return { events: [{ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, droppedByCharacterId: item.droppedByCharacterId, expiresAt: item.expiresAt }], private: bagView(world.ecs, handle) }; } function pickupItem (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const item = world.groundItems.get(command.groundItemId); if (!item) { throw userError("That item is no longer on the ground."); } const position = world.ecs.get(handle, Component.position); if (position.tileX !== item.tileX || position.tileY !== item.tileY) { throw userError("Stand on the item to pick it up."); } const def = itemDefinition(item.stack.itemId); if (!def) { throw userError("Unknown item."); } const inventory = ensureInventory(world.ecs, handle); const inserted = insertStack(inventory.slots, item.stack, def); if (!inserted.ok) { throw userError("Your inventory cannot hold that."); } inventory.slots = inserted.slots; removeGroundItem(world, item.groundItemId); return { events: [{ type: "ground-item-despawn", ...publicGroundItem(item) }], private: bagView(world.ecs, handle) }; } function equipItem (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const equipment = ensureEquipment(world.ecs, handle); const taken = takeFromSlot(inventory.slots, command.slotIndex, 1); if (!taken.ok) { throw userError("That inventory slot is empty."); } const def = itemDefinition(taken.taken.itemId); const slot = def?.equipment?.slot; if (!slot) { inventory.slots = insertStack(inventory.slots, taken.taken, def).slots; throw userError("That item cannot be equipped."); } const previous = equipment.slots[slot]; if (previous) { const back = insertStack(taken.slots, previous, itemDefinition(previous.itemId)); if (!back.ok) { inventory.slots = insertStack(inventory.slots, taken.taken, def).slots; throw userError("No inventory space to unequip the current item."); } inventory.slots = back.slots; } else { inventory.slots = taken.slots; } equipment.slots[slot] = { ...taken.taken, quantity: 1 }; return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true }; } function unequipItem (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const equipment = ensureEquipment(world.ecs, handle); const worn = equipment.slots[command.equipSlot]; if (!worn) { throw userError("Nothing is equipped there."); } const def = itemDefinition(worn.itemId); const inserted = insertStack(inventory.slots, worn, def); if (!inserted.ok) { throw userError("Your inventory cannot hold that."); } inventory.slots = inserted.slots; equipment.slots[command.equipSlot] = null; return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true }; } function openBank (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const position = world.ecs.get(handle, Component.position); if (!nearBank(world, position.tileX, position.tileY)) { throw userError("Stand next to a bank."); } return { events: [], private: bagView(world.ecs, handle), bank: true }; } function bankMove (world, sessionId, command, fromKey, toKey) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireBank(world, handle); const inventory = ensureInventory(world.ecs, handle); const vault = ensureVault(world.ecs, handle); const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots; const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null); if (!taken.ok) { throw userError("That slot is empty."); } const def = itemDefinition(taken.taken.itemId); const dest = toKey === "vault" ? vault : inventory; const inserted = insertStack(dest.slots, taken.taken, def); if (!inserted.ok) { throw userError("Not enough space."); } if (fromKey === "vault") { vault.slots = taken.slots; } else { inventory.slots = taken.slots; } dest.slots = inserted.slots; return { events: [], private: bagView(world.ecs, handle), bank: true }; } function bankMoney (world, sessionId, command, fromKey, toKey) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireBank(world, handle); const amount = Math.max(0, command.amount | 0); if (!amount) { throw userError("Enter an amount."); } const currency = world.ecs.get(handle, Component.currency) ?? world.ecs.add(handle, Component.currency, { amount: 0 }); const vault = ensureVault(world.ecs, handle); const from = fromKey === "vault" ? vault : currency; const to = toKey === "vault" ? vault : currency; const fromAmount = fromKey === "vault" ? vault.currency : currency.amount; if (fromAmount < amount) { throw userError("Not enough coins."); } if (fromKey === "vault") { vault.currency -= amount; } else { currency.amount -= amount; } if (toKey === "vault") { vault.currency += amount; } else { currency.amount += amount; } return { events: [], private: bagView(world.ecs, handle), bank: true }; } function claimInheritance (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireBank(world, handle); const vault = ensureVault(world.ecs, handle); const remainder = []; for (const stack of command.stacks ?? []) { const def = itemDefinition(stack.itemId); if (!def) { remainder.push(stack); continue; } const inserted = insertStack(vault.slots, stack, def); if (inserted.ok) { vault.slots = inserted.slots; } else { remainder.push(stack); } } vault.currency += command.currency | 0; return { events: [], private: bagView(world.ecs, handle), bank: true, remainder }; } function writeLetter (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const slotIndex = command.slotIndex | 0; const slot = inventory.slots[slotIndex]; if (!slot || slot.itemId !== ItemId.paper) { throw userError("Select blank paper."); } const body = normalizeLetterBody(command.body); const appearance = world.ecs.get(handle, Component.appearance); const authorDisplayName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim(); const letterStack = { itemId: ItemId.letter, quantity: 1, origin: null, instance: { kind: "letter", letterId: randomUUID(), authorCharacterId: command.characterId, authorDisplayName, body, opened: true, writtenAt: Date.now() } }; if (slot.quantity <= 1) { inventory.slots[slotIndex] = letterStack; return { events: [], private: bagView(world.ecs, handle) }; } const free = inventory.slots.findIndex((entry) => !entry); if (free < 0) { throw userError("Need a free inventory slot for the letter."); } slot.quantity -= 1; inventory.slots[free] = letterStack; return { events: [], private: bagView(world.ecs, handle) }; } function editLetter (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const slotIndex = command.slotIndex | 0; const slot = inventory.slots[slotIndex]; if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter") { throw userError("That is not a letter."); } if (slot.instance.authorCharacterId !== command.characterId) { throw userError("Only the signer can edit this letter."); } const appearance = world.ecs.get(handle, Component.appearance); const authorDisplayName = `${appearance?.firstName ?? slot.instance.authorDisplayName} ${appearance?.lastName ?? ""}`.trim() || slot.instance.authorDisplayName; slot.instance = { ...slot.instance, authorDisplayName, body: normalizeLetterBody(command.body), writtenAt: Date.now() }; return { events: [], private: bagView(world.ecs, handle) }; } function openLetter (world, sessionId, command) { const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const slotIndex = command.slotIndex | 0; const slot = inventory.slots[slotIndex]; if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter") { throw userError("That is not a letter."); } if (slot.instance.opened !== false) { return { events: [], private: bagView(world.ecs, handle) }; } slot.instance = { ...slot.instance, opened: true }; return { events: [], private: bagView(world.ecs, handle) }; } function normalizeLetterBody (raw) { const body = String(raw ?? "").replace(/\r\n/g, "\n").trimEnd(); if (body.length > LETTER_MAX_BODY_CHARS) { throw userError(`Letters can be at most ${LETTER_MAX_BODY_CHARS} characters.`); } return body; } function requireBank (world, handle) { const position = world.ecs.get(handle, Component.position); if (!nearBank(world, position.tileX, position.tileY)) { throw userError("Stand next to a bank."); } } function nearBank (world, tileX, tileY) { for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy)); const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx); if (data.blocks[index]?.typeId === BlockType.bank) { return true; } } } return false; } function ensureInventory (ecs, handle) { return ecs.get(handle, Component.inventory) ?? ecs.add(handle, Component.inventory, { slots: emptySlots() }); } function ensureEquipment (ecs, handle) { return ecs.get(handle, Component.equipment) ?? ecs.add(handle, Component.equipment, emptyEquipment()); } function ensureVault (ecs, handle) { return ecs.get(handle, Component.vault) ?? ecs.add(handle, Component.vault, { slots: emptySlots(), currency: 0 }); } function userError (message) { const error = new Error(message); error.userFacing = true; return error; }