BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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