BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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