BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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