BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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