| 1 | import { Component } from "../ecs/components.js"; |
| 2 | import { syncPlayerHealth } from "../skills/service.js"; |
| 3 | import { canEquipItem } from "../../../shared/equipment/stats.js"; |
| 4 | import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js"; |
| 5 | import { stackRulesFor } from "../../../shared/items/stackRules.js"; |
| 6 | import { BlockType } from "../../../shared/definitions/tiles.js"; |
| 7 | import { ItemId, itemDefinition, itemSpriteNameForStack, itemDisplayName, LETTER_MAX_BODY_CHARS, BLANK_CHEQUE_CARRY_CAP } from "../../../shared/definitions/items.js"; |
| 8 | import |
| 9 | { |
| 10 | emptyEquipment, |
| 11 | emptySlots, |
| 12 | insertStack, |
| 13 | insertStackGrowable, |
| 14 | normalizeVault, |
| 15 | normalizeInventorySlots, |
| 16 | publicEquipment, |
| 17 | publicSlots, |
| 18 | takeFromSlot, |
| 19 | takeMatchingFromSlots, |
| 20 | countItemInSlots, |
| 21 | cloneStack, |
| 22 | singleItemFromStack, |
| 23 | stackQuantity, |
| 24 | consumeFillCharge, |
| 25 | moveInventorySlot, |
| 26 | stacksMatch, |
| 27 | fitStackQuantity |
| 28 | } from "../../../shared/items/inventory.js"; |
| 29 | import { countIdenticalInSlots, chequeIsExpired } from "../../../shared/items/cheque.js"; |
| 30 | import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js"; |
| 31 | import { CHUNK_SIZE } from "../../../shared/protocol/constants.js"; |
| 32 | import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js"; |
| 33 | import { randomUUID } from "node:crypto"; |
| 34 | import { tileShoveTowardBlock } from "../simulation/tileInteract.js"; |
| 35 | import { resolvePotionEffect } from "../../../shared/alchemy/recipes.js"; |
| 36 | import { ARROW_COATING_ARROWS_PER_USE } from "../../../shared/definitions/alchemy.js"; |
| 37 | import |
| 38 | { |
| 39 | applyStatusEffect, |
| 40 | emptyStatusEffects, |
| 41 | StatusEffectType |
| 42 | } from "../../../shared/statusEffects/rules.js"; |
| 43 | import |
| 44 | { |
| 45 | attachOrigins, |
| 46 | writtenOrigin, |
| 47 | bankIssuedOrigin, |
| 48 | normalizeOrigins, |
| 49 | mergeOriginLists, |
| 50 | splitOrigins |
| 51 | } from "../../../shared/items/origin.js"; |
| 52 | import { BANK_LETTER_AUTHOR } from "../../../shared/courier/systemLetters.js"; |
| 53 | import { canCharacterPickupGroundItem } from "../../../shared/items/letters.js"; |
| 54 | |
| 55 | export function publicGroundItem (item) |
| 56 | { |
| 57 | const instance = item.stack?.instance ?? null; |
| 58 | return { |
| 59 | groundItemId: item.groundItemId, |
| 60 | tileX: item.tileX, |
| 61 | tileY: item.tileY, |
| 62 | dimensionId: normalizeDimensionId(item.dimensionId ?? OVERWORLD_ID), |
| 63 | itemId: item.stack.itemId, |
| 64 | quantity: item.stack.quantity, |
| 65 | displayName: itemDisplayName(item.stack), |
| 66 | sprite: itemSpriteNameForStack(item.stack), |
| 67 | instance: instance && ( |
| 68 | instance.kind === "potion" |
| 69 | || instance.kind === "letter" |
| 70 | || instance.kind === "recipe-paper" |
| 71 | || instance.kind === "log" |
| 72 | ) |
| 73 | ? instance |
| 74 | : null, |
| 75 | expiresAt: item.expiresAt, |
| 76 | droppedByCharacterId: item.droppedByCharacterId ?? null |
| 77 | }; |
| 78 | } |
| 79 | |
| 80 | export function bagView (ecs, handle) |
| 81 | { |
| 82 | const vault = normalizeVault(ecs.get(handle, Component.vault)); |
| 83 | return { |
| 84 | inventory: publicSlots(normalizeInventorySlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots())), |
| 85 | equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()), |
| 86 | vault: publicSlots(vault.slots), |
| 87 | vaultReserved: publicSlots(vault.reserved) |
| 88 | }; |
| 89 | } |
| 90 | |
| 91 | /** Remove all coin stacks from the bag for death drops. Anyone may pick them up. */ |
| 92 | export function stripCarriedCoinsForDeath (world, characterId) |
| 93 | { |
| 94 | const entityId = world.characterEntities.get(characterId); |
| 95 | if (entityId == null) |
| 96 | { return { stack: null, private: null }; } |
| 97 | const handle = world.ecs.handleOf(entityId); |
| 98 | if (handle == null) |
| 99 | { return { stack: null, private: null }; } |
| 100 | const inventory = ensureInventory(world.ecs, handle); |
| 101 | let total = 0; |
| 102 | let origins = []; |
| 103 | const next = inventory.slots.map(cloneStack); |
| 104 | for (let i = 0; i < next.length; i++) |
| 105 | { |
| 106 | const slot = next[i]; |
| 107 | if (!slot || (slot.itemId | 0) !== ItemId.coins) |
| 108 | { continue; } |
| 109 | const qty = stackQuantity(slot.quantity); |
| 110 | if (qty <= 0) |
| 111 | { |
| 112 | next[i] = null; |
| 113 | continue; |
| 114 | } |
| 115 | total += qty; |
| 116 | origins = mergeOriginLists(origins, normalizeOrigins(slot)); |
| 117 | next[i] = null; |
| 118 | } |
| 119 | if (total <= 0) |
| 120 | { return { stack: null, private: null }; } |
| 121 | inventory.slots = next; |
| 122 | return { |
| 123 | stack: attachOrigins({ |
| 124 | itemId: ItemId.coins, |
| 125 | quantity: total, |
| 126 | origins |
| 127 | }), |
| 128 | private: bagView(world.ecs, handle) |
| 129 | }; |
| 130 | } |
| 131 | |
| 132 | export function applyBagView (ecs, handle, bag) |
| 133 | { |
| 134 | const inventory = ensureInventory(ecs, handle); |
| 135 | inventory.slots = normalizeInventorySlots(publicSlots(bag.inventory ?? emptySlots())); |
| 136 | const equipment = ensureEquipment(ecs, handle); |
| 137 | const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment()); |
| 138 | equipment.slots = nextEquip.slots; |
| 139 | const vault = ensureVault(ecs, handle); |
| 140 | const normalized = normalizeVault( |
| 141 | bag.vaultReserved != null || (bag.vault && !Array.isArray(bag.vault)) |
| 142 | ? { slots: bag.vault, reserved: bag.vaultReserved } |
| 143 | : bag.vault |
| 144 | ); |
| 145 | vault.slots = publicSlots(normalized.slots); |
| 146 | vault.reserved = publicSlots(normalized.reserved); |
| 147 | return bagView(ecs, handle); |
| 148 | } |
| 149 | |
| 150 | export function handleItemCommand (world, sessionId, command, now) |
| 151 | { |
| 152 | switch (command.type) |
| 153 | { |
| 154 | case "drop-item": |
| 155 | return dropItem(world, sessionId, command, now); |
| 156 | case "pickup-item": |
| 157 | return pickupItem(world, sessionId, command); |
| 158 | case "equip-item": |
| 159 | return equipItem(world, sessionId, command); |
| 160 | case "unequip-item": |
| 161 | return unequipItem(world, sessionId, command); |
| 162 | case "move-inventory-slot": |
| 163 | return moveInventorySlotCommand(world, sessionId, command); |
| 164 | case "open-bank": |
| 165 | return openBank(world, sessionId, command); |
| 166 | case "bank-deposit": |
| 167 | return bankMove(world, sessionId, command, "inventory", "vault"); |
| 168 | case "bank-withdraw": |
| 169 | return bankMove(world, sessionId, command, "vault", "inventory"); |
| 170 | case "get-blank-cheques": |
| 171 | return getBlankCheques(world, sessionId, command); |
| 172 | case "return-blank-cheques": |
| 173 | return returnBlankCheques(world, sessionId, command); |
| 174 | case "write-cheque": |
| 175 | return writeCheque(world, sessionId, command); |
| 176 | case "redeem-cheque": |
| 177 | return redeemCheque(world, sessionId, command); |
| 178 | case "claim-inheritance": |
| 179 | return claimInheritance(world, sessionId, command); |
| 180 | case "write-letter": |
| 181 | return writeLetter(world, sessionId, command); |
| 182 | case "edit-letter": |
| 183 | return editLetter(world, sessionId, command); |
| 184 | case "open-letter": |
| 185 | return openLetter(world, sessionId, command); |
| 186 | case "eat-item": |
| 187 | return eatItem(world, sessionId, command); |
| 188 | case "drink-item": |
| 189 | return drinkItem(world, sessionId, command); |
| 190 | case "tip-arrows": |
| 191 | return tipArrows(world, sessionId, command); |
| 192 | default: |
| 193 | return null; |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | export function expireGroundItems (world, now) |
| 198 | { |
| 199 | const events = []; |
| 200 | for (const item of [...world.groundItems.values()]) |
| 201 | { |
| 202 | // Authored item-spawner piles never time out. |
| 203 | if (item.itemSpawnerId || item.source === "item-spawner") |
| 204 | { continue; } |
| 205 | if (item.expiresAt == null || item.expiresAt > now) |
| 206 | { continue; } |
| 207 | // Destroyed paper frees reserved vault goods; a live ground cheque keeps them reserved. |
| 208 | if (item.stack?.itemId === ItemId.filledCheque && item.stack?.instance?.kind === "filled-cheque") |
| 209 | { world.voidFilledCheque?.(item.stack); } |
| 210 | removeGroundItem(world, item.groundItemId); |
| 211 | events.push({ type: "ground-item-despawn", ...publicGroundItem(item) }); |
| 212 | } |
| 213 | return events; |
| 214 | } |
| 215 | |
| 216 | export function groundItemsInChunk (world, chunkX, chunkY, dimensionId = OVERWORLD_ID) |
| 217 | { |
| 218 | const dim = normalizeDimensionId(dimensionId); |
| 219 | return [...world.groundItems.values()] |
| 220 | .filter((item) => |
| 221 | tileToChunk(item.tileX) === chunkX |
| 222 | && tileToChunk(item.tileY) === chunkY |
| 223 | && normalizeDimensionId(item.dimensionId ?? OVERWORLD_ID) === dim |
| 224 | ) |
| 225 | .map(publicGroundItem); |
| 226 | } |
| 227 | |
| 228 | export function groundItemsInRegion (world, regionX, regionY, tileToRegion, dimensionId = OVERWORLD_ID) |
| 229 | { |
| 230 | const dim = normalizeDimensionId(dimensionId); |
| 231 | return [...world.groundItems.values()].filter((item) => |
| 232 | tileToRegion(item.tileX) === regionX |
| 233 | && tileToRegion(item.tileY) === regionY |
| 234 | && normalizeDimensionId(item.dimensionId ?? OVERWORLD_ID) === dim |
| 235 | ); |
| 236 | } |
| 237 | |
| 238 | export function addGroundItem (world, item) |
| 239 | { |
| 240 | const dimensionId = normalizeDimensionId(item.dimensionId ?? OVERWORLD_ID); |
| 241 | item.dimensionId = dimensionId; |
| 242 | world.groundItems.set(item.groundItemId, item); |
| 243 | const key = tileKey(item.tileX, item.tileY, dimensionId); |
| 244 | if (!world.groundByTile.has(key)) |
| 245 | { world.groundByTile.set(key, new Set()); } |
| 246 | world.groundByTile.get(key).add(item.groundItemId); |
| 247 | } |
| 248 | |
| 249 | export function removeGroundItem (world, groundItemId) |
| 250 | { |
| 251 | const item = world.groundItems.get(groundItemId); |
| 252 | if (!item) |
| 253 | { return null; } |
| 254 | world.groundItems.delete(groundItemId); |
| 255 | const key = tileKey(item.tileX, item.tileY, normalizeDimensionId(item.dimensionId ?? OVERWORLD_ID)); |
| 256 | world.groundByTile.get(key)?.delete(groundItemId); |
| 257 | if (world.groundByTile.get(key)?.size === 0) |
| 258 | { world.groundByTile.delete(key); } |
| 259 | // Item-spawner tracking (pickup, debark, burn, …) — optional hook avoids cycles. |
| 260 | world.onGroundItemRemoved?.(item); |
| 261 | return item; |
| 262 | } |
| 263 | |
| 264 | export function replaceGroundItems (world, items) |
| 265 | { |
| 266 | world.groundItems.clear(); |
| 267 | world.groundByTile.clear(); |
| 268 | for (const item of items ?? []) |
| 269 | { addGroundItem(world, item); } |
| 270 | } |
| 271 | |
| 272 | export function setGroundItemsForRegion (world, regionX, regionY, items, tileToRegion, dimensionId = OVERWORLD_ID) |
| 273 | { |
| 274 | const dim = normalizeDimensionId(dimensionId); |
| 275 | for (const item of [...world.groundItems.values()]) |
| 276 | { |
| 277 | if (normalizeDimensionId(item.dimensionId ?? OVERWORLD_ID) !== dim) |
| 278 | { continue; } |
| 279 | if (tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY) |
| 280 | { removeGroundItem(world, item.groundItemId); } |
| 281 | } |
| 282 | for (const item of items ?? []) |
| 283 | { addGroundItem(world, item); } |
| 284 | } |
| 285 | |
| 286 | export function groundItemAppearEvent (item) |
| 287 | { |
| 288 | return { |
| 289 | type: "ground-item-appear", |
| 290 | ...publicGroundItem(item), |
| 291 | stack: item.stack, |
| 292 | droppedAt: item.droppedAt, |
| 293 | source: item.source, |
| 294 | droppedByCharacterId: item.droppedByCharacterId, |
| 295 | expiresAt: item.expiresAt |
| 296 | }; |
| 297 | } |
| 298 | |
| 299 | function allocateGroundItemId (world, preferredId) |
| 300 | { |
| 301 | if (preferredId != null) |
| 302 | { return preferredId | 0; } |
| 303 | return (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1); |
| 304 | } |
| 305 | |
| 306 | /** |
| 307 | * Place a stack on the ground, merging into matching piles on the same tile |
| 308 | * using bag stacking rules. Successful merges reset the despawn timer. |
| 309 | * |
| 310 | * @returns {{ events: object[] }} |
| 311 | */ |
| 312 | export function placeOrMergeGroundStack (world, { |
| 313 | tileX, |
| 314 | tileY, |
| 315 | stack, |
| 316 | now, |
| 317 | source = "world", |
| 318 | droppedByCharacterId = null, |
| 319 | groundItemId = null, |
| 320 | despawnDurationMs = null, |
| 321 | dimensionId = OVERWORLD_ID |
| 322 | }) |
| 323 | { |
| 324 | const events = []; |
| 325 | const quantity = stackQuantity(stack?.quantity); |
| 326 | if (!stack || quantity <= 0) |
| 327 | { return { events }; } |
| 328 | |
| 329 | const dim = normalizeDimensionId(dimensionId); |
| 330 | const def = itemDefinition(stack.itemId); |
| 331 | const rules = stackRulesFor(def); |
| 332 | const duration = despawnDurationMs |
| 333 | ?? world.settings?.groundItemDespawnDurationMs |
| 334 | ?? 600_000; |
| 335 | let remaining = quantity; |
| 336 | let pendingOrigins = normalizeOrigins(stack); |
| 337 | let preferredId = groundItemId; |
| 338 | |
| 339 | if (rules.stackable && !rules.uniqueInstance) |
| 340 | { |
| 341 | const ids = [...(world.groundByTile.get(tileKey(tileX, tileY, dim)) ?? [])]; |
| 342 | for (const id of ids) |
| 343 | { |
| 344 | const existing = world.groundItems.get(id); |
| 345 | if (!existing?.stack || !stacksMatch(existing.stack, stack, def)) |
| 346 | { continue; } |
| 347 | const space = rules.maxStackSize - stackQuantity(existing.stack.quantity); |
| 348 | if (space <= 0) |
| 349 | { continue; } |
| 350 | const add = Math.min(space, remaining); |
| 351 | const split = splitOrigins(pendingOrigins, add); |
| 352 | existing.stack.origins = mergeOriginLists(normalizeOrigins(existing.stack), split.taken); |
| 353 | existing.stack.quantity = stackQuantity(existing.stack.quantity) + add; |
| 354 | if (stack.instance != null && existing.stack.instance == null) |
| 355 | { existing.stack.instance = cloneStack(stack.instance); } |
| 356 | delete existing.stack.origin; |
| 357 | existing.droppedAt = now; |
| 358 | existing.expiresAt = now + duration; |
| 359 | pendingOrigins = split.remain; |
| 360 | remaining -= add; |
| 361 | events.push(groundItemAppearEvent(existing)); |
| 362 | if (remaining === 0) |
| 363 | { return { events }; } |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | while (remaining > 0) |
| 368 | { |
| 369 | const cap = rules.maxStackSize === Number.POSITIVE_INFINITY |
| 370 | ? remaining |
| 371 | : rules.maxStackSize; |
| 372 | const amount = rules.stackable && !rules.uniqueInstance |
| 373 | ? Math.min(remaining, cap) |
| 374 | : 1; |
| 375 | const split = splitOrigins(pendingOrigins, amount); |
| 376 | const item = { |
| 377 | groundItemId: allocateGroundItemId(world, preferredId), |
| 378 | tileX, |
| 379 | tileY, |
| 380 | dimensionId: dim, |
| 381 | stack: { |
| 382 | itemId: stack.itemId, |
| 383 | quantity: amount, |
| 384 | instance: stack.instance ? cloneStack(stack.instance) : null, |
| 385 | origins: split.taken |
| 386 | }, |
| 387 | droppedAt: now, |
| 388 | expiresAt: now + duration, |
| 389 | source, |
| 390 | droppedByCharacterId |
| 391 | }; |
| 392 | preferredId = null; |
| 393 | addGroundItem(world, item); |
| 394 | events.push(groundItemAppearEvent(item)); |
| 395 | pendingOrigins = split.remain; |
| 396 | remaining -= amount; |
| 397 | if (!rules.stackable || rules.uniqueInstance) |
| 398 | { break; } |
| 399 | } |
| 400 | return { events }; |
| 401 | } |
| 402 | |
| 403 | function dropItem (world, sessionId, command, now) |
| 404 | { |
| 405 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 406 | const inventory = ensureInventory(world.ecs, handle); |
| 407 | const taken = takeFromSlot(inventory.slots, command.slotIndex, command.quantity ?? null); |
| 408 | if (!taken.ok) |
| 409 | { throw userError("That inventory slot is empty."); } |
| 410 | inventory.slots = taken.slots; |
| 411 | const position = world.ecs.get(handle, Component.position); |
| 412 | const placed = placeOrMergeGroundStack(world, { |
| 413 | tileX: position.tileX, |
| 414 | tileY: position.tileY, |
| 415 | dimensionId: normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID), |
| 416 | stack: taken.taken, |
| 417 | now, |
| 418 | source: "player-drop", |
| 419 | droppedByCharacterId: command.characterId, |
| 420 | groundItemId: command.groundItemId |
| 421 | }); |
| 422 | return { |
| 423 | events: placed.events, |
| 424 | private: bagView(world.ecs, handle) |
| 425 | }; |
| 426 | } |
| 427 | |
| 428 | function pickupItem (world, sessionId, command) |
| 429 | { |
| 430 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 431 | const item = world.groundItems.get(command.groundItemId); |
| 432 | if (!item) |
| 433 | { throw userError("That item is no longer on the ground."); } |
| 434 | if (!canCharacterPickupGroundItem(item, command.characterId)) |
| 435 | { throw userError("That item is no longer on the ground."); } |
| 436 | const position = world.ecs.get(handle, Component.position); |
| 437 | const playerDim = normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID); |
| 438 | const itemDim = normalizeDimensionId(item.dimensionId ?? OVERWORLD_ID); |
| 439 | if (!position || position.tileX !== item.tileX || position.tileY !== item.tileY || playerDim !== itemDim) |
| 440 | { throw userError("Stand on the item to pick it up."); } |
| 441 | const def = itemDefinition(item.stack.itemId); |
| 442 | if (!def) |
| 443 | { throw userError("Unknown item."); } |
| 444 | const inventory = ensureInventory(world.ecs, handle); |
| 445 | let stackToAdd = item.stack; |
| 446 | if (item.stack.itemId === ItemId.blankCheque) |
| 447 | { |
| 448 | const have = countItemInSlots(inventory.slots, ItemId.blankCheque); |
| 449 | const room = BLANK_CHEQUE_CARRY_CAP - have; |
| 450 | if (room <= 0) |
| 451 | { throw userError(`You already carry ${BLANK_CHEQUE_CARRY_CAP} blank cheques.`); } |
| 452 | const takeQty = Math.min(item.stack.quantity, room); |
| 453 | stackToAdd = { ...item.stack, quantity: takeQty }; |
| 454 | } |
| 455 | const inserted = insertStack(inventory.slots, stackToAdd, def); |
| 456 | if (!inserted.ok) |
| 457 | { throw userError("Your inventory cannot hold that."); } |
| 458 | inventory.slots = inserted.slots; |
| 459 | const events = []; |
| 460 | if (item.stack.itemId === ItemId.blankCheque && stackToAdd.quantity < item.stack.quantity) |
| 461 | { |
| 462 | item.stack.quantity -= stackToAdd.quantity; |
| 463 | events.push({ |
| 464 | type: "ground-item-appear", |
| 465 | ...publicGroundItem(item), |
| 466 | stack: item.stack, |
| 467 | droppedAt: item.droppedAt, |
| 468 | source: item.source, |
| 469 | droppedByCharacterId: item.droppedByCharacterId, |
| 470 | expiresAt: item.expiresAt |
| 471 | }); |
| 472 | } |
| 473 | else |
| 474 | { |
| 475 | removeGroundItem(world, item.groundItemId); |
| 476 | events.push({ type: "ground-item-despawn", ...publicGroundItem(item) }); |
| 477 | } |
| 478 | return { |
| 479 | events, |
| 480 | private: bagView(world.ecs, handle) |
| 481 | }; |
| 482 | } |
| 483 | |
| 484 | function equipItem (world, sessionId, command) |
| 485 | { |
| 486 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 487 | const inventory = ensureInventory(world.ecs, handle); |
| 488 | const equipment = ensureEquipment(world.ecs, handle); |
| 489 | const slotIndex = command.slotIndex | 0; |
| 490 | const source = inventory.slots[slotIndex]; |
| 491 | if (!source || stackQuantity(source.quantity) <= 0) |
| 492 | { throw userError("That inventory slot is empty."); } |
| 493 | const def = itemDefinition(source.itemId); |
| 494 | const slot = def?.equipment?.slot; |
| 495 | if (!slot) |
| 496 | { throw userError("That item cannot be equipped."); } |
| 497 | const skills = world.ecs.get(handle, Component.skills); |
| 498 | const equipCheck = canEquipItem(skills, def); |
| 499 | if (!equipCheck.ok) |
| 500 | { throw userError(equipCheck.reason); } |
| 501 | |
| 502 | const isArrowAmmo = def.equipment?.kind === EquipmentKind.arrowAmmo; |
| 503 | const taken = takeFromSlot(inventory.slots, slotIndex, isArrowAmmo ? null : 1); |
| 504 | if (!taken.ok || stackQuantity(taken.taken?.quantity) <= 0) |
| 505 | { throw userError("That inventory slot is empty."); } |
| 506 | if (taken.taken.itemId === ItemId.coins) |
| 507 | { |
| 508 | inventory.slots = insertStack(taken.slots, taken.taken, itemDefinition(ItemId.coins)).slots; |
| 509 | throw userError("Coins cannot be equipped."); |
| 510 | } |
| 511 | |
| 512 | if (isArrowAmmo) |
| 513 | { |
| 514 | let slots = taken.slots; |
| 515 | const previous = equipment.slots[slot]; |
| 516 | if (previous) |
| 517 | { |
| 518 | const previousDef = itemDefinition(previous.itemId); |
| 519 | if (previous.itemId === taken.taken.itemId) |
| 520 | { |
| 521 | const rules = stackRulesFor(def); |
| 522 | const space = rules.maxStackSize - stackQuantity(previous.quantity); |
| 523 | const add = Math.min(space, stackQuantity(taken.taken.quantity)); |
| 524 | if (add <= 0) |
| 525 | { |
| 526 | inventory.slots = insertStack(slots, taken.taken, def).slots; |
| 527 | throw userError("Your arrow stack is full."); |
| 528 | } |
| 529 | previous.quantity = stackQuantity(previous.quantity) + add; |
| 530 | const leftover = stackQuantity(taken.taken.quantity) - add; |
| 531 | if (leftover > 0) |
| 532 | { |
| 533 | const back = insertStack(slots, { ...taken.taken, quantity: leftover }, def); |
| 534 | if (!back.ok) |
| 535 | { |
| 536 | previous.quantity = stackQuantity(previous.quantity) - add; |
| 537 | inventory.slots = insertStack(slots, taken.taken, def).slots; |
| 538 | throw userError("No inventory space for leftover arrows."); |
| 539 | } |
| 540 | slots = back.slots; |
| 541 | } |
| 542 | inventory.slots = slots; |
| 543 | return { events: [], private: bagView(world.ecs, handle), appearanceChanged: false }; |
| 544 | } |
| 545 | const back = insertStack(slots, previous, previousDef); |
| 546 | if (!back.ok) |
| 547 | { |
| 548 | inventory.slots = insertStack(slots, taken.taken, def).slots; |
| 549 | throw userError("No inventory space to unequip the current item."); |
| 550 | } |
| 551 | slots = back.slots; |
| 552 | } |
| 553 | inventory.slots = slots; |
| 554 | equipment.slots[slot] = taken.taken; |
| 555 | syncPlayerHealth(world.ecs, handle); |
| 556 | return { events: [], private: bagView(world.ecs, handle), appearanceChanged: false, healthChanged: true }; |
| 557 | } |
| 558 | |
| 559 | const toEquip = singleItemFromStack(taken.taken); |
| 560 | const previous = equipment.slots[slot]; |
| 561 | if (previous) |
| 562 | { |
| 563 | const previousSingle = singleItemFromStack(previous); |
| 564 | const back = insertStack(taken.slots, previousSingle, itemDefinition(previous.itemId)); |
| 565 | if (!back.ok) |
| 566 | { |
| 567 | inventory.slots = insertStack(inventory.slots, toEquip, def).slots; |
| 568 | throw userError("No inventory space to unequip the current item."); |
| 569 | } |
| 570 | inventory.slots = back.slots; |
| 571 | } |
| 572 | else |
| 573 | { inventory.slots = taken.slots; } |
| 574 | equipment.slots[slot] = toEquip; |
| 575 | syncPlayerHealth(world.ecs, handle); |
| 576 | return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true, healthChanged: true }; |
| 577 | } |
| 578 | |
| 579 | function unequipItem (world, sessionId, command) |
| 580 | { |
| 581 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 582 | const inventory = ensureInventory(world.ecs, handle); |
| 583 | const equipment = ensureEquipment(world.ecs, handle); |
| 584 | const worn = equipment.slots[command.equipSlot]; |
| 585 | if (!worn) |
| 586 | { throw userError("Nothing is equipped there."); } |
| 587 | const def = itemDefinition(worn.itemId); |
| 588 | const toStore = def?.equipment?.kind === EquipmentKind.arrowAmmo |
| 589 | ? cloneStack(worn) |
| 590 | : singleItemFromStack(worn); |
| 591 | const inserted = insertStack(inventory.slots, toStore, def); |
| 592 | if (!inserted.ok) |
| 593 | { throw userError("Your inventory cannot hold that."); } |
| 594 | inventory.slots = inserted.slots; |
| 595 | equipment.slots[command.equipSlot] = null; |
| 596 | syncPlayerHealth(world.ecs, handle); |
| 597 | const appearanceChanged = def?.equipment?.kind !== EquipmentKind.arrowAmmo; |
| 598 | return { events: [], private: bagView(world.ecs, handle), appearanceChanged, healthChanged: true }; |
| 599 | } |
| 600 | |
| 601 | function moveInventorySlotCommand (world, sessionId, command) |
| 602 | { |
| 603 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 604 | if (world.ecs.has(handle, Component.dead)) |
| 605 | { throw userError("You are dead."); } |
| 606 | const inventory = ensureInventory(world.ecs, handle); |
| 607 | const moved = moveInventorySlot( |
| 608 | inventory.slots, |
| 609 | command.fromSlotIndex, |
| 610 | command.toSlotIndex |
| 611 | ); |
| 612 | if (!moved.ok) |
| 613 | { throw userError(moved.reason ?? "Could not move that item."); } |
| 614 | if (moved.changed) |
| 615 | { inventory.slots = moved.slots; } |
| 616 | return { events: [], private: bagView(world.ecs, handle) }; |
| 617 | } |
| 618 | |
| 619 | function eatItem (world, sessionId, command) |
| 620 | { |
| 621 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 622 | syncPlayerHealth(world.ecs, handle); |
| 623 | const inventory = ensureInventory(world.ecs, handle); |
| 624 | const health = world.ecs.get(handle, Component.health); |
| 625 | if (!health) |
| 626 | { throw userError("You cannot eat right now."); } |
| 627 | if ((health.current | 0) >= (health.max | 0)) |
| 628 | { throw userError("You are already at full health."); } |
| 629 | const slotIndex = command.slotIndex | 0; |
| 630 | const slot = inventory.slots[slotIndex]; |
| 631 | if (!slot || stackQuantity(slot.quantity) <= 0) |
| 632 | { throw userError("That inventory slot is empty."); } |
| 633 | const def = itemDefinition(slot.itemId); |
| 634 | const healing = def?.healing ?? 0; |
| 635 | if (healing <= 0) |
| 636 | { throw userError("That cannot be eaten."); } |
| 637 | const taken = takeFromSlot(inventory.slots, slotIndex, 1); |
| 638 | if (!taken.ok || stackQuantity(taken.taken?.quantity) !== 1) |
| 639 | { throw userError("That inventory slot is empty."); } |
| 640 | inventory.slots = taken.slots; |
| 641 | health.current = Math.min(health.max | 0, (health.current | 0) + healing); |
| 642 | let statusEffectsChanged = false; |
| 643 | if (def?.eatStatusEffect) |
| 644 | { |
| 645 | let component = world.ecs.get(handle, Component.statusEffects); |
| 646 | if (!component) |
| 647 | { component = world.ecs.add(handle, Component.statusEffects, emptyStatusEffects()); } |
| 648 | applyStatusEffect(component, def.eatStatusEffect, Date.now()); |
| 649 | statusEffectsChanged = true; |
| 650 | } |
| 651 | return { |
| 652 | events: [], |
| 653 | private: bagView(world.ecs, handle), |
| 654 | healthChanged: true, |
| 655 | statusEffectsChanged |
| 656 | }; |
| 657 | } |
| 658 | |
| 659 | function drinkItem (world, sessionId, command) |
| 660 | { |
| 661 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 662 | syncPlayerHealth(world.ecs, handle); |
| 663 | const inventory = ensureInventory(world.ecs, handle); |
| 664 | const slotIndex = command.slotIndex | 0; |
| 665 | const slot = inventory.slots[slotIndex]; |
| 666 | if (!slot || slot.itemId !== ItemId.potion || slot.instance?.kind !== "potion") |
| 667 | { throw userError("That is not a potion."); } |
| 668 | const consumed = consumeFillCharge(inventory.slots, slotIndex, { |
| 669 | kind: "potion", |
| 670 | itemId: ItemId.potion, |
| 671 | returnEmptyItemId: ItemId.glassBottle |
| 672 | }); |
| 673 | if (!consumed.ok) |
| 674 | { |
| 675 | if (consumed.reason === "space") |
| 676 | { |
| 677 | throw userError( |
| 678 | "Need bag space to keep the partially used potion (or empty bottle)." |
| 679 | ); |
| 680 | } |
| 681 | throw userError("That inventory slot is empty."); |
| 682 | } |
| 683 | inventory.slots = consumed.slots; |
| 684 | const effectResult = applyPotionEffect(world.ecs, handle, resolvePotionEffect(consumed.instance)); |
| 685 | return { |
| 686 | events: effectResult.events ?? [], |
| 687 | private: bagView(world.ecs, handle), |
| 688 | healthChanged: !!effectResult.healthChanged, |
| 689 | appearanceChanged: !!effectResult.appearanceChanged, |
| 690 | statusEffectsChanged: !!effectResult.statusEffectsChanged |
| 691 | }; |
| 692 | } |
| 693 | |
| 694 | /** |
| 695 | * Apply an arrow-coating potion to untipped arrows in the bag. |
| 696 | * Consumes one coating fill charge; tips up to ARROW_COATING_ARROWS_PER_USE arrows. |
| 697 | */ |
| 698 | function tipArrows (world, sessionId, command) |
| 699 | { |
| 700 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 701 | const inventory = ensureInventory(world.ecs, handle); |
| 702 | const coatingSlotIndex = command.coatingSlotIndex | 0; |
| 703 | const arrowSlotIndex = command.arrowSlotIndex | 0; |
| 704 | const wantQty = Math.max(1, command.quantity | 0 || 1); |
| 705 | |
| 706 | const coating = inventory.slots[coatingSlotIndex]; |
| 707 | if (!coating || coating.itemId !== ItemId.potion || coating.instance?.kind !== "potion") |
| 708 | { throw userError("That is not a coating."); } |
| 709 | const effect = coating.instance.effect |
| 710 | ?? resolvePotionEffect(coating.instance); |
| 711 | if (effect?.type !== "arrow-coating" || !effect.element) |
| 712 | { throw userError("That brew cannot tip arrows."); } |
| 713 | const element = effect.element; |
| 714 | |
| 715 | const arrowSlot = inventory.slots[arrowSlotIndex]; |
| 716 | if (!arrowSlot) |
| 717 | { throw userError("Select arrows to tip."); } |
| 718 | const arrowDef = itemDefinition(arrowSlot.itemId); |
| 719 | if (arrowDef?.equipment?.kind !== EquipmentKind.arrowAmmo) |
| 720 | { throw userError("That is not an arrow."); } |
| 721 | if (arrowSlot.instance?.kind === "tipped-arrow") |
| 722 | { throw userError("Those arrows are already tipped."); } |
| 723 | |
| 724 | const available = stackQuantity(arrowSlot.quantity); |
| 725 | const tipQty = Math.min(wantQty, available, ARROW_COATING_ARROWS_PER_USE); |
| 726 | if (tipQty <= 0) |
| 727 | { throw userError("No arrows to tip."); } |
| 728 | |
| 729 | const taken = takeFromSlot(inventory.slots, arrowSlotIndex, tipQty); |
| 730 | if (!taken.ok || !taken.taken) |
| 731 | { throw userError("Could not take those arrows."); } |
| 732 | inventory.slots = taken.slots; |
| 733 | |
| 734 | const tipped = attachOrigins({ |
| 735 | itemId: arrowSlot.itemId, |
| 736 | quantity: tipQty, |
| 737 | instance: { kind: "tipped-arrow", element }, |
| 738 | origins: taken.taken.origins ?? [] |
| 739 | }); |
| 740 | const inserted = insertStack(inventory.slots, tipped, itemDefinition(arrowSlot.itemId)); |
| 741 | if (!inserted.ok || inserted.remainder > 0) |
| 742 | { |
| 743 | const refund = insertStack( |
| 744 | inventory.slots, |
| 745 | attachOrigins({ |
| 746 | itemId: arrowSlot.itemId, |
| 747 | quantity: tipQty, |
| 748 | instance: null, |
| 749 | origins: taken.taken.origins ?? [] |
| 750 | }), |
| 751 | arrowDef |
| 752 | ); |
| 753 | inventory.slots = refund.slots; |
| 754 | throw userError("Need bag space for the tipped arrows."); |
| 755 | } |
| 756 | inventory.slots = inserted.slots; |
| 757 | |
| 758 | const consumed = consumeFillCharge(inventory.slots, coatingSlotIndex, { |
| 759 | kind: "potion", |
| 760 | itemId: ItemId.potion, |
| 761 | returnEmptyItemId: ItemId.glassBottle |
| 762 | }); |
| 763 | if (!consumed.ok) |
| 764 | { |
| 765 | throw userError( |
| 766 | consumed.reason === "space" |
| 767 | ? "Need bag space to keep the partially used coating (or empty bottle)." |
| 768 | : "That coating is gone." |
| 769 | ); |
| 770 | } |
| 771 | inventory.slots = consumed.slots; |
| 772 | |
| 773 | return { |
| 774 | events: [], |
| 775 | private: bagView(world.ecs, handle) |
| 776 | }; |
| 777 | } |
| 778 | |
| 779 | function ensureStatusEffects (ecs, handle) |
| 780 | { |
| 781 | let component = ecs.get(handle, Component.statusEffects); |
| 782 | if (!component) |
| 783 | { component = ecs.add(handle, Component.statusEffects, emptyStatusEffects()); } |
| 784 | if (!Array.isArray(component.effects)) |
| 785 | { component.effects = []; } |
| 786 | return component; |
| 787 | } |
| 788 | |
| 789 | function applyPotionEffect (ecs, handle, effect) |
| 790 | { |
| 791 | const result = { |
| 792 | healthChanged: false, |
| 793 | appearanceChanged: false, |
| 794 | statusEffectsChanged: false, |
| 795 | events: [] |
| 796 | }; |
| 797 | if (!effect || typeof effect !== "object") |
| 798 | { return result; } |
| 799 | |
| 800 | const health = ecs.get(handle, Component.health); |
| 801 | const type = effect.type; |
| 802 | |
| 803 | if (type === "arrow-coating") |
| 804 | { return result; } |
| 805 | |
| 806 | if (type === "heal" && health) |
| 807 | { |
| 808 | const amount = Math.max(0, effect.amount | 0 || 0); |
| 809 | health.current = Math.min(health.max | 0, (health.current | 0) + amount); |
| 810 | result.healthChanged = true; |
| 811 | return result; |
| 812 | } |
| 813 | if (type === "damage" && health) |
| 814 | { |
| 815 | const amount = Math.max(0, effect.amount | 0 || 0); |
| 816 | health.current = Math.max(0, (health.current | 0) - amount); |
| 817 | result.healthChanged = true; |
| 818 | return result; |
| 819 | } |
| 820 | |
| 821 | const timed = { |
| 822 | [StatusEffectType.healthRegen]: true, |
| 823 | [StatusEffectType.healthDrain]: true, |
| 824 | [StatusEffectType.foodPoisoning]: true, |
| 825 | [StatusEffectType.staminaRegen]: true, |
| 826 | [StatusEffectType.strengthBonus]: true, |
| 827 | [StatusEffectType.mindBonus]: true, |
| 828 | [StatusEffectType.staminaDrain]: true, |
| 829 | [StatusEffectType.glow]: true, |
| 830 | [StatusEffectType.shrink]: true, |
| 831 | [StatusEffectType.blind]: true |
| 832 | }; |
| 833 | if (!timed[type]) |
| 834 | { return result; } |
| 835 | |
| 836 | const component = ensureStatusEffects(ecs, handle); |
| 837 | applyStatusEffect(component, effect, Date.now()); |
| 838 | result.statusEffectsChanged = true; |
| 839 | if (type === StatusEffectType.glow || type === StatusEffectType.shrink) |
| 840 | { result.appearanceChanged = true; } |
| 841 | return result; |
| 842 | } |
| 843 | |
| 844 | function openBank (world, sessionId, command) |
| 845 | { |
| 846 | const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId); |
| 847 | const position = world.ecs.get(handle, Component.position); |
| 848 | const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); |
| 849 | if (!nearBank(world, position.tileX, position.tileY, dim)) |
| 850 | { throw userError("Stand next to a bank."); } |
| 851 | const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.bank); |
| 852 | return { |
| 853 | events: shove ? [shove] : [], |
| 854 | private: bagView(world.ecs, handle), |
| 855 | bank: true |
| 856 | }; |
| 857 | } |
| 858 | |
| 859 | function bankMove (world, sessionId, command, fromKey, toKey) |
| 860 | { |
| 861 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 862 | requireBank(world, handle); |
| 863 | const inventory = ensureInventory(world.ecs, handle); |
| 864 | const vault = ensureVault(world.ecs, handle); |
| 865 | if (fromKey === "inventory" && toKey === "vault") |
| 866 | { |
| 867 | const slot = inventory.slots[command.slotIndex | 0]; |
| 868 | if (slot?.itemId === ItemId.filledCheque) |
| 869 | { |
| 870 | world.sweepExpiredCheques?.(command.characterId); |
| 871 | const fresh = inventory.slots[command.slotIndex | 0]; |
| 872 | if (!fresh || fresh.itemId !== ItemId.filledCheque) |
| 873 | { throw userError("That cheque has expired."); } |
| 874 | return redeemCheque(world, sessionId, command); |
| 875 | } |
| 876 | } |
| 877 | if (toKey === "vault") |
| 878 | { |
| 879 | const taken = takeFromSlot(inventory.slots, command.slotIndex, command.quantity ?? null); |
| 880 | if (!taken.ok) |
| 881 | { throw userError("That slot is empty."); } |
| 882 | const def = itemDefinition(taken.taken.itemId); |
| 883 | const inserted = insertStackGrowable(vault.slots, taken.taken, def); |
| 884 | inventory.slots = taken.slots; |
| 885 | vault.slots = inserted.slots; |
| 886 | return { events: [], private: bagView(world.ecs, handle), bank: true }; |
| 887 | } |
| 888 | |
| 889 | const vaultSlot = vault.slots[command.slotIndex | 0]; |
| 890 | if (!vaultSlot) |
| 891 | { throw userError("That slot is empty."); } |
| 892 | const def = itemDefinition(vaultSlot.itemId); |
| 893 | const available = stackQuantity(vaultSlot.quantity); |
| 894 | const want = command.quantity == null |
| 895 | ? available |
| 896 | : Math.min(available, Math.max(1, stackQuantity(command.quantity))); |
| 897 | const fit = fitStackQuantity(inventory.slots, { |
| 898 | itemId: vaultSlot.itemId, |
| 899 | quantity: want, |
| 900 | instance: vaultSlot.instance ?? null |
| 901 | }, def); |
| 902 | if (fit <= 0) |
| 903 | { throw userError("Not enough space."); } |
| 904 | const taken = takeFromSlot(vault.slots, command.slotIndex, fit); |
| 905 | if (!taken.ok) |
| 906 | { throw userError("That slot is empty."); } |
| 907 | const inserted = insertStack(inventory.slots, taken.taken, def); |
| 908 | if (!inserted.ok) |
| 909 | { throw userError("Not enough space."); } |
| 910 | vault.slots = taken.slots; |
| 911 | inventory.slots = inserted.slots; |
| 912 | const events = []; |
| 913 | if (fit < want) |
| 914 | { |
| 915 | events.push({ |
| 916 | type: "command-error", |
| 917 | sessionId, |
| 918 | message: "Not enough space." |
| 919 | }); |
| 920 | } |
| 921 | return { events, private: bagView(world.ecs, handle), bank: true }; |
| 922 | } |
| 923 | |
| 924 | function getBlankCheques (world, sessionId, command) |
| 925 | { |
| 926 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 927 | requireBank(world, handle); |
| 928 | const inventory = ensureInventory(world.ecs, handle); |
| 929 | const have = countItemInSlots(inventory.slots, ItemId.blankCheque); |
| 930 | const need = Math.max(0, BLANK_CHEQUE_CARRY_CAP - have); |
| 931 | if (!need) |
| 932 | { return { events: [], private: bagView(world.ecs, handle), bank: true }; } |
| 933 | const def = itemDefinition(ItemId.blankCheque); |
| 934 | const inserted = insertStack(inventory.slots, attachOrigins({ |
| 935 | itemId: ItemId.blankCheque, |
| 936 | quantity: need, |
| 937 | origins: [{ origin: bankIssuedOrigin(BANK_LETTER_AUTHOR), quantity: need }] |
| 938 | }), def); |
| 939 | if (!inserted.ok) |
| 940 | { throw userError("Need inventory space for blank cheques."); } |
| 941 | inventory.slots = inserted.slots; |
| 942 | return { events: [], private: bagView(world.ecs, handle), bank: true }; |
| 943 | } |
| 944 | |
| 945 | function returnBlankCheques (world, sessionId, command) |
| 946 | { |
| 947 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 948 | requireBank(world, handle); |
| 949 | const inventory = ensureInventory(world.ecs, handle); |
| 950 | const slot = inventory.slots[command.slotIndex | 0]; |
| 951 | if (!slot || slot.itemId !== ItemId.blankCheque) |
| 952 | { throw userError("Select blank cheques."); } |
| 953 | const quantity = command.quantity == null ? slot.quantity : Math.min(slot.quantity, Math.max(1, command.quantity | 0)); |
| 954 | const taken = takeFromSlot(inventory.slots, command.slotIndex | 0, quantity); |
| 955 | if (!taken.ok) |
| 956 | { throw userError("Select blank cheques."); } |
| 957 | inventory.slots = taken.slots; |
| 958 | return { events: [], private: bagView(world.ecs, handle), bank: true }; |
| 959 | } |
| 960 | |
| 961 | function writeCheque (world, sessionId, command) |
| 962 | { |
| 963 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 964 | world.sweepExpiredCheques?.(command.characterId); |
| 965 | const inventory = ensureInventory(world.ecs, handle); |
| 966 | const vault = ensureVault(world.ecs, handle); |
| 967 | const slotIndex = command.slotIndex | 0; |
| 968 | const blankSlot = inventory.slots[slotIndex]; |
| 969 | if (!blankSlot || blankSlot.itemId !== ItemId.blankCheque) |
| 970 | { throw userError("Select a blank cheque."); } |
| 971 | const vaultSlot = vault.slots[command.vaultSlotIndex | 0]; |
| 972 | if (!vaultSlot) |
| 973 | { throw userError("Select vault goods to reserve."); } |
| 974 | const def = itemDefinition(vaultSlot.itemId); |
| 975 | if (!def) |
| 976 | { throw userError("Unknown item."); } |
| 977 | const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0); |
| 978 | const available = countIdenticalInSlots(vault.slots, vaultSlot); |
| 979 | if (available < quantity) |
| 980 | { throw userError("Not enough unreserved goods in the vault."); } |
| 981 | if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry)) |
| 982 | { throw userError("Need a free inventory slot for the filled cheque."); } |
| 983 | |
| 984 | const pulled = takeMatchingFromSlots(vault.slots, { |
| 985 | itemId: vaultSlot.itemId, |
| 986 | quantity, |
| 987 | matchStack: vaultSlot |
| 988 | }); |
| 989 | if (!pulled.ok) |
| 990 | { throw userError("Not enough unreserved goods in the vault."); } |
| 991 | |
| 992 | const appearance = world.ecs.get(handle, Component.appearance); |
| 993 | const issuerName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim() |
| 994 | || "Unknown"; |
| 995 | const chequeId = randomUUID(); |
| 996 | const reservedStack = { |
| 997 | itemId: pulled.taken.itemId, |
| 998 | quantity: pulled.taken.quantity, |
| 999 | origins: normalizeOrigins(pulled.taken), |
| 1000 | instance: pulled.taken.instance ?? null, |
| 1001 | chequeId |
| 1002 | }; |
| 1003 | vault.slots = pulled.slots; |
| 1004 | vault.reserved = [...(vault.reserved ?? []).map(cloneStack), reservedStack]; |
| 1005 | |
| 1006 | const filled = attachOrigins({ |
| 1007 | itemId: ItemId.filledCheque, |
| 1008 | quantity: 1, |
| 1009 | origins: [{ origin: writtenOrigin(issuerName), quantity: 1 }], |
| 1010 | instance: { |
| 1011 | kind: "filled-cheque", |
| 1012 | chequeId, |
| 1013 | issuerCharacterId: command.characterId, |
| 1014 | itemId: pulled.taken.itemId, |
| 1015 | quantity: pulled.taken.quantity, |
| 1016 | reservedInstance: pulled.taken.instance ?? null, |
| 1017 | createdAt: Date.now() |
| 1018 | } |
| 1019 | }); |
| 1020 | const blankTaken = takeFromSlot(inventory.slots, slotIndex, 1); |
| 1021 | inventory.slots = blankTaken.slots; |
| 1022 | if (!inventory.slots[slotIndex]) |
| 1023 | { inventory.slots[slotIndex] = filled; } |
| 1024 | else |
| 1025 | { |
| 1026 | const free = inventory.slots.findIndex((entry) => !entry); |
| 1027 | inventory.slots[free] = filled; |
| 1028 | } |
| 1029 | return { events: [], private: bagView(world.ecs, handle) }; |
| 1030 | } |
| 1031 | |
| 1032 | function redeemCheque (world, sessionId, command) |
| 1033 | { |
| 1034 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 1035 | world.sweepExpiredCheques?.(command.characterId); |
| 1036 | requireBank(world, handle); |
| 1037 | const inventory = ensureInventory(world.ecs, handle); |
| 1038 | const vault = ensureVault(world.ecs, handle); |
| 1039 | const slotIndex = command.slotIndex | 0; |
| 1040 | const slot = inventory.slots[slotIndex]; |
| 1041 | if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque") |
| 1042 | { throw userError("Select a filled cheque."); } |
| 1043 | if (chequeIsExpired(slot)) |
| 1044 | { |
| 1045 | world.expireFilledChequePaper?.(command.characterId, slotIndex); |
| 1046 | throw userError("That cheque has expired."); |
| 1047 | } |
| 1048 | |
| 1049 | const chequeId = slot.instance.chequeId; |
| 1050 | const issuerId = slot.instance.issuerCharacterId; |
| 1051 | const goodsDef = itemDefinition(slot.instance.itemId); |
| 1052 | if (!goodsDef) |
| 1053 | { throw userError("Unknown reserved goods."); } |
| 1054 | |
| 1055 | const chequeTaken = takeFromSlot(inventory.slots, slotIndex, 1); |
| 1056 | if (!chequeTaken.ok) |
| 1057 | { throw userError("Select a filled cheque."); } |
| 1058 | inventory.slots = chequeTaken.slots; |
| 1059 | |
| 1060 | let reservedStack = null; |
| 1061 | if (Number(issuerId) === Number(command.characterId)) |
| 1062 | { |
| 1063 | const index = findReservedChequeIndex(vault.reserved, slot.instance); |
| 1064 | if (index < 0) |
| 1065 | { |
| 1066 | inventory.slots[slotIndex] = chequeTaken.taken; |
| 1067 | throw userError("That cheque cannot be redeemed."); |
| 1068 | } |
| 1069 | reservedStack = cloneStack(vault.reserved[index]); |
| 1070 | vault.reserved = vault.reserved.filter((_, i) => i !== index); |
| 1071 | } |
| 1072 | else |
| 1073 | { |
| 1074 | const release = world.releaseChequeReservation?.(issuerId, chequeId, slot.instance); |
| 1075 | if (!release?.ok) |
| 1076 | { |
| 1077 | inventory.slots[slotIndex] = chequeTaken.taken; |
| 1078 | throw userError(release?.error ?? "That cheque cannot be redeemed."); |
| 1079 | } |
| 1080 | reservedStack = release.stack; |
| 1081 | } |
| 1082 | |
| 1083 | const inserted = insertStackGrowable(vault.slots, attachOrigins({ |
| 1084 | itemId: reservedStack.itemId, |
| 1085 | quantity: reservedStack.quantity, |
| 1086 | origins: normalizeOrigins(reservedStack), |
| 1087 | instance: reservedStack.instance ?? null |
| 1088 | }), goodsDef); |
| 1089 | if (!inserted.ok) |
| 1090 | { |
| 1091 | inventory.slots[slotIndex] = chequeTaken.taken; |
| 1092 | if (Number(issuerId) === Number(command.characterId)) |
| 1093 | { vault.reserved = [...(vault.reserved ?? []), reservedStack]; } |
| 1094 | else |
| 1095 | { world.restoreChequeReservation?.(issuerId, reservedStack); } |
| 1096 | throw userError("Your vault cannot hold those goods."); |
| 1097 | } |
| 1098 | vault.slots = inserted.slots; |
| 1099 | return { events: [], private: bagView(world.ecs, handle), bank: true }; |
| 1100 | } |
| 1101 | |
| 1102 | /** Match reserved vault entry by chequeId, or by goods identity for legacy rows that lost chequeId. */ |
| 1103 | export function findReservedChequeIndex (reserved, chequeInstance) |
| 1104 | { |
| 1105 | const list = reserved ?? []; |
| 1106 | const chequeId = chequeInstance?.chequeId; |
| 1107 | if (chequeId != null) |
| 1108 | { |
| 1109 | const byId = list.findIndex((entry) => entry?.chequeId === chequeId); |
| 1110 | if (byId >= 0) |
| 1111 | { return byId; } |
| 1112 | } |
| 1113 | const itemId = chequeInstance?.itemId; |
| 1114 | const quantity = chequeInstance?.quantity | 0; |
| 1115 | if (itemId == null || quantity <= 0) |
| 1116 | { return -1; } |
| 1117 | return list.findIndex((entry) => |
| 1118 | entry |
| 1119 | && entry.chequeId == null |
| 1120 | && entry.itemId === itemId |
| 1121 | && (entry.quantity | 0) === quantity |
| 1122 | ); |
| 1123 | } |
| 1124 | |
| 1125 | function claimInheritance (world, sessionId, command) |
| 1126 | { |
| 1127 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 1128 | requireBank(world, handle); |
| 1129 | const vault = ensureVault(world.ecs, handle); |
| 1130 | const remainder = []; |
| 1131 | for (const stack of command.stacks ?? []) |
| 1132 | { |
| 1133 | const def = itemDefinition(stack.itemId); |
| 1134 | if (!def) |
| 1135 | { |
| 1136 | remainder.push(stack); |
| 1137 | continue; |
| 1138 | } |
| 1139 | const inserted = insertStackGrowable(vault.slots, stack, def); |
| 1140 | if (inserted.ok) |
| 1141 | { vault.slots = inserted.slots; } |
| 1142 | else |
| 1143 | { remainder.push(stack); } |
| 1144 | } |
| 1145 | return { events: [], private: bagView(world.ecs, handle), bank: true, remainder }; |
| 1146 | } |
| 1147 | |
| 1148 | function writeLetter (world, sessionId, command) |
| 1149 | { |
| 1150 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 1151 | const inventory = ensureInventory(world.ecs, handle); |
| 1152 | const slotIndex = command.slotIndex | 0; |
| 1153 | const slot = inventory.slots[slotIndex]; |
| 1154 | if (!slot || slot.itemId !== ItemId.paper) |
| 1155 | { throw userError("Select blank paper."); } |
| 1156 | const body = normalizeLetterBody(command.body); |
| 1157 | const appearance = world.ecs.get(handle, Component.appearance); |
| 1158 | const authorDisplayName = `${appearance?.firstName ?? "Unknown"} ${appearance?.lastName ?? ""}`.trim(); |
| 1159 | const letterStack = attachOrigins({ |
| 1160 | itemId: ItemId.letter, |
| 1161 | quantity: 1, |
| 1162 | origins: [{ origin: writtenOrigin(authorDisplayName), quantity: 1 }], |
| 1163 | instance: { |
| 1164 | kind: "letter", |
| 1165 | letterId: randomUUID(), |
| 1166 | authorCharacterId: command.characterId, |
| 1167 | authorDisplayName, |
| 1168 | body, |
| 1169 | opened: true, |
| 1170 | writtenAt: Date.now() |
| 1171 | } |
| 1172 | }); |
| 1173 | if (slot.quantity <= 1) |
| 1174 | { |
| 1175 | inventory.slots[slotIndex] = letterStack; |
| 1176 | return { events: [], private: bagView(world.ecs, handle) }; |
| 1177 | } |
| 1178 | const free = inventory.slots.findIndex((entry) => !entry); |
| 1179 | if (free < 0) |
| 1180 | { throw userError("Need a free inventory slot for the letter."); } |
| 1181 | slot.quantity -= 1; |
| 1182 | inventory.slots[free] = letterStack; |
| 1183 | return { events: [], private: bagView(world.ecs, handle) }; |
| 1184 | } |
| 1185 | |
| 1186 | function editLetter (world, sessionId, command) |
| 1187 | { |
| 1188 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 1189 | const inventory = ensureInventory(world.ecs, handle); |
| 1190 | const slotIndex = command.slotIndex | 0; |
| 1191 | const slot = inventory.slots[slotIndex]; |
| 1192 | if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter") |
| 1193 | { throw userError("That is not a letter."); } |
| 1194 | if (slot.instance.authorCharacterId !== command.characterId) |
| 1195 | { throw userError("Only the signer can edit this letter."); } |
| 1196 | const appearance = world.ecs.get(handle, Component.appearance); |
| 1197 | const authorDisplayName = `${appearance?.firstName ?? slot.instance.authorDisplayName} ${appearance?.lastName ?? ""}`.trim() |
| 1198 | || slot.instance.authorDisplayName; |
| 1199 | slot.instance = { |
| 1200 | ...slot.instance, |
| 1201 | authorDisplayName, |
| 1202 | body: normalizeLetterBody(command.body), |
| 1203 | writtenAt: Date.now() |
| 1204 | }; |
| 1205 | slot.origins = [{ origin: writtenOrigin(authorDisplayName), quantity: 1 }]; |
| 1206 | delete slot.origin; |
| 1207 | return { events: [], private: bagView(world.ecs, handle) }; |
| 1208 | } |
| 1209 | |
| 1210 | function openLetter (world, sessionId, command) |
| 1211 | { |
| 1212 | const { handle } = world.requireOwnedEntity(sessionId, command.characterId); |
| 1213 | const inventory = ensureInventory(world.ecs, handle); |
| 1214 | const slotIndex = command.slotIndex | 0; |
| 1215 | const slot = inventory.slots[slotIndex]; |
| 1216 | if (!slot || slot.itemId !== ItemId.letter || slot.instance?.kind !== "letter") |
| 1217 | { throw userError("That is not a letter."); } |
| 1218 | if (slot.instance.opened !== false) |
| 1219 | { return { events: [], private: bagView(world.ecs, handle) }; } |
| 1220 | slot.instance = { ...slot.instance, opened: true }; |
| 1221 | return { events: [], private: bagView(world.ecs, handle) }; |
| 1222 | } |
| 1223 | |
| 1224 | function normalizeLetterBody (raw) |
| 1225 | { |
| 1226 | const body = String(raw ?? "").replace(/\r\n/g, "\n").trimEnd(); |
| 1227 | if (body.length > LETTER_MAX_BODY_CHARS) |
| 1228 | { throw userError(`Letters can be at most ${LETTER_MAX_BODY_CHARS} characters.`); } |
| 1229 | return body; |
| 1230 | } |
| 1231 | |
| 1232 | function requireBank (world, handle) |
| 1233 | { |
| 1234 | const position = world.ecs.get(handle, Component.position); |
| 1235 | const dim = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID); |
| 1236 | if (!nearBank(world, position.tileX, position.tileY, dim)) |
| 1237 | { throw userError("Stand next to a bank."); } |
| 1238 | } |
| 1239 | |
| 1240 | function nearBank (world, tileX, tileY, dimensionId = OVERWORLD_ID) |
| 1241 | { |
| 1242 | const dim = normalizeDimensionId(dimensionId); |
| 1243 | for (let dy = -1; dy <= 1; dy++) |
| 1244 | { |
| 1245 | for (let dx = -1; dx <= 1; dx++) |
| 1246 | { |
| 1247 | if (dx === 0 && dy === 0) |
| 1248 | { continue; } |
| 1249 | const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy), dim); |
| 1250 | const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx); |
| 1251 | if (data.blocks[index]?.typeId === BlockType.bank) |
| 1252 | { return true; } |
| 1253 | } |
| 1254 | } |
| 1255 | return false; |
| 1256 | } |
| 1257 | |
| 1258 | function ensureInventory (ecs, handle) |
| 1259 | { |
| 1260 | let inventory = ecs.get(handle, Component.inventory); |
| 1261 | if (!inventory) |
| 1262 | { inventory = ecs.add(handle, Component.inventory, { slots: emptySlots() }); } |
| 1263 | inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots()); |
| 1264 | return inventory; |
| 1265 | } |
| 1266 | |
| 1267 | function ensureEquipment (ecs, handle) |
| 1268 | { |
| 1269 | return ecs.get(handle, Component.equipment) ?? ecs.add(handle, Component.equipment, emptyEquipment()); |
| 1270 | } |
| 1271 | |
| 1272 | function ensureVault (ecs, handle) |
| 1273 | { |
| 1274 | let vault = ecs.get(handle, Component.vault); |
| 1275 | if (!vault) |
| 1276 | { vault = ecs.add(handle, Component.vault, { slots: [], reserved: [] }); } |
| 1277 | if (!Array.isArray(vault.slots)) |
| 1278 | { vault.slots = []; } |
| 1279 | if (!Array.isArray(vault.reserved)) |
| 1280 | { vault.reserved = []; } |
| 1281 | return vault; |
| 1282 | } |
| 1283 | |
| 1284 | function userError (message) |
| 1285 | { |
| 1286 | const error = new Error(message); |
| 1287 | error.userFacing = true; |
| 1288 | return error; |
| 1289 | } |