BlueGit

timfa questward

Files

questward / server / src / items / bags.js

bags.js

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