BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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